I3dmLoader.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  1. import AttributeCompression from "../../Core/AttributeCompression.js";
  2. import BoundingSphere from "../../Core/BoundingSphere.js";
  3. import Cartesian3 from "../../Core/Cartesian3.js";
  4. import Check from "../../Core/Check.js";
  5. import clone from "../../Core/clone.js";
  6. import ComponentDatatype from "../../Core/ComponentDatatype.js";
  7. import defaultValue from "../../Core/defaultValue.js";
  8. import defined from "../../Core/defined.js";
  9. import Ellipsoid from "../../Core/Ellipsoid.js";
  10. import getStringFromTypedArray from "../../Core/getStringFromTypedArray.js";
  11. import Matrix3 from "../../Core/Matrix3.js";
  12. import Matrix4 from "../../Core/Matrix4.js";
  13. import Quaternion from "../../Core/Quaternion.js";
  14. import RuntimeError from "../../Core/RuntimeError.js";
  15. import Transforms from "../../Core/Transforms.js";
  16. import Buffer from "../../Renderer/Buffer.js";
  17. import BufferUsage from "../../Renderer/BufferUsage.js";
  18. import AttributeType from "../AttributeType.js";
  19. import Axis from "../Axis.js";
  20. import Cesium3DTileFeatureTable from "../Cesium3DTileFeatureTable.js";
  21. import GltfLoader from "../GltfLoader.js";
  22. import InstanceAttributeSemantic from "../InstanceAttributeSemantic.js";
  23. import I3dmParser from "../I3dmParser.js";
  24. import MetadataClass from "../MetadataClass.js";
  25. import ModelComponents from "../ModelComponents.js";
  26. import parseBatchTable from "../parseBatchTable.js";
  27. import PropertyTable from "../PropertyTable.js";
  28. import ResourceLoader from "../ResourceLoader.js";
  29. import StructuralMetadata from "../StructuralMetadata.js";
  30. const I3dmLoaderState = {
  31. NOT_LOADED: 0,
  32. LOADING: 1,
  33. PROCESSING: 2,
  34. POST_PROCESSING: 3,
  35. READY: 4,
  36. FAILED: 5,
  37. UNLOADED: 6,
  38. };
  39. const Attribute = ModelComponents.Attribute;
  40. const FeatureIdAttribute = ModelComponents.FeatureIdAttribute;
  41. const Instances = ModelComponents.Instances;
  42. /**
  43. * Loads an Instanced 3D Model.
  44. * <p>
  45. * Implements the {@link ResourceLoader} interface.
  46. * </p>
  47. *
  48. * @alias I3dmLoader
  49. * @constructor
  50. * @augments ResourceLoader
  51. * @private
  52. *
  53. * @param {object} options Object with the following properties:
  54. * @param {Resource} options.i3dmResource The {@link Resource} containing the i3dm.
  55. * @param {ArrayBuffer} options.arrayBuffer The array buffer of the i3dm contents.
  56. * @param {number} [options.byteOffset=0] The byte offset to the beginning of the i3dm contents in the array buffer.
  57. * @param {Resource} [options.baseResource] The {@link Resource} that paths in the glTF JSON are relative to.
  58. * @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.
  59. * @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.
  60. * @param {boolean} [options.incrementallyLoadTextures=true] Determine if textures may continue to stream in after the glTF is loaded.
  61. * @param {Axis} [options.upAxis=Axis.Y] The up-axis of the glTF model.
  62. * @param {Axis} [options.forwardAxis=Axis.X] The forward-axis of the glTF model.
  63. * @param {boolean} [options.loadAttributesAsTypedArray=false] Load all attributes as typed arrays instead of GPU buffers. If the attributes are interleaved in the glTF they will be de-interleaved in the typed array.
  64. * @param {boolean} [options.loadIndicesForWireframe=false] Load the index buffer as a typed array so wireframe indices can be created for WebGL1.
  65. * @param {boolean} [options.loadPrimitiveOutline=true] If true, load outlines from the {@link https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/CESIUM_primitive_outline|CESIUM_primitive_outline} extension. This can be set false to avoid post-processing geometry at load time.
  66. */
  67. function I3dmLoader(options) {
  68. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  69. const i3dmResource = options.i3dmResource;
  70. const arrayBuffer = options.arrayBuffer;
  71. let baseResource = options.baseResource;
  72. const byteOffset = defaultValue(options.byteOffset, 0);
  73. const releaseGltfJson = defaultValue(options.releaseGltfJson, false);
  74. const asynchronous = defaultValue(options.asynchronous, true);
  75. const incrementallyLoadTextures = defaultValue(
  76. options.incrementallyLoadTextures,
  77. true
  78. );
  79. const upAxis = defaultValue(options.upAxis, Axis.Y);
  80. const forwardAxis = defaultValue(options.forwardAxis, Axis.X);
  81. const loadAttributesAsTypedArray = defaultValue(
  82. options.loadAttributesAsTypedArray,
  83. false
  84. );
  85. const loadIndicesForWireframe = defaultValue(
  86. options.loadIndicesForWireframe,
  87. false
  88. );
  89. const loadPrimitiveOutline = defaultValue(options.loadPrimitiveOutline, true);
  90. //>>includeStart('debug', pragmas.debug);
  91. Check.typeOf.object("options.i3dmResource", i3dmResource);
  92. Check.typeOf.object("options.arrayBuffer", arrayBuffer);
  93. //>>includeEnd('debug');
  94. baseResource = defined(baseResource) ? baseResource : i3dmResource.clone();
  95. this._i3dmResource = i3dmResource;
  96. this._baseResource = baseResource;
  97. this._arrayBuffer = arrayBuffer;
  98. this._byteOffset = byteOffset;
  99. this._releaseGltfJson = releaseGltfJson;
  100. this._asynchronous = asynchronous;
  101. this._incrementallyLoadTextures = incrementallyLoadTextures;
  102. this._upAxis = upAxis;
  103. this._forwardAxis = forwardAxis;
  104. this._loadAttributesAsTypedArray = loadAttributesAsTypedArray;
  105. this._loadIndicesForWireframe = loadIndicesForWireframe;
  106. this._loadPrimitiveOutline = loadPrimitiveOutline;
  107. this._state = I3dmLoaderState.NOT_LOADED;
  108. this._promise = undefined;
  109. this._gltfLoader = undefined;
  110. // Instanced attributes are initially parsed as typed arrays, but if they
  111. // do not need to be further processed (e.g. turned into transform matrices),
  112. // it is more efficient to turn them into buffers. The I3dmLoader will own the
  113. // resources and store them here.
  114. this._buffers = [];
  115. this._components = undefined;
  116. this._transform = Matrix4.IDENTITY;
  117. this._batchTable = undefined;
  118. this._featureTable = undefined;
  119. this._instancesLength = 0;
  120. }
  121. if (defined(Object.create)) {
  122. I3dmLoader.prototype = Object.create(ResourceLoader.prototype);
  123. I3dmLoader.prototype.constructor = I3dmLoader;
  124. }
  125. Object.defineProperties(I3dmLoader.prototype, {
  126. /**
  127. * true if textures are loaded, useful when incrementallyLoadTextures is true
  128. *
  129. * @memberof I3dmLoader.prototype
  130. *
  131. * @type {boolean}
  132. * @readonly
  133. * @private
  134. */
  135. texturesLoaded: {
  136. get: function () {
  137. return this._gltfLoader?.texturesLoaded;
  138. },
  139. },
  140. /**
  141. * The cache key of the resource
  142. *
  143. * @memberof I3dmLoader.prototype
  144. *
  145. * @type {string}
  146. * @readonly
  147. * @private
  148. */
  149. cacheKey: {
  150. get: function () {
  151. return undefined;
  152. },
  153. },
  154. /**
  155. * The loaded components.
  156. *
  157. * @memberof I3dmLoader.prototype
  158. *
  159. * @type {ModelComponents.Components}
  160. * @default {@link Matrix4.IDENTITY}
  161. * @readonly
  162. * @private
  163. */
  164. components: {
  165. get: function () {
  166. return this._components;
  167. },
  168. },
  169. });
  170. /**
  171. * Loads the resource.
  172. * @returns {Promise<I3dmLoader>} A promise which resolves to the loader when the resource loading is completed.
  173. * @private
  174. */
  175. I3dmLoader.prototype.load = function () {
  176. if (defined(this._promise)) {
  177. return this._promise;
  178. }
  179. // Parse the i3dm into its various sections.
  180. const i3dm = I3dmParser.parse(this._arrayBuffer, this._byteOffset);
  181. const featureTableJson = i3dm.featureTableJson;
  182. const featureTableBinary = i3dm.featureTableBinary;
  183. const batchTableJson = i3dm.batchTableJson;
  184. const batchTableBinary = i3dm.batchTableBinary;
  185. const gltfFormat = i3dm.gltfFormat;
  186. // Generate the feature table.
  187. const featureTable = new Cesium3DTileFeatureTable(
  188. featureTableJson,
  189. featureTableBinary
  190. );
  191. this._featureTable = featureTable;
  192. // Get the number of instances in the i3dm.
  193. const instancesLength = featureTable.getGlobalProperty("INSTANCES_LENGTH");
  194. featureTable.featuresLength = instancesLength;
  195. if (!defined(instancesLength)) {
  196. throw new RuntimeError(
  197. "Feature table global property: INSTANCES_LENGTH must be defined"
  198. );
  199. }
  200. this._instancesLength = instancesLength;
  201. // Get the RTC center, if available, and set the loader's transform.
  202. const rtcCenter = featureTable.getGlobalProperty(
  203. "RTC_CENTER",
  204. ComponentDatatype.FLOAT,
  205. 3
  206. );
  207. if (defined(rtcCenter)) {
  208. this._transform = Matrix4.fromTranslation(Cartesian3.fromArray(rtcCenter));
  209. }
  210. // Save the batch table section to use for StructuralMetadata generation.
  211. this._batchTable = {
  212. json: batchTableJson,
  213. binary: batchTableBinary,
  214. };
  215. const loaderOptions = {
  216. upAxis: this._upAxis,
  217. forwardAxis: this._forwardAxis,
  218. releaseGltfJson: this._releaseGltfJson,
  219. incrementallyLoadTextures: this._incrementallyLoadTextures,
  220. loadAttributesAsTypedArray: this._loadAttributesAsTypedArray,
  221. loadIndicesForWireframe: this._loadIndicesForWireframe,
  222. loadPrimitiveOutline: this._loadPrimitiveOutline,
  223. };
  224. if (gltfFormat === 0) {
  225. let gltfUrl = getStringFromTypedArray(i3dm.gltf);
  226. // We need to remove padding from the end of the model URL in case this tile was part of a composite tile.
  227. // This removes all white space and null characters from the end of the string.
  228. gltfUrl = gltfUrl.replace(/[\s\0]+$/, "");
  229. const gltfResource = this._baseResource.getDerivedResource({
  230. url: gltfUrl,
  231. });
  232. loaderOptions.gltfResource = gltfResource;
  233. loaderOptions.baseResource = gltfResource;
  234. } else {
  235. loaderOptions.gltfResource = this._i3dmResource;
  236. loaderOptions.typedArray = i3dm.gltf;
  237. }
  238. // Create the GltfLoader, update the state and load the glTF.
  239. const gltfLoader = new GltfLoader(loaderOptions);
  240. this._gltfLoader = gltfLoader;
  241. this._state = I3dmLoaderState.LOADING;
  242. this._promise = gltfLoader
  243. .load()
  244. .then(() => {
  245. if (this.isDestroyed()) {
  246. return;
  247. }
  248. this._state = I3dmLoaderState.PROCESSING;
  249. return this;
  250. })
  251. .catch((error) => {
  252. if (this.isDestroyed()) {
  253. return;
  254. }
  255. throw handleError(this, error);
  256. });
  257. return this._promise;
  258. };
  259. function handleError(i3dmLoader, error) {
  260. i3dmLoader.unload();
  261. i3dmLoader._state = I3dmLoaderState.FAILED;
  262. const errorMessage = "Failed to load i3dm";
  263. return i3dmLoader.getError(errorMessage, error);
  264. }
  265. I3dmLoader.prototype.process = function (frameState) {
  266. //>>includeStart('debug', pragmas.debug);
  267. Check.typeOf.object("frameState", frameState);
  268. //>>includeEnd('debug');
  269. if (this._state === I3dmLoaderState.READY) {
  270. return true;
  271. }
  272. const gltfLoader = this._gltfLoader;
  273. let ready = false;
  274. if (this._state === I3dmLoaderState.PROCESSING) {
  275. ready = gltfLoader.process(frameState);
  276. }
  277. if (!ready) {
  278. return false;
  279. }
  280. const components = gltfLoader.components;
  281. // Combine the RTC_CENTER transform from the i3dm and the CESIUM_RTC
  282. // transform from the glTF. In practice CESIUM_RTC is not set for
  283. // instanced models but multiply the transforms just in case.
  284. components.transform = Matrix4.multiplyTransformation(
  285. this._transform,
  286. components.transform,
  287. components.transform
  288. );
  289. createInstances(this, components, frameState);
  290. createStructuralMetadata(this, components);
  291. this._components = components;
  292. // Now that we have the parsed components, we can release the array buffer
  293. this._arrayBuffer = undefined;
  294. this._state = I3dmLoaderState.READY;
  295. return true;
  296. };
  297. function createStructuralMetadata(loader, components) {
  298. const batchTable = loader._batchTable;
  299. const instancesLength = loader._instancesLength;
  300. if (instancesLength === 0) {
  301. return;
  302. }
  303. let structuralMetadata;
  304. if (defined(batchTable.json)) {
  305. // Add the structural metadata from the batch table to the model components.
  306. structuralMetadata = parseBatchTable({
  307. count: instancesLength,
  308. batchTable: batchTable.json,
  309. binaryBody: batchTable.binary,
  310. });
  311. } else {
  312. // If batch table is not defined, create a property table without any properties.
  313. const emptyPropertyTable = new PropertyTable({
  314. name: MetadataClass.BATCH_TABLE_CLASS_NAME,
  315. count: instancesLength,
  316. });
  317. structuralMetadata = new StructuralMetadata({
  318. schema: {},
  319. propertyTables: [emptyPropertyTable],
  320. });
  321. }
  322. components.structuralMetadata = structuralMetadata;
  323. }
  324. const positionScratch = new Cartesian3();
  325. const propertyScratch1 = new Array(4);
  326. const transformScratch = new Matrix4();
  327. function createInstances(loader, components, frameState) {
  328. let i;
  329. const featureTable = loader._featureTable;
  330. const instancesLength = loader._instancesLength;
  331. if (instancesLength === 0) {
  332. return;
  333. }
  334. const rtcCenter = featureTable.getGlobalProperty(
  335. "RTC_CENTER",
  336. ComponentDatatype.FLOAT,
  337. 3
  338. );
  339. const eastNorthUp = featureTable.getGlobalProperty("EAST_NORTH_UP");
  340. const hasRotation =
  341. featureTable.hasProperty("NORMAL_UP") ||
  342. featureTable.hasProperty("NORMAL_UP_OCT32P") ||
  343. eastNorthUp;
  344. const hasScale =
  345. featureTable.hasProperty("SCALE") ||
  346. featureTable.hasProperty("SCALE_NON_UNIFORM");
  347. const translationTypedArray = getPositions(featureTable, instancesLength);
  348. let rotationTypedArray;
  349. if (hasRotation) {
  350. rotationTypedArray = new Float32Array(4 * instancesLength);
  351. }
  352. let scaleTypedArray;
  353. if (hasScale) {
  354. scaleTypedArray = new Float32Array(3 * instancesLength);
  355. }
  356. const featureIdArray = new Float32Array(instancesLength);
  357. const instancePositions = Cartesian3.unpackArray(translationTypedArray);
  358. let instancePosition = new Cartesian3();
  359. const instanceNormalRight = new Cartesian3();
  360. const instanceNormalUp = new Cartesian3();
  361. const instanceNormalForward = new Cartesian3();
  362. const instanceRotation = new Matrix3();
  363. const instanceQuaternion = new Quaternion();
  364. const instanceQuaternionArray = new Array(4);
  365. const instanceScale = new Cartesian3();
  366. const instanceScaleArray = new Array(3);
  367. const instanceTransform = new Matrix4();
  368. // For I3DMs that do not define an RTC center, we manually compute a BoundingSphere and store
  369. // positions relative to the center, to be uploaded to the GPU. This avoids jittering at higher
  370. // precisions.
  371. if (!defined(rtcCenter)) {
  372. const positionBoundingSphere = BoundingSphere.fromPoints(instancePositions);
  373. for (i = 0; i < instancePositions.length; i++) {
  374. Cartesian3.subtract(
  375. instancePositions[i],
  376. positionBoundingSphere.center,
  377. positionScratch
  378. );
  379. translationTypedArray[3 * i + 0] = positionScratch.x;
  380. translationTypedArray[3 * i + 1] = positionScratch.y;
  381. translationTypedArray[3 * i + 2] = positionScratch.z;
  382. }
  383. // Set the center of the bounding sphere as the RTC center transform.
  384. const centerTransform = Matrix4.fromTranslation(
  385. positionBoundingSphere.center,
  386. transformScratch
  387. );
  388. // Combine the center transform and the CESIUM_RTC transform from the glTF.
  389. // In practice CESIUM_RTC is not set for instanced models but multiply the
  390. // transforms just in case.
  391. components.transform = Matrix4.multiplyTransformation(
  392. centerTransform,
  393. components.transform,
  394. components.transform
  395. );
  396. }
  397. for (i = 0; i < instancesLength; i++) {
  398. // Get the instance position
  399. instancePosition = Cartesian3.clone(instancePositions[i]);
  400. if (defined(rtcCenter)) {
  401. Cartesian3.add(
  402. instancePosition,
  403. Cartesian3.unpack(rtcCenter),
  404. instancePosition
  405. );
  406. }
  407. // Get the instance rotation, if present
  408. if (hasRotation) {
  409. processRotation(
  410. featureTable,
  411. eastNorthUp,
  412. i,
  413. instanceQuaternion,
  414. instancePosition,
  415. instanceNormalUp,
  416. instanceNormalRight,
  417. instanceNormalForward,
  418. instanceRotation,
  419. instanceTransform
  420. );
  421. Quaternion.pack(instanceQuaternion, instanceQuaternionArray, 0);
  422. rotationTypedArray[4 * i + 0] = instanceQuaternionArray[0];
  423. rotationTypedArray[4 * i + 1] = instanceQuaternionArray[1];
  424. rotationTypedArray[4 * i + 2] = instanceQuaternionArray[2];
  425. rotationTypedArray[4 * i + 3] = instanceQuaternionArray[3];
  426. }
  427. // Get the instance scale, if present
  428. if (hasScale) {
  429. processScale(featureTable, i, instanceScale);
  430. Cartesian3.pack(instanceScale, instanceScaleArray, 0);
  431. scaleTypedArray[3 * i + 0] = instanceScaleArray[0];
  432. scaleTypedArray[3 * i + 1] = instanceScaleArray[1];
  433. scaleTypedArray[3 * i + 2] = instanceScaleArray[2];
  434. }
  435. // Get the batchId
  436. let batchId = featureTable.getProperty(
  437. "BATCH_ID",
  438. ComponentDatatype.UNSIGNED_SHORT,
  439. 1,
  440. i
  441. );
  442. if (!defined(batchId)) {
  443. // If BATCH_ID semantic is undefined, batchId is just the instance number
  444. batchId = i;
  445. }
  446. featureIdArray[i] = batchId;
  447. }
  448. // Create instances.
  449. const instances = new Instances();
  450. instances.transformInWorldSpace = true;
  451. const buffers = loader._buffers;
  452. // Create translation vertex attribute.
  453. const translationAttribute = new Attribute();
  454. translationAttribute.name = "Instance Translation";
  455. translationAttribute.semantic = InstanceAttributeSemantic.TRANSLATION;
  456. translationAttribute.componentDatatype = ComponentDatatype.FLOAT;
  457. translationAttribute.type = AttributeType.VEC3;
  458. translationAttribute.count = instancesLength;
  459. // The min / max values of the translation attribute need to be computed
  460. // by the model pipeline, so so a pointer to the typed array is stored.
  461. translationAttribute.typedArray = translationTypedArray;
  462. // If there is no rotation attribute, however, the translations can also be
  463. // loaded as a buffer to prevent additional resource creation in the pipeline.
  464. if (!hasRotation) {
  465. const buffer = Buffer.createVertexBuffer({
  466. context: frameState.context,
  467. typedArray: translationTypedArray,
  468. usage: BufferUsage.STATIC_DRAW,
  469. });
  470. // Destruction of resources is handled by I3dmLoader.unload().
  471. buffer.vertexArrayDestroyable = false;
  472. buffers.push(buffer);
  473. translationAttribute.buffer = buffer;
  474. }
  475. instances.attributes.push(translationAttribute);
  476. // Create rotation vertex attribute.
  477. if (hasRotation) {
  478. const rotationAttribute = new Attribute();
  479. rotationAttribute.name = "Instance Rotation";
  480. rotationAttribute.semantic = InstanceAttributeSemantic.ROTATION;
  481. rotationAttribute.componentDatatype = ComponentDatatype.FLOAT;
  482. rotationAttribute.type = AttributeType.VEC4;
  483. rotationAttribute.count = instancesLength;
  484. rotationAttribute.typedArray = rotationTypedArray;
  485. instances.attributes.push(rotationAttribute);
  486. }
  487. // Create scale vertex attribute.
  488. if (hasScale) {
  489. const scaleAttribute = new Attribute();
  490. scaleAttribute.name = "Instance Scale";
  491. scaleAttribute.semantic = InstanceAttributeSemantic.SCALE;
  492. scaleAttribute.componentDatatype = ComponentDatatype.FLOAT;
  493. scaleAttribute.type = AttributeType.VEC3;
  494. scaleAttribute.count = instancesLength;
  495. if (hasRotation) {
  496. // If rotations are present, all transform attributes are loaded
  497. // as typed arrays to compute transform matrices for the model.
  498. scaleAttribute.typedArray = scaleTypedArray;
  499. } else {
  500. const buffer = Buffer.createVertexBuffer({
  501. context: frameState.context,
  502. typedArray: scaleTypedArray,
  503. usage: BufferUsage.STATIC_DRAW,
  504. });
  505. // Destruction of resources is handled by I3dmLoader.unload().
  506. buffer.vertexArrayDestroyable = false;
  507. buffers.push(buffer);
  508. scaleAttribute.buffer = buffer;
  509. }
  510. instances.attributes.push(scaleAttribute);
  511. }
  512. // Create feature ID vertex attribute.
  513. const featureIdAttribute = new Attribute();
  514. featureIdAttribute.name = "Instance Feature ID";
  515. featureIdAttribute.setIndex = 0;
  516. featureIdAttribute.semantic = InstanceAttributeSemantic.FEATURE_ID;
  517. featureIdAttribute.componentDatatype = ComponentDatatype.FLOAT;
  518. featureIdAttribute.type = AttributeType.SCALAR;
  519. featureIdAttribute.count = instancesLength;
  520. const buffer = Buffer.createVertexBuffer({
  521. context: frameState.context,
  522. typedArray: featureIdArray,
  523. usage: BufferUsage.STATIC_DRAW,
  524. });
  525. // Destruction of resources is handled by I3dmLoader.unload().
  526. buffer.vertexArrayDestroyable = false;
  527. buffers.push(buffer);
  528. featureIdAttribute.buffer = buffer;
  529. instances.attributes.push(featureIdAttribute);
  530. // Create feature ID attribute.
  531. const featureIdInstanceAttribute = new FeatureIdAttribute();
  532. featureIdInstanceAttribute.propertyTableId = 0;
  533. featureIdInstanceAttribute.setIndex = 0;
  534. featureIdInstanceAttribute.positionalLabel = "instanceFeatureId_0";
  535. instances.featureIds.push(featureIdInstanceAttribute);
  536. // Apply instancing to every node that has at least one primitive.
  537. const nodes = components.nodes;
  538. const nodesLength = nodes.length;
  539. let makeInstancesCopy = false;
  540. for (i = 0; i < nodesLength; i++) {
  541. const node = nodes[i];
  542. if (node.primitives.length > 0) {
  543. // If the instances have not been assigned to a node already, assign
  544. // it to the first node encountered. Otherwise, make a copy of them
  545. // for each subsequent node.
  546. node.instances = makeInstancesCopy
  547. ? createInstancesCopy(instances)
  548. : instances;
  549. makeInstancesCopy = true;
  550. }
  551. }
  552. }
  553. /**
  554. * Returns a copy of the instances that contains shallow copies of the instanced
  555. * attributes. That is, the instances and attribute objects will be new copies,
  556. * but they will point to the same buffers and typed arrays. This is so each
  557. * node can manage memory separately, such that unloading memory for one
  558. * node does not unload it for another.
  559. *
  560. * @returns {ModelComponents.Instances}
  561. *
  562. * @private
  563. */
  564. function createInstancesCopy(instances) {
  565. const instancesCopy = new Instances();
  566. instancesCopy.transformInWorldSpace = instances.transformInWorldSpace;
  567. const attributes = instances.attributes;
  568. const attributesLength = attributes.length;
  569. for (let i = 0; i < attributesLength; i++) {
  570. const attributeCopy = clone(attributes[i], false);
  571. instancesCopy.attributes.push(attributeCopy);
  572. }
  573. instancesCopy.featureIds = instances.featureIds;
  574. return instancesCopy;
  575. }
  576. /**
  577. * Returns a typed array of positions from the i3dm's feature table. The positions
  578. * returned are dequantized, if dequantization is applied.
  579. *
  580. * @private
  581. */
  582. function getPositions(featureTable, instancesLength) {
  583. if (featureTable.hasProperty("POSITION")) {
  584. // Handle positions.
  585. return featureTable.getPropertyArray(
  586. "POSITION",
  587. ComponentDatatype.FLOAT,
  588. 3
  589. );
  590. } else if (featureTable.hasProperty("POSITION_QUANTIZED")) {
  591. // Handle quantized positions.
  592. const quantizedPositions = featureTable.getPropertyArray(
  593. "POSITION_QUANTIZED",
  594. ComponentDatatype.UNSIGNED_SHORT,
  595. 3
  596. );
  597. const quantizedVolumeOffset = featureTable.getGlobalProperty(
  598. "QUANTIZED_VOLUME_OFFSET",
  599. ComponentDatatype.FLOAT,
  600. 3
  601. );
  602. if (!defined(quantizedVolumeOffset)) {
  603. throw new RuntimeError(
  604. "Global property: QUANTIZED_VOLUME_OFFSET must be defined for quantized positions."
  605. );
  606. }
  607. const quantizedVolumeScale = featureTable.getGlobalProperty(
  608. "QUANTIZED_VOLUME_SCALE",
  609. ComponentDatatype.FLOAT,
  610. 3
  611. );
  612. if (!defined(quantizedVolumeScale)) {
  613. throw new RuntimeError(
  614. "Global property: QUANTIZED_VOLUME_SCALE must be defined for quantized positions."
  615. );
  616. }
  617. const decodedPositions = new Float32Array(quantizedPositions.length);
  618. for (let i = 0; i < quantizedPositions.length / 3; i++) {
  619. for (let j = 0; j < 3; j++) {
  620. const index = 3 * i + j;
  621. decodedPositions[index] =
  622. (quantizedPositions[index] / 65535.0) * quantizedVolumeScale[j] +
  623. quantizedVolumeOffset[j];
  624. }
  625. }
  626. return decodedPositions;
  627. // eslint-disable-next-line no-else-return
  628. } else {
  629. throw new RuntimeError(
  630. "Either POSITION or POSITION_QUANTIZED must be defined for each instance."
  631. );
  632. }
  633. }
  634. const propertyScratch2 = new Array(4);
  635. function processRotation(
  636. featureTable,
  637. eastNorthUp,
  638. i,
  639. instanceQuaternion,
  640. instancePosition,
  641. instanceNormalUp,
  642. instanceNormalRight,
  643. instanceNormalForward,
  644. instanceRotation,
  645. instanceTransform
  646. ) {
  647. // Get the instance rotation
  648. const normalUp = featureTable.getProperty(
  649. "NORMAL_UP",
  650. ComponentDatatype.FLOAT,
  651. 3,
  652. i,
  653. propertyScratch1
  654. );
  655. const normalRight = featureTable.getProperty(
  656. "NORMAL_RIGHT",
  657. ComponentDatatype.FLOAT,
  658. 3,
  659. i,
  660. propertyScratch2
  661. );
  662. let hasCustomOrientation = false;
  663. if (defined(normalUp)) {
  664. if (!defined(normalRight)) {
  665. throw new RuntimeError(
  666. "To define a custom orientation, both NORMAL_UP and NORMAL_RIGHT must be defined."
  667. );
  668. }
  669. Cartesian3.unpack(normalUp, 0, instanceNormalUp);
  670. Cartesian3.unpack(normalRight, 0, instanceNormalRight);
  671. hasCustomOrientation = true;
  672. } else {
  673. const octNormalUp = featureTable.getProperty(
  674. "NORMAL_UP_OCT32P",
  675. ComponentDatatype.UNSIGNED_SHORT,
  676. 2,
  677. i,
  678. propertyScratch1
  679. );
  680. const octNormalRight = featureTable.getProperty(
  681. "NORMAL_RIGHT_OCT32P",
  682. ComponentDatatype.UNSIGNED_SHORT,
  683. 2,
  684. i,
  685. propertyScratch2
  686. );
  687. if (defined(octNormalUp)) {
  688. if (!defined(octNormalRight)) {
  689. throw new RuntimeError(
  690. "To define a custom orientation with oct-encoded vectors, both NORMAL_UP_OCT32P and NORMAL_RIGHT_OCT32P must be defined."
  691. );
  692. }
  693. AttributeCompression.octDecodeInRange(
  694. octNormalUp[0],
  695. octNormalUp[1],
  696. 65535,
  697. instanceNormalUp
  698. );
  699. AttributeCompression.octDecodeInRange(
  700. octNormalRight[0],
  701. octNormalRight[1],
  702. 65535,
  703. instanceNormalRight
  704. );
  705. hasCustomOrientation = true;
  706. } else if (eastNorthUp) {
  707. Transforms.eastNorthUpToFixedFrame(
  708. instancePosition,
  709. Ellipsoid.WGS84,
  710. instanceTransform
  711. );
  712. Matrix4.getMatrix3(instanceTransform, instanceRotation);
  713. } else {
  714. Matrix3.clone(Matrix3.IDENTITY, instanceRotation);
  715. }
  716. }
  717. if (hasCustomOrientation) {
  718. Cartesian3.cross(
  719. instanceNormalRight,
  720. instanceNormalUp,
  721. instanceNormalForward
  722. );
  723. Cartesian3.normalize(instanceNormalForward, instanceNormalForward);
  724. Matrix3.setColumn(
  725. instanceRotation,
  726. 0,
  727. instanceNormalRight,
  728. instanceRotation
  729. );
  730. Matrix3.setColumn(instanceRotation, 1, instanceNormalUp, instanceRotation);
  731. Matrix3.setColumn(
  732. instanceRotation,
  733. 2,
  734. instanceNormalForward,
  735. instanceRotation
  736. );
  737. }
  738. Quaternion.fromRotationMatrix(instanceRotation, instanceQuaternion);
  739. }
  740. function processScale(featureTable, i, instanceScale) {
  741. instanceScale = Cartesian3.fromElements(1.0, 1.0, 1.0, instanceScale);
  742. const scale = featureTable.getProperty(
  743. "SCALE",
  744. ComponentDatatype.FLOAT,
  745. 1,
  746. i
  747. );
  748. if (defined(scale)) {
  749. Cartesian3.multiplyByScalar(instanceScale, scale, instanceScale);
  750. }
  751. const nonUniformScale = featureTable.getProperty(
  752. "SCALE_NON_UNIFORM",
  753. ComponentDatatype.FLOAT,
  754. 3,
  755. i,
  756. propertyScratch1
  757. );
  758. if (defined(nonUniformScale)) {
  759. instanceScale.x *= nonUniformScale[0];
  760. instanceScale.y *= nonUniformScale[1];
  761. instanceScale.z *= nonUniformScale[2];
  762. }
  763. }
  764. function unloadBuffers(loader) {
  765. const buffers = loader._buffers;
  766. const length = buffers.length;
  767. for (let i = 0; i < length; i++) {
  768. const buffer = buffers[i];
  769. if (!buffer.isDestroyed()) {
  770. buffer.destroy();
  771. }
  772. }
  773. buffers.length = 0;
  774. }
  775. I3dmLoader.prototype.isUnloaded = function () {
  776. return this._state === I3dmLoaderState.UNLOADED;
  777. };
  778. I3dmLoader.prototype.unload = function () {
  779. if (defined(this._gltfLoader) && !this._gltfLoader.isDestroyed()) {
  780. this._gltfLoader.unload();
  781. }
  782. unloadBuffers(this);
  783. this._components = undefined;
  784. this._arrayBuffer = undefined;
  785. this._state = I3dmLoaderState.UNLOADED;
  786. };
  787. export default I3dmLoader;