I3dmLoader.js 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734
  1. import AttributeCompression from "../../Core/AttributeCompression.js";
  2. import Axis from "../Axis.js";
  3. import Cartesian3 from "../../Core/Cartesian3.js";
  4. import Cesium3DTileFeatureTable from "../Cesium3DTileFeatureTable.js";
  5. import Check from "../../Core/Check.js";
  6. import ComponentDatatype from "../../Core/ComponentDatatype.js";
  7. import defaultValue from "../../Core/defaultValue.js";
  8. import defer from "../../Core/defer.js";
  9. import defined from "../../Core/defined.js";
  10. import Ellipsoid from "../../Core/Ellipsoid.js";
  11. import StructuralMetadata from "../StructuralMetadata.js";
  12. import getStringFromTypedArray from "../../Core/getStringFromTypedArray.js";
  13. import GltfLoader from "../GltfLoader.js";
  14. import I3dmParser from "../I3dmParser.js";
  15. import Matrix3 from "../../Core/Matrix3.js";
  16. import Matrix4 from "../../Core/Matrix4.js";
  17. import MetadataClass from "../MetadataClass.js";
  18. import ModelComponents from "../ModelComponents.js";
  19. import parseBatchTable from "../parseBatchTable.js";
  20. import PropertyTable from "../PropertyTable.js";
  21. import Quaternion from "../../Core/Quaternion.js";
  22. import ResourceLoader from "../ResourceLoader.js";
  23. import RuntimeError from "../../Core/RuntimeError.js";
  24. import Transforms from "../../Core/Transforms.js";
  25. import InstanceAttributeSemantic from "../InstanceAttributeSemantic.js";
  26. import AttributeType from "../AttributeType.js";
  27. import BoundingSphere from "../../Core/BoundingSphere.js";
  28. const I3dmLoaderState = {
  29. UNLOADED: 0,
  30. LOADING: 1,
  31. PROCESSING: 2,
  32. READY: 3,
  33. FAILED: 4,
  34. };
  35. const Attribute = ModelComponents.Attribute;
  36. const FeatureIdAttribute = ModelComponents.FeatureIdAttribute;
  37. const Instances = ModelComponents.Instances;
  38. /**
  39. * Loads an Instanced 3D Model.
  40. * <p>
  41. * Implements the {@link ResourceLoader} interface.
  42. * </p>
  43. *
  44. * @alias I3dmLoader
  45. * @constructor
  46. * @augments ResourceLoader
  47. * @private
  48. *
  49. * @param {Object} options Object with the following properties:
  50. * @param {Resource} options.i3dmResource The {@link Resource} containing the I3DM.
  51. * @param {ArrayBuffer} options.arrayBuffer The array buffer of the I3DM contents.
  52. * @param {Number} [options.byteOffset=0] The byte offset to the beginning of the I3DM contents in the array buffer.
  53. * @param {Resource} [options.baseResource] The {@link Resource} that paths in the glTF JSON are relative to.
  54. * @param {Boolean} [options.releaseGltfJson=false] When true, the glTF JSON is released once the glTF is loaded. This is is especially useful for cases like 3D Tiles, where each .gltf model is unique and caching the glTF JSON is not effective.
  55. * @param {Boolean} [options.asynchronous=true] Determines if WebGL resource creation will be spread out over several frames or block until all WebGL resources are created.
  56. * @param {Boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the glTF is loaded.
  57. * @param {Axis} [options.upAxis=Axis.Y] The up-axis of the glTF model.
  58. * @param {Axis} [options.forwardAxis=Axis.X] The forward-axis of the glTF model.
  59. * @param {Boolean} [options.loadAsTypedArray=false] Load all attributes as typed arrays instead of GPU buffers.
  60. */
  61. function I3dmLoader(options) {
  62. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  63. const i3dmResource = options.i3dmResource;
  64. const arrayBuffer = options.arrayBuffer;
  65. let baseResource = options.baseResource;
  66. const byteOffset = defaultValue(options.byteOffset, 0);
  67. const releaseGltfJson = defaultValue(options.releaseGltfJson, false);
  68. const asynchronous = defaultValue(options.asynchronous, true);
  69. const incrementallyLoadTextures = defaultValue(
  70. options.incrementallyLoadTextures,
  71. true
  72. );
  73. const upAxis = defaultValue(options.upAxis, Axis.Y);
  74. const forwardAxis = defaultValue(options.forwardAxis, Axis.X);
  75. const loadAsTypedArray = defaultValue(options.loadAsTypedArray, false);
  76. //>>includeStart('debug', pragmas.debug);
  77. Check.typeOf.object("options.i3dmResource", i3dmResource);
  78. Check.typeOf.object("options.arrayBuffer", arrayBuffer);
  79. //>>includeEnd('debug');
  80. baseResource = defined(baseResource) ? baseResource : i3dmResource.clone();
  81. this._i3dmResource = i3dmResource;
  82. this._baseResource = baseResource;
  83. this._arrayBuffer = arrayBuffer;
  84. this._byteOffset = byteOffset;
  85. this._releaseGltfJson = releaseGltfJson;
  86. this._asynchronous = asynchronous;
  87. this._incrementallyLoadTextures = incrementallyLoadTextures;
  88. this._upAxis = upAxis;
  89. this._forwardAxis = forwardAxis;
  90. this._loadAsTypedArray = loadAsTypedArray;
  91. this._state = I3dmLoaderState.UNLOADED;
  92. this._promise = defer();
  93. this._gltfLoader = undefined;
  94. this._transform = Matrix4.IDENTITY;
  95. this._batchTable = undefined;
  96. this._featureTable = undefined;
  97. this._instancesLength = 0;
  98. }
  99. if (defined(Object.create)) {
  100. I3dmLoader.prototype = Object.create(ResourceLoader.prototype);
  101. I3dmLoader.prototype.constructor = I3dmLoader;
  102. }
  103. Object.defineProperties(I3dmLoader.prototype, {
  104. /**
  105. * A promise that resolves to the resource when the resource is ready.
  106. *
  107. * @memberof I3dmLoader.prototype
  108. *
  109. * @type {Promise.<I3dmLoader>}
  110. * @readonly
  111. * @private
  112. */
  113. promise: {
  114. get: function () {
  115. return this._promise.promise;
  116. },
  117. },
  118. /**
  119. * A promise that resolves when all textures are loaded.
  120. * When <code>incrementallyLoadTextures</code> is true this may resolve after
  121. * <code>promise</code> resolves.
  122. *
  123. * @memberof I3dmLoader.prototype
  124. *
  125. * @type {Promise}
  126. * @readonly
  127. * @private
  128. */
  129. texturesLoadedPromise: {
  130. get: function () {
  131. return this._gltfLoader.texturesLoadedPromise;
  132. },
  133. },
  134. /**
  135. * The cache key of the resource
  136. *
  137. * @memberof I3dmLoader.prototype
  138. *
  139. * @type {String}
  140. * @readonly
  141. * @private
  142. */
  143. cacheKey: {
  144. get: function () {
  145. return undefined;
  146. },
  147. },
  148. /**
  149. * The loaded components.
  150. *
  151. * @memberof I3dmLoader.prototype
  152. *
  153. * @type {ModelComponents.Components}
  154. * @default {@link Matrix4.IDENTITY}
  155. * @readonly
  156. * @private
  157. */
  158. components: {
  159. get: function () {
  160. return this._components;
  161. },
  162. },
  163. });
  164. /**
  165. * Loads the resource.
  166. * @private
  167. */
  168. I3dmLoader.prototype.load = function () {
  169. // Parse the I3DM into its various sections.
  170. const i3dm = I3dmParser.parse(this._arrayBuffer, this._byteOffset);
  171. const featureTableJson = i3dm.featureTableJson;
  172. const featureTableBinary = i3dm.featureTableBinary;
  173. const batchTableJson = i3dm.batchTableJson;
  174. const batchTableBinary = i3dm.batchTableBinary;
  175. const gltfFormat = i3dm.gltfFormat;
  176. // Generate the feature table.
  177. const featureTable = new Cesium3DTileFeatureTable(
  178. featureTableJson,
  179. featureTableBinary
  180. );
  181. this._featureTable = featureTable;
  182. // Get the number of instances in the I3DM.
  183. const instancesLength = featureTable.getGlobalProperty("INSTANCES_LENGTH");
  184. featureTable.featuresLength = instancesLength;
  185. if (!defined(instancesLength)) {
  186. throw new RuntimeError(
  187. "Feature table global property: INSTANCES_LENGTH must be defined"
  188. );
  189. }
  190. this._instancesLength = instancesLength;
  191. // Get the RTC center, if available, and set the loader's transform.
  192. const rtcCenter = featureTable.getGlobalProperty(
  193. "RTC_CENTER",
  194. ComponentDatatype.FLOAT,
  195. 3
  196. );
  197. if (defined(rtcCenter)) {
  198. this._transform = Matrix4.fromTranslation(Cartesian3.fromArray(rtcCenter));
  199. }
  200. // Save the batch table section to use for StructuralMetadata generation.
  201. this._batchTable = {
  202. json: batchTableJson,
  203. binary: batchTableBinary,
  204. };
  205. const loaderOptions = {
  206. upAxis: this._upAxis,
  207. forwardAxis: this._forwardAxis,
  208. releaseGltfJson: this._releaseGltfJson,
  209. incrementallyLoadTextures: this._incrementallyLoadTextures,
  210. loadAsTypedArray: this._loadAsTypedArray,
  211. };
  212. if (gltfFormat === 0) {
  213. let gltfUrl = getStringFromTypedArray(i3dm.gltf);
  214. // We need to remove padding from the end of the model URL in case this tile was part of a composite tile.
  215. // This removes all white space and null characters from the end of the string.
  216. gltfUrl = gltfUrl.replace(/[\s\0]+$/, "");
  217. const gltfResource = this._baseResource.getDerivedResource({
  218. url: gltfUrl,
  219. });
  220. loaderOptions.gltfResource = gltfResource;
  221. loaderOptions.baseResource = gltfResource;
  222. } else {
  223. loaderOptions.gltfResource = this._i3dmResource;
  224. loaderOptions.typedArray = i3dm.gltf;
  225. }
  226. // Create the GltfLoader, update the state and load the glTF.
  227. const gltfLoader = new GltfLoader(loaderOptions);
  228. this._gltfLoader = gltfLoader;
  229. this._state = I3dmLoaderState.LOADING;
  230. const that = this;
  231. gltfLoader.load();
  232. gltfLoader.promise
  233. .then(function () {
  234. if (that.isDestroyed()) {
  235. return;
  236. }
  237. const components = gltfLoader.components;
  238. components.transform = that._transform;
  239. createInstances(that, components);
  240. createStructuralMetadata(that, components);
  241. that._components = components;
  242. that._state = I3dmLoaderState.READY;
  243. that._promise.resolve(that);
  244. })
  245. .catch(function (error) {
  246. if (that.isDestroyed()) {
  247. return;
  248. }
  249. handleError(that, error);
  250. });
  251. };
  252. function handleError(i3dmLoader, error) {
  253. i3dmLoader.unload();
  254. i3dmLoader._state = I3dmLoaderState.FAILED;
  255. const errorMessage = "Failed to load I3DM";
  256. error = i3dmLoader.getError(errorMessage, error);
  257. i3dmLoader._promise.reject(error);
  258. }
  259. I3dmLoader.prototype.process = function (frameState) {
  260. //>>includeStart('debug', pragmas.debug);
  261. Check.typeOf.object("frameState", frameState);
  262. //>>includeEnd('debug');
  263. if (this._state === I3dmLoaderState.LOADING) {
  264. this._state = I3dmLoaderState.PROCESSING;
  265. }
  266. if (this._state === I3dmLoaderState.PROCESSING) {
  267. this._gltfLoader.process(frameState);
  268. }
  269. };
  270. function createStructuralMetadata(loader, components) {
  271. const batchTable = loader._batchTable;
  272. const instancesLength = loader._instancesLength;
  273. if (instancesLength === 0) {
  274. return;
  275. }
  276. let structuralMetadata;
  277. if (defined(batchTable.json)) {
  278. // Add the structural metadata from the batch table to the model components.
  279. structuralMetadata = parseBatchTable({
  280. count: instancesLength,
  281. batchTable: batchTable.json,
  282. binaryBody: batchTable.binary,
  283. });
  284. } else {
  285. // If batch table is not defined, create a property table without any properties.
  286. const emptyPropertyTable = new PropertyTable({
  287. name: MetadataClass.BATCH_TABLE_CLASS_NAME,
  288. count: instancesLength,
  289. });
  290. structuralMetadata = new StructuralMetadata({
  291. schema: {},
  292. propertyTables: [emptyPropertyTable],
  293. });
  294. }
  295. components.structuralMetadata = structuralMetadata;
  296. }
  297. const positionScratch = new Cartesian3();
  298. const propertyScratch1 = new Array(4);
  299. function createInstances(loader, components) {
  300. let i;
  301. const featureTable = loader._featureTable;
  302. const instancesLength = loader._instancesLength;
  303. if (instancesLength === 0) {
  304. return;
  305. }
  306. const rtcCenter = featureTable.getGlobalProperty(
  307. "RTC_CENTER",
  308. ComponentDatatype.FLOAT,
  309. 3
  310. );
  311. const eastNorthUp = featureTable.getGlobalProperty("EAST_NORTH_UP");
  312. const hasRotation =
  313. featureTable.hasProperty("NORMAL_UP") ||
  314. featureTable.hasProperty("NORMAL_UP_OCT32P") ||
  315. eastNorthUp;
  316. const hasScale =
  317. featureTable.hasProperty("SCALE") ||
  318. featureTable.hasProperty("SCALE_NON_UNIFORM");
  319. const translationTypedArray = getPositions(featureTable, instancesLength);
  320. let rotationTypedArray;
  321. if (hasRotation) {
  322. rotationTypedArray = new Float32Array(4 * instancesLength);
  323. }
  324. let scaleTypedArray;
  325. if (hasScale) {
  326. scaleTypedArray = new Float32Array(3 * instancesLength);
  327. }
  328. const featureIdArray = new Float32Array(instancesLength);
  329. const instancePositions = Cartesian3.unpackArray(translationTypedArray);
  330. let instancePosition = new Cartesian3();
  331. const instanceNormalRight = new Cartesian3();
  332. const instanceNormalUp = new Cartesian3();
  333. const instanceNormalForward = new Cartesian3();
  334. const instanceRotation = new Matrix3();
  335. const instanceQuaternion = new Quaternion();
  336. const instanceQuaternionArray = new Array(4);
  337. const instanceScale = new Cartesian3();
  338. const instanceScaleArray = new Array(3);
  339. const instanceTransform = new Matrix4();
  340. // For I3DMs that do not define an RTC center, we manually compute a BoundingSphere and store
  341. // positions relative to the center, to be uploaded to the GPU. This avoids jittering at higher
  342. // precisions.
  343. if (!defined(rtcCenter)) {
  344. const positionBoundingSphere = BoundingSphere.fromPoints(instancePositions);
  345. for (i = 0; i < instancePositions.length; i++) {
  346. Cartesian3.subtract(
  347. instancePositions[i],
  348. positionBoundingSphere.center,
  349. positionScratch
  350. );
  351. translationTypedArray[3 * i + 0] = positionScratch.x;
  352. translationTypedArray[3 * i + 1] = positionScratch.y;
  353. translationTypedArray[3 * i + 2] = positionScratch.z;
  354. }
  355. // Set the center of the bounding sphere as the RTC center transform.
  356. components.transform = Matrix4.fromTranslation(
  357. positionBoundingSphere.center
  358. );
  359. }
  360. for (i = 0; i < instancesLength; i++) {
  361. // Get the instance position
  362. instancePosition = Cartesian3.clone(instancePositions[i]);
  363. if (defined(rtcCenter)) {
  364. Cartesian3.add(
  365. instancePosition,
  366. Cartesian3.unpack(rtcCenter),
  367. instancePosition
  368. );
  369. }
  370. // Get the instance rotation, if present
  371. if (hasRotation) {
  372. processRotation(
  373. featureTable,
  374. eastNorthUp,
  375. i,
  376. instanceQuaternion,
  377. instancePosition,
  378. instanceNormalUp,
  379. instanceNormalRight,
  380. instanceNormalForward,
  381. instanceRotation,
  382. instanceTransform
  383. );
  384. Quaternion.pack(instanceQuaternion, instanceQuaternionArray, 0);
  385. rotationTypedArray[4 * i + 0] = instanceQuaternionArray[0];
  386. rotationTypedArray[4 * i + 1] = instanceQuaternionArray[1];
  387. rotationTypedArray[4 * i + 2] = instanceQuaternionArray[2];
  388. rotationTypedArray[4 * i + 3] = instanceQuaternionArray[3];
  389. }
  390. // Get the instance scale, if present
  391. if (hasScale) {
  392. processScale(featureTable, i, instanceScale);
  393. Cartesian3.pack(instanceScale, instanceScaleArray, 0);
  394. scaleTypedArray[3 * i + 0] = instanceScaleArray[0];
  395. scaleTypedArray[3 * i + 1] = instanceScaleArray[1];
  396. scaleTypedArray[3 * i + 2] = instanceScaleArray[2];
  397. }
  398. // Get the batchId
  399. let batchId = featureTable.getProperty(
  400. "BATCH_ID",
  401. ComponentDatatype.UNSIGNED_SHORT,
  402. 1,
  403. i
  404. );
  405. if (!defined(batchId)) {
  406. // If BATCH_ID semantic is undefined, batchId is just the instance number
  407. batchId = i;
  408. }
  409. featureIdArray[i] = batchId;
  410. }
  411. // Create instances.
  412. const instances = new Instances();
  413. instances.transformInWorldSpace = true;
  414. // Create translation vertex attribute.
  415. const translationAttribute = new Attribute();
  416. translationAttribute.name = "Instance Translation";
  417. translationAttribute.semantic = InstanceAttributeSemantic.TRANSLATION;
  418. translationAttribute.componentDatatype = ComponentDatatype.FLOAT;
  419. translationAttribute.type = AttributeType.VEC3;
  420. translationAttribute.count = instancesLength;
  421. translationAttribute.packedTypedArray = translationTypedArray;
  422. instances.attributes.push(translationAttribute);
  423. // Create rotation vertex attribute.
  424. if (hasRotation) {
  425. const rotationAttribute = new Attribute();
  426. rotationAttribute.name = "Instance Rotation";
  427. rotationAttribute.semantic = InstanceAttributeSemantic.ROTATION;
  428. rotationAttribute.componentDatatype = ComponentDatatype.FLOAT;
  429. rotationAttribute.type = AttributeType.VEC4;
  430. rotationAttribute.count = instancesLength;
  431. rotationAttribute.packedTypedArray = rotationTypedArray;
  432. instances.attributes.push(rotationAttribute);
  433. }
  434. // Create scale vertex attribute.
  435. if (hasScale) {
  436. const scaleAttribute = new Attribute();
  437. scaleAttribute.name = "Instance Scale";
  438. scaleAttribute.semantic = InstanceAttributeSemantic.SCALE;
  439. scaleAttribute.componentDatatype = ComponentDatatype.FLOAT;
  440. scaleAttribute.type = AttributeType.VEC3;
  441. scaleAttribute.count = instancesLength;
  442. scaleAttribute.packedTypedArray = scaleTypedArray;
  443. instances.attributes.push(scaleAttribute);
  444. }
  445. // Create feature ID vertex attribute.
  446. const featureIdAttribute = new Attribute();
  447. featureIdAttribute.name = "Instance Feature ID";
  448. featureIdAttribute.setIndex = 0;
  449. featureIdAttribute.semantic = InstanceAttributeSemantic.FEATURE_ID;
  450. featureIdAttribute.componentDatatype = ComponentDatatype.FLOAT;
  451. featureIdAttribute.type = AttributeType.SCALAR;
  452. featureIdAttribute.count = instancesLength;
  453. featureIdAttribute.packedTypedArray = featureIdArray;
  454. instances.attributes.push(featureIdAttribute);
  455. // Create feature ID attribute.
  456. const featureIdInstanceAttribute = new FeatureIdAttribute();
  457. featureIdInstanceAttribute.propertyTableId = 0;
  458. featureIdInstanceAttribute.setIndex = 0;
  459. featureIdInstanceAttribute.positionalLabel = "instanceFeatureId_0";
  460. instances.featureIds.push(featureIdInstanceAttribute);
  461. // Apply instancing to every node that has at least one primitive.
  462. for (i = 0; i < components.nodes.length; i++) {
  463. const node = components.nodes[i];
  464. if (node.primitives.length > 0) {
  465. node.instances = instances;
  466. }
  467. }
  468. }
  469. /**
  470. * Returns a typed array of positions from the I3DM's feature table. The positions
  471. * returned are dequantized, if dequantization is applied.
  472. *
  473. * @private
  474. */
  475. function getPositions(featureTable, instancesLength) {
  476. if (featureTable.hasProperty("POSITION")) {
  477. // Handle positions.
  478. return featureTable.getPropertyArray(
  479. "POSITION",
  480. ComponentDatatype.FLOAT,
  481. 3
  482. );
  483. } else if (featureTable.hasProperty("POSITION_QUANTIZED")) {
  484. // Handle quantized positions.
  485. const quantizedPositions = featureTable.getPropertyArray(
  486. "POSITION_QUANTIZED",
  487. ComponentDatatype.UNSIGNED_SHORT,
  488. 3
  489. );
  490. const quantizedVolumeOffset = featureTable.getGlobalProperty(
  491. "QUANTIZED_VOLUME_OFFSET",
  492. ComponentDatatype.FLOAT,
  493. 3
  494. );
  495. if (!defined(quantizedVolumeOffset)) {
  496. throw new RuntimeError(
  497. "Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."
  498. );
  499. }
  500. const quantizedVolumeScale = featureTable.getGlobalProperty(
  501. "QUANTIZED_VOLUME_SCALE",
  502. ComponentDatatype.FLOAT,
  503. 3
  504. );
  505. if (!defined(quantizedVolumeScale)) {
  506. throw new RuntimeError(
  507. "Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."
  508. );
  509. }
  510. for (let i = 0; i < quantizedPositions.length / 3; i++) {
  511. const quantizedPosition = quantizedPositions[i];
  512. for (let j = 0; j < 3; j++) {
  513. quantizedPositions[3 * i + j] =
  514. (quantizedPosition[j] / 65535.0) * quantizedVolumeScale[j] +
  515. quantizedVolumeOffset[j];
  516. }
  517. }
  518. return quantizedPositions;
  519. // eslint-disable-next-line no-else-return
  520. } else {
  521. throw new RuntimeError(
  522. "Either POSITION or POSITION_QUANTIZED must be defined for each instance."
  523. );
  524. }
  525. }
  526. const propertyScratch2 = new Array(4);
  527. function processRotation(
  528. featureTable,
  529. eastNorthUp,
  530. i,
  531. instanceQuaternion,
  532. instancePosition,
  533. instanceNormalUp,
  534. instanceNormalRight,
  535. instanceNormalForward,
  536. instanceRotation,
  537. instanceTransform
  538. ) {
  539. // Get the instance rotation
  540. const normalUp = featureTable.getProperty(
  541. "NORMAL_UP",
  542. ComponentDatatype.FLOAT,
  543. 3,
  544. i,
  545. propertyScratch1
  546. );
  547. const normalRight = featureTable.getProperty(
  548. "NORMAL_RIGHT",
  549. ComponentDatatype.FLOAT,
  550. 3,
  551. i,
  552. propertyScratch2
  553. );
  554. let hasCustomOrientation = false;
  555. if (defined(normalUp)) {
  556. if (!defined(normalRight)) {
  557. throw new RuntimeError(
  558. "To define a custom orientation, both NORMAL_UP and NORMAL_RIGHT must be defined."
  559. );
  560. }
  561. Cartesian3.unpack(normalUp, 0, instanceNormalUp);
  562. Cartesian3.unpack(normalRight, 0, instanceNormalRight);
  563. hasCustomOrientation = true;
  564. } else {
  565. const octNormalUp = featureTable.getProperty(
  566. "NORMAL_UP_OCT32P",
  567. ComponentDatatype.UNSIGNED_SHORT,
  568. 2,
  569. i,
  570. propertyScratch1
  571. );
  572. const octNormalRight = featureTable.getProperty(
  573. "NORMAL_RIGHT_OCT32P",
  574. ComponentDatatype.UNSIGNED_SHORT,
  575. 2,
  576. i,
  577. propertyScratch2
  578. );
  579. if (defined(octNormalUp)) {
  580. if (!defined(octNormalRight)) {
  581. throw new RuntimeError(
  582. "To define a custom orientation with oct-encoded vectors, both NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P must be defined."
  583. );
  584. }
  585. AttributeCompression.octDecodeInRange(
  586. octNormalUp[0],
  587. octNormalUp[1],
  588. 65535,
  589. instanceNormalUp
  590. );
  591. AttributeCompression.octDecodeInRange(
  592. octNormalRight[0],
  593. octNormalRight[1],
  594. 65535,
  595. instanceNormalRight
  596. );
  597. hasCustomOrientation = true;
  598. } else if (eastNorthUp) {
  599. Transforms.eastNorthUpToFixedFrame(
  600. instancePosition,
  601. Ellipsoid.WGS84,
  602. instanceTransform
  603. );
  604. Matrix4.getMatrix3(instanceTransform, instanceRotation);
  605. } else {
  606. Matrix3.clone(Matrix3.IDENTITY, instanceRotation);
  607. }
  608. }
  609. if (hasCustomOrientation) {
  610. Cartesian3.cross(
  611. instanceNormalRight,
  612. instanceNormalUp,
  613. instanceNormalForward
  614. );
  615. Cartesian3.normalize(instanceNormalForward, instanceNormalForward);
  616. Matrix3.setColumn(
  617. instanceRotation,
  618. 0,
  619. instanceNormalRight,
  620. instanceRotation
  621. );
  622. Matrix3.setColumn(instanceRotation, 1, instanceNormalUp, instanceRotation);
  623. Matrix3.setColumn(
  624. instanceRotation,
  625. 2,
  626. instanceNormalForward,
  627. instanceRotation
  628. );
  629. }
  630. Quaternion.fromRotationMatrix(instanceRotation, instanceQuaternion);
  631. }
  632. function processScale(featureTable, i, instanceScale) {
  633. instanceScale = Cartesian3.fromElements(1.0, 1.0, 1.0, instanceScale);
  634. const scale = featureTable.getProperty(
  635. "SCALE",
  636. ComponentDatatype.FLOAT,
  637. 1,
  638. i
  639. );
  640. if (defined(scale)) {
  641. Cartesian3.multiplyByScalar(instanceScale, scale, instanceScale);
  642. }
  643. const nonUniformScale = featureTable.getProperty(
  644. "SCALE_NON_UNIFORM",
  645. ComponentDatatype.FLOAT,
  646. 3,
  647. i,
  648. propertyScratch1
  649. );
  650. if (defined(nonUniformScale)) {
  651. instanceScale.x *= nonUniformScale[0];
  652. instanceScale.y *= nonUniformScale[1];
  653. instanceScale.z *= nonUniformScale[2];
  654. }
  655. }
  656. I3dmLoader.prototype.unload = function () {
  657. if (defined(this._gltfLoader)) {
  658. this._gltfLoader.unload();
  659. }
  660. this._components = undefined;
  661. };
  662. export default I3dmLoader;