All files / engine/Source/Scene I3SGeometry.js

96.96% Statements 160/165
91.54% Branches 65/71
90% Functions 9/10
96.91% Lines 157/162

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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478                                    15x 15x       15x 12x       3x     15x 15x 15x 15x   15x     1x                 9x                       2x                                         1x 15x 15x 14x 14x       1x 1x 1x 1x 1x     169x 169x         169x         169x     1x 1x 1x   1x 1x 1x 1x   1x 1x 1x                         1x 8x         8x   8x 8x 8x 8x           8x             8x 8x       8x 4x   4x     8x   96x 48x 48x 48x   48x 48x 48x     96x           96x           96x                 96x         84x     12x 12x 12x     12x     12x   12x 12x 12x 6x 6x     6x     6x     6x     6x 2x 2x 2x 4x         4x 4x 4x         8x 6x                     2x               14x 14x 14x 49x 42x   7x     14x           1x                     10x               10x   10x 10x       8x 8x 8x       8x 8x   8x       1x 1x     1x   1x 1x 1x         1x 1x 1x       2x 2x 1x 1x           1x       1x             8x       7x       8x 7x         2x   1x 1x     1x   10x   6x     10x 10x 10x   10x 2x             2x           2x                   10x 10x 10x 10x 10x 10x 10x       12x 12x   11x 11x 11x   11x 11x   2x 1x   9x   5x         10x                                             10x        
import Cartesian3 from "../Core/Cartesian3.js";
import clone from "../Core/clone.js";
import defined from "../Core/defined.js";
import Matrix3 from "../Core/Matrix3.js";
import srgbToLinear from "../Core/srgbToLinear.js";
 
/**
 * This class implements an I3S Geometry. Each I3SGeometry
 * generates an in memory glTF to be used as content for a Cesium3DTile
 * <p>
 * Do not construct this directly, instead access tiles through {@link I3SNode}.
 * </p>
 * @alias I3SGeometry
 * @internalConstructor
 * @privateParam {I3SNode} parent The parent of that geometry
 * @privateParam {string} uri The uri to load the data from
 */
function I3SGeometry(parent, uri) {
  const dataProvider = parent._dataProvider;
  const layer = parent._layer;
 
  let resource;
 
  if (defined(parent._nodeIndex)) {
    resource = layer.resource.getDerivedResource({
      url: `nodes/${parent._data.mesh.geometry.resource}/${uri}`,
    });
  } else {
    resource = parent.resource.getDerivedResource({ url: uri });
  }
 
  this._parent = parent;
  this._dataProvider = dataProvider;
  this._layer = layer;
  this._resource = resource;
 
  this._customAttributes = undefined;
}
 
Object.defineProperties(I3SGeometry.prototype, {
  /**
   * Gets the resource for the geometry
   * @memberof I3SGeometry.prototype
   * @type {Resource}
   * @readonly
   */
  resource: {
    get: function () {
      return this._resource;
    },
  },
 
  /**
   * Gets the I3S data for this object.
   * @memberof I3SGeometry.prototype
   * @type {object}
   * @readonly
   */
  data: {
    get: function () {
      return this._data;
    },
  },
  /**
   * Gets the custom attributes of the geometry.
   * @memberof I3SGeometry.prototype
   * @type {object}
   * @readonly
   */
  customAttributes: {
    get: function () {
      return this._customAttributes;
    },
  },
});
 
/**
 * Loads the content.
 * @returns {Promise<object>} A promise that is resolved when the geometry data is loaded
 * @private
 */
I3SGeometry.prototype.load = function () {
  const that = this;
  return this._dataProvider._loadBinary(this._resource).then(function (data) {
    that._data = data;
    return data;
  });
};
 
const scratchAb = new Cartesian3();
const scratchAp1 = new Cartesian3();
const scratchAp2 = new Cartesian3();
const scratchCp1 = new Cartesian3();
const scratchCp2 = new Cartesian3();
 
function sameSide(p1, p2, a, b) {
  const ab = Cartesian3.subtract(b, a, scratchAb);
  const cp1 = Cartesian3.cross(
    ab,
    Cartesian3.subtract(p1, a, scratchAp1),
    scratchCp1,
  );
  const cp2 = Cartesian3.cross(
    ab,
    Cartesian3.subtract(p2, a, scratchAp2),
    scratchCp2,
  );
  return Cartesian3.dot(cp1, cp2) >= 0;
}
 
const scratchV0 = new Cartesian3();
const scratchV1 = new Cartesian3();
const scratchV2 = new Cartesian3();
 
const scratchV0V1 = new Cartesian3();
const scratchV0V2 = new Cartesian3();
const scratchCrossProd = new Cartesian3();
const scratchNormal = new Cartesian3();
 
const scratchV0p = new Cartesian3();
const scratchV1p = new Cartesian3();
const scratchV2p = new Cartesian3();
 
/**
 * Find a triangle touching the point [px, py, pz], then return the vertex closest to the search point
 * @param {number} px The x component of the point to query
 * @param {number} py The y component of the point to query
 * @param {number} pz The z component of the point to query
 * @returns {object} A structure containing the index of the closest point,
 * the squared distance from the queried point to the point that is found,
 * the distance from the queried point to the point that is found,
 * the queried position in local space,
 * the closest position in local space
 */
I3SGeometry.prototype.getClosestPointIndexOnTriangle = function (px, py, pz) {
  Eif (
    defined(this._customAttributes) &&
    defined(this._customAttributes.positions)
  ) {
    // Convert queried position to local
    const position = new Cartesian3(px, py, pz);
 
    position.x -= this._customAttributes.cartesianCenter.x;
    position.y -= this._customAttributes.cartesianCenter.y;
    position.z -= this._customAttributes.cartesianCenter.z;
    Matrix3.multiplyByVector(
      this._customAttributes.parentRotation,
      position,
      position,
    );
 
    let bestTriDist = Number.MAX_VALUE;
    let bestTri;
    let bestDistSq;
    let bestIndex;
    let bestPt;
 
    // Brute force lookup, @TODO: this can be improved with a spatial partitioning search system
    const positions = this._customAttributes.positions;
    const indices = this._customAttributes.indices;
 
    // We may have indexed or non-indexed triangles here
    let triCount;
    if (defined(indices)) {
      triCount = indices.length;
    } else {
      triCount = positions.length / 3;
    }
 
    for (let triIndex = 0; triIndex < triCount; triIndex++) {
      let i0, i1, i2;
      if (defined(indices)) {
        i0 = indices[triIndex];
        i1 = indices[triIndex + 1];
        i2 = indices[triIndex + 2];
      } else {
        i0 = triIndex * 3;
        i1 = triIndex * 3 + 1;
        i2 = triIndex * 3 + 2;
      }
 
      const v0 = Cartesian3.fromElements(
        positions[i0 * 3],
        positions[i0 * 3 + 1],
        positions[i0 * 3 + 2],
        scratchV0,
      );
      const v1 = Cartesian3.fromElements(
        positions[i1 * 3],
        positions[i1 * 3 + 1],
        positions[i1 * 3 + 2],
        scratchV1,
      );
      const v2 = new Cartesian3(
        positions[i2 * 3],
        positions[i2 * 3 + 1],
        positions[i2 * 3 + 2],
        scratchV2,
      );
 
      // Check how the point is positioned relative to the triangle.
      // This will tell us whether the projection of the point in the triangle's plane lands in the triangle
      if (
        !sameSide(position, v0, v1, v2) ||
        !sameSide(position, v1, v0, v2) ||
        !sameSide(position, v2, v0, v1)
      ) {
        continue;
      }
      // Because of precision issues, we can't always reliably tell if the point lands directly on the face, so the most robust way is just to find the closest one
      const v0v1 = Cartesian3.subtract(v1, v0, scratchV0V1);
      const v0v2 = Cartesian3.subtract(v2, v0, scratchV0V2);
      const crossProd = Cartesian3.cross(v0v1, v0v2, scratchCrossProd);
 
      // Skip "triangles" with 3 colinear points
      Iif (Cartesian3.magnitude(crossProd) === 0) {
        continue;
      }
      const normal = Cartesian3.normalize(crossProd, scratchNormal);
 
      const v0p = Cartesian3.subtract(position, v0, scratchV0p);
      const normalDist = Math.abs(Cartesian3.dot(v0p, normal));
      if (normalDist < bestTriDist) {
        bestTriDist = normalDist;
        bestTri = triIndex;
 
        // Found a triangle, return the index of the closest point
        const d0 = Cartesian3.magnitudeSquared(
          Cartesian3.subtract(position, v0, v0p),
        );
        const d1 = Cartesian3.magnitudeSquared(
          Cartesian3.subtract(position, v1, scratchV1p),
        );
        const d2 = Cartesian3.magnitudeSquared(
          Cartesian3.subtract(position, v2, scratchV2p),
        );
        if (d0 < d1 && d0 < d2) {
          bestIndex = i0;
          bestPt = v0;
          bestDistSq = d0;
        } else Iif (d1 < d2) {
          bestIndex = i1;
          bestPt = v1;
          bestDistSq = d1;
        } else {
          bestIndex = i2;
          bestPt = v2;
          bestDistSq = d2;
        }
      }
    }
 
    if (defined(bestTri)) {
      return {
        index: bestIndex,
        distanceSquared: bestDistSq,
        distance: Math.sqrt(bestDistSq),
        queriedPosition: position,
        closestPosition: Cartesian3.clone(bestPt),
      };
    }
  }
 
  // No hits found
  return {
    index: -1,
    distanceSquared: Number.Infinity,
    distance: Number.Infinity,
  };
};
 
function convertColorFactor(factor) {
  const convertedFactor = [];
  const length = factor.length;
  for (let i = 0; i < length; i++) {
    if (i < 3) {
      convertedFactor.push(srgbToLinear(factor[i]));
    } else {
      convertedFactor.push(factor[i]);
    }
  }
  return convertedFactor;
}
 
/**
 * @private
 */
I3SGeometry.prototype._generateGltf = function (
  nodesInScene,
  nodes,
  meshes,
  buffers,
  bufferViews,
  accessors,
  extensions,
  extensionsUsed,
) {
  // Get the material definition
  let gltfMaterial = {
    pbrMetallicRoughness: {
      metallicFactor: 0.0,
    },
    doubleSided: true,
    name: "Material",
  };
 
  let isTextured = false;
  let materialDefinition;
  let texturePath = "";
  if (
    defined(this._parent._data.mesh) &&
    defined(this._layer._data.materialDefinitions)
  ) {
    const materialInfo = this._parent._data.mesh.material;
    const materialIndex = materialInfo.definition;
    Eif (
      materialIndex >= 0 &&
      materialIndex < this._layer._data.materialDefinitions.length
    ) {
      materialDefinition = this._layer._data.materialDefinitions[materialIndex];
      gltfMaterial = materialDefinition;
 
      if (
        defined(gltfMaterial.pbrMetallicRoughness) &&
        defined(gltfMaterial.pbrMetallicRoughness.baseColorTexture)
      ) {
        isTextured = true;
        gltfMaterial.pbrMetallicRoughness.baseColorTexture.index = 0;
 
        // Choose the JPG for the texture
        let textureName = "0";
 
        Eif (defined(this._layer._data.textureSetDefinitions)) {
          for (
            let defIndex = 0;
            defIndex < this._layer._data.textureSetDefinitions.length;
            defIndex++
          ) {
            const textureSetDefinition =
              this._layer._data.textureSetDefinitions[defIndex];
            for (
              let formatIndex = 0;
              formatIndex < textureSetDefinition.formats.length;
              formatIndex++
            ) {
              const textureFormat = textureSetDefinition.formats[formatIndex];
              if (textureFormat.format === "jpg") {
                textureName = textureFormat.name;
                break;
              }
            }
          }
        }
 
        Eif (
          defined(this._parent._data.mesh) &&
          this._parent._data.mesh.material.resource >= 0
        ) {
          texturePath = this._layer.resource.getDerivedResource({
            url: `nodes/${this._parent._data.mesh.material.resource}/textures/${textureName}`,
          }).url;
        }
      }
 
      // Convert color factors from sRGB to linear color space
      if (
        defined(gltfMaterial.pbrMetallicRoughness) &&
        defined(gltfMaterial.pbrMetallicRoughness.baseColorFactor)
      ) {
        gltfMaterial.pbrMetallicRoughness.baseColorFactor = convertColorFactor(
          gltfMaterial.pbrMetallicRoughness.baseColorFactor,
        );
      }
      if (defined(gltfMaterial.emissiveFactor)) {
        gltfMaterial.emissiveFactor = convertColorFactor(
          gltfMaterial.emissiveFactor,
        );
      }
    }
  } else if (defined(this._parent._data.textureData)) {
    // No material definition, but if there's a texture reference, we can create a simple material using it (version 1.6 support)
    isTextured = true;
    texturePath = this._parent.resource.getDerivedResource({
      url: `${this._parent._data.textureData[0].href}`,
    }).url;
    gltfMaterial.pbrMetallicRoughness.baseColorTexture = { index: 0 };
  }
  if (defined(gltfMaterial.alphaMode)) {
    // I3S specifies alphaMode values in lowercase, but glTF expects values in uppercase
    gltfMaterial.alphaMode = gltfMaterial.alphaMode.toUpperCase();
  }
 
  let gltfTextures = [];
  let gltfImages = [];
  let gltfSamplers = [];
 
  if (isTextured) {
    gltfTextures = [
      {
        sampler: 0,
        source: 0,
      },
    ];
 
    gltfImages = [
      {
        uri: texturePath,
      },
    ];
 
    gltfSamplers = [
      {
        magFilter: 9729,
        minFilter: 9986,
        wrapS: 10497,
        wrapT: 10497,
      },
    ];
  }
 
  const gltfMaterials = [];
  const meshesLength = meshes.length;
  for (let meshIndex = 0; meshIndex < meshesLength; meshIndex++) {
    const primitives = meshes[meshIndex].primitives;
    const primitivesLength = primitives.length;
    for (
      let primitiveIndex = 0;
      primitiveIndex < primitivesLength;
      primitiveIndex++
    ) {
      const primitive = primitives[primitiveIndex];
      if (defined(primitive.material)) {
        // Create as many copies of the material as specified in the mesh primitives
        while (primitive.material >= gltfMaterials.length) {
          const material = clone(gltfMaterial, true);
          gltfMaterials.push(material);
        }
        const primitiveMaterial = gltfMaterials[primitive.material];
        if (defined(primitive.extra) && primitive.extra.isTransparent) {
          // If the alpha mode is not specified in the original material but the geometry is transparent, we need to force set BLEND alpha mode. Otherwise the geometry will be rendered opaque.
          if (!defined(primitiveMaterial.alphaMode)) {
            primitiveMaterial.alphaMode = "BLEND";
          }
        } else if (primitiveMaterial.alphaMode === "BLEND") {
          // If the geometry is not transparent, but the alpha mode is set to BLEND in the original material, we need to force set OPAQUE alpha mode. Otherwise the geometry will be rendered transparent.
          primitiveMaterial.alphaMode = "OPAQUE";
        }
      }
    }
  }
  const gltfData = {
    scene: 0,
    scenes: [
      {
        nodes: nodesInScene,
      },
    ],
    nodes: nodes,
    meshes: meshes,
    buffers: buffers,
    bufferViews: bufferViews,
    accessors: accessors,
    materials: gltfMaterials,
    textures: gltfTextures,
    images: gltfImages,
    samplers: gltfSamplers,
    asset: {
      version: "2.0",
    },
    extensions: extensions,
    extensionsUsed: extensionsUsed,
  };
 
  return gltfData;
};
 
export default I3SGeometry;