"use strict";
/*---------------------------------------------------------------------------------------------
* Copyright (c) Bentley Systems, Incorporated. All rights reserved.
* See LICENSE.md in the project root for license terms and full copyright notice.
*--------------------------------------------------------------------------------------------*/
/** @packageDocumentation
 * @module Tiles
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.TileDrawArgs = void 0;
const core_geometry_1 = require("@itwin/core-geometry");
const core_common_1 = require("@itwin/core-common");
const GraphicBranch_1 = require("../render/GraphicBranch");
const CoordSystem_1 = require("../CoordSystem");
const scratchRange = new core_geometry_1.Range3d();
const scratchPoint = core_geometry_1.Point3d.create();
const scratchPoint4d = core_geometry_1.Point4d.create();
const scratchXRange = core_geometry_1.Range1d.createNull();
const scratchYRange = core_geometry_1.Range1d.createNull();
const scratchMatrix4d = core_geometry_1.Matrix4d.createIdentity();
/**
 * Provides context used when selecting and drawing [[Tile]]s.
 * @see [[TileTree.selectTiles]]
 * @see [[TileTree.draw]]
 * @public
 * @extensions
 */
class TileDrawArgs {
    /** Overrides applied to the view's [ViewFlags]($common) when drawing the tiles. */
    get viewFlagOverrides() { return this.graphics.viewFlagOverrides; }
    /** If defined, replaces the view's own symbology overrides when drawing the tiles. */
    get symbologyOverrides() { return this.graphics.symbologyOverrides; }
    /** Compute the size in pixels of the specified tile at the point on its bounding sphere closest to the camera. */
    getPixelSize(tile) {
        const sizeFromProjection = this.getPixelSizeFromProjection(tile);
        if (undefined !== sizeFromProjection)
            return sizeFromProjection;
        const radius = this.getTileRadius(tile); // use a sphere to test pixel size. We don't know the orientation of the image within the bounding box.
        const center = this.getTileCenter(tile);
        const pixelSizeAtPt = this.computePixelSizeInMetersAtClosestPoint(center, radius);
        return 0 !== pixelSizeAtPt ? this.context.adjustPixelSizeForLOD(radius / pixelSizeAtPt) : 1.0e-3;
    }
    /** If the tile provides corners (from an OBB) then this produces most accurate representation of the tile size */
    getPixelSizeFromProjection(tile) {
        const sizeProjectionCorners = tile.getSizeProjectionCorners();
        if (!sizeProjectionCorners)
            return undefined;
        /* For maps or global reality models we use the projected screen rectangle rather than sphere to calculate pixel size to avoid excessive tiles at horizon.  */
        const tileToView = this.worldToViewMap.transform0.multiplyMatrixMatrix(core_geometry_1.Matrix4d.createTransform(this.location, scratchMatrix4d), scratchMatrix4d);
        scratchXRange.setNull();
        scratchYRange.setNull();
        let behindEye = false;
        for (const corner of sizeProjectionCorners) {
            const viewCorner = tileToView.multiplyPoint3d(corner, 1, scratchPoint4d);
            if (viewCorner.w < 0.0) {
                behindEye = true;
                break;
            }
            scratchXRange.extendX(viewCorner.x / viewCorner.w);
            scratchYRange.extendX(viewCorner.y / viewCorner.w);
        }
        if (behindEye)
            return undefined;
        return scratchXRange.isNull ? 1.0E-3 : this.context.adjustPixelSizeForLOD(Math.sqrt(scratchXRange.length() * scratchYRange.length()));
    }
    /** Compute the size in meters of one pixel at the point on the tile's bounding sphere closest to the camera. */
    getPixelSizeInMetersAtClosestPoint(tile) {
        const radius = this.getTileRadius(tile); // use a sphere to test pixel size. We don't know the orientation of the image within the bounding box.
        const center = this.getTileCenter(tile);
        const pixelSizeAtPt = this.computePixelSizeInMetersAtClosestPoint(center, radius);
        return 0 !== pixelSizeAtPt ? this.context.adjustPixelSizeForLOD(pixelSizeAtPt) : 1.0e-3;
    }
    /** Compute the size in meters of one pixel at the point on a sphere closest to the camera.
     * Device scaling is not applied.
     */
    computePixelSizeInMetersAtClosestPoint(center, radius) {
        if (this.context.viewport.view.is3d() && this.context.viewport.isCameraOn && this._nearFrontCenter) {
            const toFront = core_geometry_1.Vector3d.createStartEnd(center, this._nearFrontCenter);
            const viewZ = this.context.viewport.rotation.rowZ();
            // If the sphere overlaps the near front plane just use near front point.  This also handles behind eye conditions.
            if (viewZ.dotProduct(toFront) < radius) {
                center = this._nearFrontCenter;
            }
            else {
                // Find point on sphere closest to eye.
                const toEye = center.unitVectorTo(this.context.viewport.view.camera.eye);
                if (toEye) { // Only if tile is not already behind the eye.
                    toEye.scaleInPlace(radius);
                    center.addInPlace(toEye);
                }
            }
        }
        const viewPt = this.worldToViewMap.transform0.multiplyPoint3dQuietNormalize(center);
        const viewPt2 = new core_geometry_1.Point3d(viewPt.x + 1.0, viewPt.y, viewPt.z);
        return this.worldToViewMap.transform1.multiplyPoint3dQuietNormalize(viewPt).distance(this.worldToViewMap.transform1.multiplyPoint3dQuietNormalize(viewPt2));
    }
    /** Compute this size of a sphere on screen in pixels */
    getRangePixelSize(range) {
        const transformedRange = this.location.multiplyRange(range, scratchRange);
        const center = transformedRange.localXYZToWorld(.5, .5, .5, scratchPoint);
        const radius = transformedRange.diagonal().magnitude();
        const viewPt = this.worldToViewMap.transform0.multiplyPoint3dQuietNormalize(center);
        const viewPt2 = new core_geometry_1.Point3d(viewPt.x + 1.0, viewPt.y, viewPt.z);
        const pixelSizeAtPt = this.worldToViewMap.transform1.multiplyPoint3dQuietNormalize(viewPt).distance(this.worldToViewMap.transform1.multiplyPoint3dQuietNormalize(viewPt2));
        return 0 !== pixelSizeAtPt ? radius / pixelSizeAtPt : 1.0e-3;
    }
    /** @internal */
    getTileGraphics(tile) {
        return tile.produceGraphics();
    }
    /** The planes of the viewing frustum, used for frustum culling. */
    get frustumPlanes() {
        return this._frustumPlanes !== undefined ? this._frustumPlanes : this.context.frustumPlanes;
    }
    /** Provides conversions between [[CoordSystem.World]] and [[CoordSystem.View]]. */
    get worldToViewMap() {
        return this.viewingSpace.worldToViewMap;
    }
    computePixelSizeScaleFactor() {
        // Check to see if a model display transform with non-uniform scaling is being used.
        const mat = this.context.viewport.view.modelDisplayTransformProvider?.getModelDisplayTransform(this.tree.modelId)?.transform.matrix;
        if (!mat)
            return 1;
        const scale = [0, 1, 2].map((x) => mat.getColumn(x).magnitude());
        if (Math.abs(scale[0] - scale[1]) <= core_geometry_1.Geometry.smallMetricDistance && Math.abs(scale[0] - scale[2]) <= core_geometry_1.Geometry.smallMetricDistance)
            return 1;
        // If the component with the largest scale is not the same as the component with the largest tile range use it to adjust the pixel size.
        const rangeDiag = this.tree.range.diagonal();
        let maxS = 0;
        let maxR = 0;
        if (scale[0] > scale[1])
            maxS = (scale[0] > scale[2] ? 0 : 2);
        else
            maxS = (scale[1] > scale[2] ? 1 : 2);
        if (rangeDiag.x > rangeDiag.y)
            maxR = (rangeDiag.x > rangeDiag.z ? 0 : 2);
        else
            maxR = (rangeDiag.y > rangeDiag.z ? 1 : 2);
        return maxS !== maxR ? scale[maxS] : 1;
    }
    /** Constructor */
    constructor(params) {
        /** Holds the tile graphics to be drawn. */
        this.graphics = new GraphicBranch_1.GraphicBranch();
        /** Tiles that we want to draw and that are ready to draw. May not actually be selected, e.g. if sibling tiles are not yet ready. */
        this.readyTiles = new Set();
        /** Tiles whose contents should be kept in memory regardless of whether or not they are selected for display.
         * @internal
         */
        this.touchedTiles = new Set();
        const { location, tree, context, now, viewFlagOverrides, clipVolume, parentsAndChildrenExclusive, symbologyOverrides } = params;
        this.location = location;
        this.tree = tree;
        this.context = context;
        this.now = now;
        this._appearanceProvider = params.appearanceProvider;
        this.hiddenLineSettings = params.hiddenLineSettings;
        this.animationTransformNodeId = params.animationTransformNodeId;
        this.groupNodeId = params.groupNodeId;
        this.boundingRange = params.boundingRange;
        this.maximumScreenSpaceError = params.maximumScreenSpaceError ?? 16; // 16 is Cesium's default.
        this.transformFromIModel = params.transformFromIModel;
        // Do not cull tiles based on clip volume if tiles outside clip are supposed to be drawn but in a different color.
        if (undefined !== clipVolume && !context.viewport.view.displayStyle.settings.clipStyle.outsideColor)
            this.clipVolume = clipVolume;
        this.graphics.setViewFlagOverrides(viewFlagOverrides);
        this.graphics.symbologyOverrides = symbologyOverrides;
        this.graphics.animationId = tree.modelId;
        this.viewingSpace = context.viewingSpace;
        this._frustumPlanes = core_common_1.FrustumPlanes.fromFrustum(this.viewingSpace.getFrustum());
        this.planarClassifier = context.getPlanarClassifierForModel(tree.modelId);
        this.drape = context.getTextureDrapeForModel(tree.modelId);
        // NB: If the tile tree has its own clip, do not also apply the view's clip.
        if (context.viewFlags.clipVolume && false !== viewFlagOverrides.clipVolume && undefined === clipVolume) {
            const outsideClipColor = context.viewport.displayStyle.settings.clipStyle.outsideColor;
            this.viewClip = undefined === outsideClipColor ? context.viewport.view.getViewClip() : undefined;
        }
        this.parentsAndChildrenExclusive = parentsAndChildrenExclusive;
        if (context.viewport.isCameraOn)
            this._nearFrontCenter = context.viewport.getFrustum(CoordSystem_1.CoordSystem.World).frontCenter;
        this.pixelSizeScaleFactor = this.computePixelSizeScaleFactor();
    }
    /** A multiplier applied to a [[Tile]]'s `maximumSize` property to adjust level of detail.
     * @see [[Viewport.tileSizeModifier]].
     * @public
     */
    get tileSizeModifier() { return this.context.viewport.tileSizeModifier; }
    /** @internal */
    getTileCenter(tile) { return this.location.multiplyPoint3d(tile.center); }
    /** @internal */
    getTileRadius(tile) {
        let range = tile.range.clone(scratchRange);
        if (tile.tree.is2d) {
            // 2d tiles have a fixed Z range of [-1, 1]. Sometimes (e.g., hypermodeling) we draw them within a 3d view. Prevent Z from artificially expanding the radius.
            range.low.z = range.high.z = 0;
        }
        range = this.location.multiplyRange(range, range);
        return 0.5 * range.low.distance(range.high);
    }
    /** @internal */
    get clip() {
        return undefined !== this.clipVolume ? this.clipVolume.clipVector : undefined;
    }
    /** Add a provider to supplement or override the symbology overrides for the view.
     * @note If a provider already exists, the new provider will be chained such that it sees the base overrides
     * after they have potentially been modified by the existing provider.
     * @public
     */
    addAppearanceProvider(provider) {
        this._appearanceProvider = this._appearanceProvider ? core_common_1.FeatureAppearanceProvider.chain(this._appearanceProvider, provider) : provider;
    }
    /** Optionally customizes aspects of the view's [[FeatureSymbology.Overrides]]. */
    get appearanceProvider() {
        return this._appearanceProvider;
    }
    /** @internal */
    produceGraphics() {
        return this._produceGraphicBranch(this.graphics);
    }
    /** @internal */
    get secondaryClassifiers() {
        return undefined;
    }
    /** @internal */
    _produceGraphicBranch(graphics) {
        if (graphics.isEmpty)
            return undefined;
        const opts = {
            iModel: this.tree.iModel,
            transformFromIModel: this.transformFromIModel,
            clipVolume: this.clipVolume,
            classifierOrDrape: this.planarClassifier ?? this.drape,
            appearanceProvider: this.appearanceProvider,
            hline: this.hiddenLineSettings,
            secondaryClassifiers: this.secondaryClassifiers,
        };
        let graphic = this.context.createGraphicBranch(graphics, this.location, opts);
        if (undefined !== this.animationTransformNodeId)
            graphic = this.context.renderSystem.createAnimationTransformNode(graphic, this.animationTransformNodeId);
        if (undefined !== this.groupNodeId) {
            const branch = new GraphicBranch_1.GraphicBranch();
            branch.add(graphic);
            branch.groupNodeId = this.groupNodeId;
            graphic = this.context.createGraphicBranch(branch, core_geometry_1.Transform.identity);
        }
        return graphic;
    }
    /** Output graphics for all accumulated tiles. */
    drawGraphics() {
        const graphics = this.produceGraphics();
        if (undefined !== graphics)
            this.context.outputGraphic(graphics);
    }
    /** Output graphics of the specified type for all accumulated tiles. */
    drawGraphicsWithType(graphicType, graphics) {
        const branch = this._produceGraphicBranch(graphics);
        if (undefined !== branch)
            this.context.withGraphicType(graphicType, () => this.context.outputGraphic(branch));
    }
    /** Indicate that graphics for the specified tile are desired but not yet available. Subsequently a request will be enqueued to load the tile's graphics. */
    insertMissing(tile) {
        this.context.insertMissingTile(tile);
    }
    /** Indicate that some requested child tiles are not yet loaded. */
    markChildrenLoading() {
        this.context.markChildrenLoading();
    }
    /** Indicate that the specified tile is being used for some purpose by the [[SceneContext]]'s [[Viewport]]. Typically "used" means "displayed", but the exact meaning is up to the [[TileTree]] - for example, "used" might also mean that the tile's children are being used. A tile that is "in use" by any [[Viewport]] will not be discarded. */
    markUsed(tile) {
        tile.usageMarker.mark(this.context.viewport, this.now);
    }
    /** Indicate that the specified tile should be displayed and that its graphics are ready to be displayed. The number of "ready" tiles is used in conjunction with the number of "missing" tiles to convey to the user how complete the current view is.
     * @see [[insertMissing]]
     */
    markReady(tile) {
        this.readyTiles.add(tile);
    }
    /** Invoked by [[TileTree.selectTiles]]. This exists chiefly for [[SolarShadowMap]].
     * @internal
     */
    processSelectedTiles(_tiles) { }
    /* @internal */
    get maxRealityTreeSelectionCount() { return undefined; }
}
exports.TileDrawArgs = TileDrawArgs;
//# sourceMappingURL=TileDrawArgs.js.map