All files / engine/Source/Scene/Model pickModel.js

76.31% Statements 116/152
61.29% Branches 57/93
100% Functions 2/2
75.67% Lines 112/148

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426                                      1x 1x 1x 1x 1x 1x 1x 1x                                                   27x 26x 25x     24x 2x     22x 22x   22x 22x 32x 32x   32x       32x         32x 32x 2x   1x           1x               32x           32x               32x 32x 2x   2x   2x 2x 2x 1x 1x                 2x 1x 25x   25x                                     25x 25x         25x               25x         32x 31x     32x 32x 22x 22x   22x 20x         20x       20x         22x       22x 22x 22x   22x   1x     21x 21x                                 21x 21x 21x   21x 21x 2x 2x     21x 21x   21x       21x 21x 21x       21x   21x                                                   21x       21x 21x 21x   21x 21x 898x 898x 898x   898x 1186x                       1186x                       1186x                         1186x               1186x 21x 19x               22x 3x     19x 19x                   19x                             3558x 3558x 3558x 3558x   3558x 72x                           72x           72x               3558x   3558x 396x                 3558x    
import AttributeCompression from "../../Core/AttributeCompression.js";
import BoundingSphere from "../../Core/BoundingSphere.js";
import Cartesian3 from "../../Core/Cartesian3.js";
import Cartographic from "../../Core/Cartographic.js";
import Check from "../../Core/Check.js";
import ComponentDatatype from "../../Core/ComponentDatatype.js";
import defined from "../../Core/defined.js";
import Ellipsoid from "../../Core/Ellipsoid.js";
import IndexDatatype from "../../Core/IndexDatatype.js";
import IntersectionTests from "../../Core/IntersectionTests.js";
import Ray from "../../Core/Ray.js";
import Matrix4 from "../../Core/Matrix4.js";
import Transforms from "../../Core/Transforms.js";
import VerticalExaggeration from "../../Core/VerticalExaggeration.js";
import AttributeType from "../AttributeType.js";
import SceneMode from "../SceneMode.js";
import VertexAttributeSemantic from "../VertexAttributeSemantic.js";
import ModelUtility from "./ModelUtility.js";
 
const scratchV0 = new Cartesian3();
const scratchV1 = new Cartesian3();
const scratchV2 = new Cartesian3();
const scratchNodeComputedTransform = new Matrix4();
const scratchModelMatrix = new Matrix4();
const scratchcomputedModelMatrix = new Matrix4();
const scratchPickCartographic = new Cartographic();
const scratchBoundingSphere = new BoundingSphere();
 
/**
 * Find an intersection between a ray and the model surface that was rendered. The ray must be given in world coordinates.
 *
 * @param {Model} model The model to pick.
 * @param {Ray} ray The ray to test for intersection.
 * @param {FrameState} frameState The frame state.
 * @param {number} [verticalExaggeration=1.0] A scalar used to exaggerate the height of a position relative to the ellipsoid. If the value is 1.0 there will be no effect.
 * @param {number} [relativeHeight=0.0] The ellipsoid height relative to which a position is exaggerated. If the value is 0.0 the position will be exaggerated relative to the ellipsoid surface.
 * @param {Ellipsoid} [ellipsoid=Ellipsoid.default] The ellipsoid to which the exaggerated position is relative.
 * @param {Cartesian3|undefined} [result] The intersection or <code>undefined</code> if none was found.
 * @returns {Cartesian3|undefined} The intersection or <code>undefined</code> if none was found.
 *
 * @private
 */
export default function pickModel(
  model,
  ray,
  frameState,
  verticalExaggeration,
  relativeHeight,
  ellipsoid,
  result,
) {
  //>>includeStart('debug', pragmas.debug);
  Check.typeOf.object("model", model);
  Check.typeOf.object("ray", ray);
  Check.typeOf.object("frameState", frameState);
  //>>includeEnd('debug');
 
  if (!model._ready || frameState.mode === SceneMode.MORPHING) {
    return;
  }
 
  let minT = Number.MAX_VALUE;
  const sceneGraph = model.sceneGraph;
 
  const nodes = sceneGraph._runtimeNodes;
  for (let i = 0; i < nodes.length; i++) {
    const runtimeNode = nodes[i];
    const node = runtimeNode.node;
 
    let nodeComputedTransform = Matrix4.clone(
      runtimeNode.computedTransform,
      scratchNodeComputedTransform,
    );
    let modelMatrix = Matrix4.clone(
      sceneGraph.computedModelMatrix,
      scratchModelMatrix,
    );
 
    const instances = node.instances;
    if (defined(instances)) {
      if (instances.transformInWorldSpace) {
        // Replicate the multiplication order in LegacyInstancingStageVS.
        modelMatrix = Matrix4.multiplyTransformation(
          model.modelMatrix,
          sceneGraph.components.transform,
          modelMatrix,
        );
 
        nodeComputedTransform = Matrix4.multiplyTransformation(
          sceneGraph.axisCorrectionMatrix,
          runtimeNode.computedTransform,
          nodeComputedTransform,
        );
      }
    }
 
    let computedModelMatrix = Matrix4.multiplyTransformation(
      modelMatrix,
      nodeComputedTransform,
      scratchcomputedModelMatrix,
    );
 
    Iif (frameState.mode !== SceneMode.SCENE3D) {
      computedModelMatrix = Transforms.basisTo2D(
        frameState.mapProjection,
        computedModelMatrix,
        computedModelMatrix,
      );
    }
 
    const transforms = [];
    if (defined(instances)) {
      const transformsCount = instances.attributes[0].count;
      const instanceComponentDatatype =
        instances.attributes[0].componentDatatype;
 
      const transformElements = 12;
      let transformsTypedArray = runtimeNode.transformsTypedArray;
      if (!defined(transformsTypedArray)) {
        const instanceTransformsBuffer = runtimeNode.instancingTransformsBuffer;
        Iif (defined(instanceTransformsBuffer) && frameState.context.webgl2) {
          transformsTypedArray = ComponentDatatype.createTypedArray(
            instanceComponentDatatype,
            transformsCount * transformElements,
          );
          instanceTransformsBuffer.getBufferData(transformsTypedArray);
        }
      }
 
      if (defined(transformsTypedArray)) {
        for (let i = 0; i < transformsCount; i++) {
          const index = i * transformElements;
 
          const transform = new Matrix4(
            transformsTypedArray[index],
            transformsTypedArray[index + 1],
            transformsTypedArray[index + 2],
            transformsTypedArray[index + 3],
            transformsTypedArray[index + 4],
            transformsTypedArray[index + 5],
            transformsTypedArray[index + 6],
            transformsTypedArray[index + 7],
            transformsTypedArray[index + 8],
            transformsTypedArray[index + 9],
            transformsTypedArray[index + 10],
            transformsTypedArray[index + 11],
            0,
            0,
            0,
            1,
          );
 
          if (instances.transformInWorldSpace) {
            Matrix4.multiplyTransformation(
              transform,
              nodeComputedTransform,
              transform,
            );
            Matrix4.multiplyTransformation(modelMatrix, transform, transform);
          } else E{
            Matrix4.multiplyTransformation(
              transform,
              computedModelMatrix,
              transform,
            );
          }
          transforms.push(transform);
        }
      }
    }
 
    if (transforms.length === 0) {
      transforms.push(computedModelMatrix);
    }
 
    const primitivesLength = runtimeNode.runtimePrimitives.length;
    for (let j = 0; j < primitivesLength; j++) {
      const runtimePrimitive = runtimeNode.runtimePrimitives[j];
      const primitive = runtimePrimitive.primitive;
 
      if (defined(runtimePrimitive.boundingSphere) && !defined(instances)) {
        const boundingSphere = BoundingSphere.transform(
          runtimePrimitive.boundingSphere,
          computedModelMatrix,
          scratchBoundingSphere,
        );
        const boundsIntersection = IntersectionTests.raySphere(
          ray,
          boundingSphere,
        );
        Iif (!defined(boundsIntersection)) {
          continue;
        }
      }
 
      const positionAttribute = ModelUtility.getAttributeBySemantic(
        primitive,
        VertexAttributeSemantic.POSITION,
      );
      const byteOffset = positionAttribute.byteOffset;
      const byteStride = positionAttribute.byteStride;
      const vertexCount = positionAttribute.count;
 
      if (!defined(primitive.indices)) {
        // Point clouds
        continue;
      }
 
      let indices = primitive.indices.typedArray;
      Iif (!defined(indices)) {
        const indicesBuffer = primitive.indices.buffer;
        const indicesCount = primitive.indices.count;
        const indexDatatype = primitive.indices.indexDatatype;
        if (defined(indicesBuffer) && frameState.context.webgl2) {
          if (indexDatatype === IndexDatatype.UNSIGNED_BYTE) {
            indices = new Uint8Array(indicesCount);
          } else if (indexDatatype === IndexDatatype.UNSIGNED_SHORT) {
            indices = new Uint16Array(indicesCount);
          } else if (indexDatatype === IndexDatatype.UNSIGNED_INT) {
            indices = new Uint32Array(indicesCount);
          }
 
          indicesBuffer.getBufferData(indices);
        }
      }
 
      let vertices = positionAttribute.typedArray;
      let componentDatatype = positionAttribute.componentDatatype;
      let attributeType = positionAttribute.type;
 
      const quantization = positionAttribute.quantization;
      if (defined(quantization)) {
        componentDatatype = positionAttribute.quantization.componentDatatype;
        attributeType = positionAttribute.quantization.type;
      }
 
      const numComponents = AttributeType.getNumberOfComponents(attributeType);
      const bytes = ComponentDatatype.getSizeInBytes(componentDatatype);
      const isInterleaved =
        !defined(vertices) &&
        defined(byteStride) &&
        byteStride !== numComponents * bytes;
 
      let elementStride = numComponents;
      let offset = 0;
      Iif (isInterleaved) {
        elementStride = byteStride / bytes;
        offset = byteOffset / bytes;
      }
      const elementCount = vertexCount * elementStride;
 
      Iif (!defined(vertices)) {
        const verticesBuffer = positionAttribute.buffer;
 
        if (defined(verticesBuffer) && frameState.context.webgl2) {
          vertices = ComponentDatatype.createTypedArray(
            componentDatatype,
            elementCount,
          );
          verticesBuffer.getBufferData(
            vertices,
            isInterleaved ? 0 : byteOffset,
            0,
            elementCount,
          );
        }
 
        if (quantization && positionAttribute.normalized) {
          vertices = AttributeCompression.dequantize(
            vertices,
            componentDatatype,
            attributeType,
            vertexCount,
          );
        }
      }
 
      Iif (!defined(indices) || !defined(vertices)) {
        return;
      }
 
      ellipsoid = ellipsoid ?? Ellipsoid.default;
      verticalExaggeration = verticalExaggeration ?? 1.0;
      relativeHeight = relativeHeight ?? 0.0;
 
      const indicesLength = indices.length;
      for (let i = 0; i < indicesLength; i += 3) {
        const i0 = indices[i];
        const i1 = indices[i + 1];
        const i2 = indices[i + 2];
 
        for (const instanceTransform of transforms) {
          const v0 = getVertexPosition(
            vertices,
            i0,
            offset,
            elementStride,
            quantization,
            instanceTransform,
            verticalExaggeration,
            relativeHeight,
            ellipsoid,
            scratchV0,
          );
          const v1 = getVertexPosition(
            vertices,
            i1,
            offset,
            elementStride,
            quantization,
            instanceTransform,
            verticalExaggeration,
            relativeHeight,
            ellipsoid,
            scratchV1,
          );
          const v2 = getVertexPosition(
            vertices,
            i2,
            offset,
            elementStride,
            quantization,
            instanceTransform,
            verticalExaggeration,
            relativeHeight,
            ellipsoid,
            scratchV2,
          );
 
          const t = IntersectionTests.rayTriangleParametric(
            ray,
            v0,
            v1,
            v2,
            model.backFaceCulling ?? true,
          );
 
          if (defined(t)) {
            if (t < minT && t >= 0.0) {
              minT = t;
            }
          }
        }
      }
    }
  }
 
  if (minT === Number.MAX_VALUE) {
    return undefined;
  }
 
  result = Ray.getPoint(ray, minT, result);
  Iif (frameState.mode !== SceneMode.SCENE3D) {
    Cartesian3.fromElements(result.y, result.z, result.x, result);
 
    const projection = frameState.mapProjection;
    const ellipsoid = projection.ellipsoid;
 
    const cartographic = projection.unproject(result, scratchPickCartographic);
    ellipsoid.cartographicToCartesian(cartographic, result);
  }
 
  return result;
}
 
function getVertexPosition(
  vertices,
  index,
  offset,
  numElements,
  quantization,
  instanceTransform,
  verticalExaggeration,
  relativeHeight,
  ellipsoid,
  result,
) {
  const i = offset + index * numElements;
  result.x = vertices[i];
  result.y = vertices[i + 1];
  result.z = vertices[i + 2];
 
  if (defined(quantization)) {
    Iif (quantization.octEncoded) {
      result = AttributeCompression.octDecodeInRange(
        result,
        quantization.normalizationRange,
        result,
      );
 
      if (quantization.octEncodedZXY) {
        const x = result.x;
        result.x = result.z;
        result.z = result.y;
        result.y = x;
      }
    } else {
      result = Cartesian3.multiplyComponents(
        result,
        quantization.quantizedVolumeStepSize,
        result,
      );
 
      result = Cartesian3.add(
        result,
        quantization.quantizedVolumeOffset,
        result,
      );
    }
  }
 
  result = Matrix4.multiplyByPoint(instanceTransform, result, result);
 
  if (verticalExaggeration !== 1.0) {
    VerticalExaggeration.getPosition(
      result,
      ellipsoid,
      verticalExaggeration,
      relativeHeight,
      result,
    );
  }
 
  return result;
}