updateVersion.js 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. import addExtensionsUsed from './addExtensionsUsed.js'
  2. import addToArray from './addToArray.js'
  3. import findAccessorMinMax from './findAccessorMinMax.js'
  4. import ForEach from './ForEach.js'
  5. import getAccessorByteStride from './getAccessorByteStride.js'
  6. import numberOfComponentsForType from './numberOfComponentsForType.js'
  7. import moveTechniqueRenderStates from './moveTechniqueRenderStates.js'
  8. import moveTechniquesToExtension from './moveTechniquesToExtension.js'
  9. import removeUnusedElements from './removeUnusedElements.js'
  10. import updateAccessorComponentTypes from './updateAccessorComponentTypes.js'
  11. import Cartesian3 from '../../Core/Cartesian3.js'
  12. import Cartesian4 from '../../Core/Cartesian4.js'
  13. import clone from '../../Core/clone.js'
  14. import ComponentDatatype from '../../Core/ComponentDatatype.js'
  15. import defaultValue from '../../Core/defaultValue.js'
  16. import defined from '../../Core/defined.js'
  17. import Matrix4 from '../../Core/Matrix4.js'
  18. import Quaternion from '../../Core/Quaternion.js'
  19. import WebGLConstants from '../../Core/WebGLConstants.js'
  20. var updateFunctions = {
  21. '0.8': glTF08to10,
  22. '1.0': glTF10to20,
  23. '2.0': undefined
  24. };
  25. /**
  26. * Update the glTF version to the latest version (2.0), or targetVersion if specified.
  27. * Applies changes made to the glTF spec between revisions so that the core library
  28. * only has to handle the latest version.
  29. *
  30. * @param {Object} gltf A javascript object containing a glTF asset.
  31. * @param {Object} [options] Options for updating the glTF.
  32. * @param {String} [options.targetVersion] The glTF will be upgraded until it hits the specified version.
  33. * @returns {Object} The updated glTF asset.
  34. *
  35. * @private
  36. */
  37. function updateVersion(gltf, options) {
  38. options = defaultValue(options, defaultValue.EMPTY_OBJECT);
  39. var targetVersion = options.targetVersion;
  40. var version = gltf.version;
  41. gltf.asset = defaultValue(gltf.asset, {
  42. version: '1.0'
  43. });
  44. gltf.asset.version = defaultValue(gltf.asset.version, '1.0');
  45. version = defaultValue(version, gltf.asset.version).toString();
  46. // Invalid version
  47. if (!Object.prototype.hasOwnProperty.call(updateFunctions, version)) {
  48. // Try truncating trailing version numbers, could be a number as well if it is 0.8
  49. if (defined(version)) {
  50. version = version.substring(0, 3);
  51. }
  52. // Default to 1.0 if it cannot be determined
  53. if (!Object.prototype.hasOwnProperty.call(updateFunctions, version)) {
  54. version = '1.0';
  55. }
  56. }
  57. var updateFunction = updateFunctions[version];
  58. while (defined(updateFunction)) {
  59. if (version === targetVersion) {
  60. break;
  61. }
  62. updateFunction(gltf, options);
  63. version = gltf.asset.version;
  64. updateFunction = updateFunctions[version];
  65. }
  66. return gltf;
  67. }
  68. function updateInstanceTechniques(gltf) {
  69. var materials = gltf.materials;
  70. for (var materialId in materials) {
  71. if (Object.prototype.hasOwnProperty.call(materials, materialId)) {
  72. var material = materials[materialId];
  73. var instanceTechnique = material.instanceTechnique;
  74. if (defined(instanceTechnique)) {
  75. material.technique = instanceTechnique.technique;
  76. material.values = instanceTechnique.values;
  77. delete material.instanceTechnique;
  78. }
  79. }
  80. }
  81. }
  82. function setPrimitiveModes(gltf) {
  83. var meshes = gltf.meshes;
  84. for (var meshId in meshes) {
  85. if (Object.prototype.hasOwnProperty.call(meshes, meshId)) {
  86. var mesh = meshes[meshId];
  87. var primitives = mesh.primitives;
  88. if (defined(primitives)) {
  89. var primitivesLength = primitives.length;
  90. for (var i = 0; i < primitivesLength; ++i) {
  91. var primitive = primitives[i];
  92. var defaultMode = defaultValue(primitive.primitive, WebGLConstants.TRIANGLES);
  93. primitive.mode = defaultValue(primitive.mode, defaultMode);
  94. delete primitive.primitive;
  95. }
  96. }
  97. }
  98. }
  99. }
  100. function updateNodes(gltf) {
  101. var nodes = gltf.nodes;
  102. var axis = new Cartesian3();
  103. var quat = new Quaternion();
  104. for (var nodeId in nodes) {
  105. if (Object.prototype.hasOwnProperty.call(nodes, nodeId)) {
  106. var node = nodes[nodeId];
  107. if (defined(node.rotation)) {
  108. var rotation = node.rotation;
  109. Cartesian3.fromArray(rotation, 0, axis);
  110. Quaternion.fromAxisAngle(axis, rotation[3], quat);
  111. node.rotation = [quat.x, quat.y, quat.z, quat.w];
  112. }
  113. var instanceSkin = node.instanceSkin;
  114. if (defined(instanceSkin)) {
  115. node.skeletons = instanceSkin.skeletons;
  116. node.skin = instanceSkin.skin;
  117. node.meshes = instanceSkin.meshes;
  118. delete node.instanceSkin;
  119. }
  120. }
  121. }
  122. }
  123. function updateAnimations(gltf) {
  124. var animations = gltf.animations;
  125. var accessors = gltf.accessors;
  126. var bufferViews = gltf.bufferViews;
  127. var buffers = gltf.buffers;
  128. var updatedAccessors = {};
  129. var axis = new Cartesian3();
  130. var quat = new Quaternion();
  131. for (var animationId in animations) {
  132. if (Object.prototype.hasOwnProperty.call(animations, animationId)) {
  133. var animation = animations[animationId];
  134. var channels = animation.channels;
  135. var parameters = animation.parameters;
  136. var samplers = animation.samplers;
  137. if (defined(channels)) {
  138. var channelsLength = channels.length;
  139. for (var i = 0; i < channelsLength; ++i) {
  140. var channel = channels[i];
  141. if (channel.target.path === 'rotation') {
  142. var accessorId = parameters[samplers[channel.sampler].output];
  143. if (defined(updatedAccessors[accessorId])) {
  144. continue;
  145. }
  146. updatedAccessors[accessorId] = true;
  147. var accessor = accessors[accessorId];
  148. var bufferView = bufferViews[accessor.bufferView];
  149. var buffer = buffers[bufferView.buffer];
  150. var source = buffer.extras._pipeline.source;
  151. var byteOffset = source.byteOffset + bufferView.byteOffset + accessor.byteOffset;
  152. var componentType = accessor.componentType;
  153. var count = accessor.count;
  154. var componentsLength = numberOfComponentsForType(accessor.type);
  155. var length = accessor.count * componentsLength;
  156. var typedArray = ComponentDatatype.createArrayBufferView(componentType, source.buffer, byteOffset, length);
  157. for (var j = 0; j < count; j++) {
  158. var offset = j * componentsLength;
  159. Cartesian3.unpack(typedArray, offset, axis);
  160. var angle = typedArray[offset + 3];
  161. Quaternion.fromAxisAngle(axis, angle, quat);
  162. Quaternion.pack(quat, typedArray, offset);
  163. }
  164. }
  165. }
  166. }
  167. }
  168. }
  169. }
  170. function removeTechniquePasses(gltf) {
  171. var techniques = gltf.techniques;
  172. for (var techniqueId in techniques) {
  173. if (Object.prototype.hasOwnProperty.call(techniques, techniqueId)) {
  174. var technique = techniques[techniqueId];
  175. var passes = technique.passes;
  176. if (defined(passes)) {
  177. var passName = defaultValue(technique.pass, 'defaultPass');
  178. if (Object.prototype.hasOwnProperty.call(passes, passName)) {
  179. var pass = passes[passName];
  180. var instanceProgram = pass.instanceProgram;
  181. technique.attributes = defaultValue(technique.attributes, instanceProgram.attributes);
  182. technique.program = defaultValue(technique.program, instanceProgram.program);
  183. technique.uniforms = defaultValue(technique.uniforms, instanceProgram.uniforms);
  184. technique.states = defaultValue(technique.states, pass.states);
  185. }
  186. delete technique.passes;
  187. delete technique.pass;
  188. }
  189. }
  190. }
  191. }
  192. function glTF08to10(gltf) {
  193. if (!defined(gltf.asset)) {
  194. gltf.asset = {};
  195. }
  196. var asset = gltf.asset;
  197. asset.version = '1.0';
  198. // Profile should be an object, not a string
  199. if (typeof asset.profile === 'string') {
  200. var split = asset.profile.split(' ');
  201. asset.profile = {
  202. api: split[0],
  203. version: split[1]
  204. };
  205. } else {
  206. asset.profile = {};
  207. }
  208. // Version property should be in asset, not on the root element
  209. if (defined(gltf.version)) {
  210. delete gltf.version;
  211. }
  212. // material.instanceTechnique properties should be directly on the material
  213. updateInstanceTechniques(gltf);
  214. // primitive.primitive should be primitive.mode
  215. setPrimitiveModes(gltf);
  216. // Node rotation should be quaternion, not axis-angle
  217. // node.instanceSkin is deprecated
  218. updateNodes(gltf);
  219. // Animations that target rotations should be quaternion, not axis-angle
  220. updateAnimations(gltf);
  221. // technique.pass and techniques.passes are deprecated
  222. removeTechniquePasses(gltf);
  223. // gltf.allExtensions -> extensionsUsed
  224. if (defined(gltf.allExtensions)) {
  225. gltf.extensionsUsed = gltf.allExtensions;
  226. delete gltf.allExtensions;
  227. }
  228. // gltf.lights -> khrMaterialsCommon.lights
  229. if (defined(gltf.lights)) {
  230. var extensions = defaultValue(gltf.extensions, {});
  231. gltf.extensions = extensions;
  232. var materialsCommon = defaultValue(extensions.KHR_materials_common, {});
  233. extensions.KHR_materials_common = materialsCommon;
  234. materialsCommon.lights = gltf.lights;
  235. delete gltf.lights;
  236. addExtensionsUsed(gltf, 'KHR_materials_common');
  237. }
  238. }
  239. function removeAnimationSamplersIndirection(gltf) {
  240. var animations = gltf.animations;
  241. for (var animationId in animations) {
  242. if (Object.prototype.hasOwnProperty.call(animations, animationId)) {
  243. var animation = animations[animationId];
  244. var parameters = animation.parameters;
  245. if (defined(parameters)) {
  246. var samplers = animation.samplers;
  247. for (var samplerId in samplers) {
  248. if (Object.prototype.hasOwnProperty.call(samplers, samplerId)) {
  249. var sampler = samplers[samplerId];
  250. sampler.input = parameters[sampler.input];
  251. sampler.output = parameters[sampler.output];
  252. }
  253. }
  254. delete animation.parameters;
  255. }
  256. }
  257. }
  258. }
  259. function objectToArray(object, mapping) {
  260. var array = [];
  261. for (var id in object) {
  262. if (Object.prototype.hasOwnProperty.call(object, id)) {
  263. var value = object[id];
  264. mapping[id] = array.length;
  265. array.push(value);
  266. if (!defined(value.name)) {
  267. value.name = id;
  268. }
  269. }
  270. }
  271. return array;
  272. }
  273. function objectsToArrays(gltf) {
  274. var i;
  275. var globalMapping = {
  276. accessors: {},
  277. animations: {},
  278. buffers: {},
  279. bufferViews: {},
  280. cameras: {},
  281. images: {},
  282. materials: {},
  283. meshes: {},
  284. nodes: {},
  285. programs: {},
  286. samplers: {},
  287. scenes: {},
  288. shaders: {},
  289. skins: {},
  290. textures: {},
  291. techniques: {}
  292. };
  293. // Map joint names to id names
  294. var jointName;
  295. var jointNameToId = {};
  296. var nodes = gltf.nodes;
  297. for (var id in nodes) {
  298. if (Object.prototype.hasOwnProperty.call(nodes, id)) {
  299. jointName = nodes[id].jointName;
  300. if (defined(jointName)) {
  301. jointNameToId[jointName] = id;
  302. }
  303. }
  304. }
  305. // Convert top level objects to arrays
  306. for (var topLevelId in gltf) {
  307. if (Object.prototype.hasOwnProperty.call(gltf, topLevelId) && defined(globalMapping[topLevelId])) {
  308. var objectMapping = {};
  309. var object = gltf[topLevelId];
  310. gltf[topLevelId] = objectToArray(object, objectMapping);
  311. globalMapping[topLevelId] = objectMapping;
  312. }
  313. }
  314. // Remap joint names to array indexes
  315. for (jointName in jointNameToId) {
  316. if (Object.prototype.hasOwnProperty.call(jointNameToId, jointName)) {
  317. jointNameToId[jointName] = globalMapping.nodes[jointNameToId[jointName]];
  318. }
  319. }
  320. // Fix references
  321. if (defined(gltf.scene)) {
  322. gltf.scene = globalMapping.scenes[gltf.scene];
  323. }
  324. ForEach.bufferView(gltf, function(bufferView) {
  325. if (defined(bufferView.buffer)) {
  326. bufferView.buffer = globalMapping.buffers[bufferView.buffer];
  327. }
  328. });
  329. ForEach.accessor(gltf, function(accessor) {
  330. if (defined(accessor.bufferView)) {
  331. accessor.bufferView = globalMapping.bufferViews[accessor.bufferView];
  332. }
  333. });
  334. ForEach.shader(gltf, function(shader) {
  335. var extensions = shader.extensions;
  336. if (defined(extensions)) {
  337. var binaryGltf = extensions.KHR_binary_glTF;
  338. if (defined(binaryGltf)) {
  339. shader.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];
  340. delete extensions.KHR_binary_glTF;
  341. }
  342. if (Object.keys(extensions).length === 0) {
  343. delete shader.extensions;
  344. }
  345. }
  346. });
  347. ForEach.program(gltf, function(program) {
  348. if (defined(program.vertexShader)) {
  349. program.vertexShader = globalMapping.shaders[program.vertexShader];
  350. }
  351. if (defined(program.fragmentShader)) {
  352. program.fragmentShader = globalMapping.shaders[program.fragmentShader];
  353. }
  354. });
  355. ForEach.technique(gltf, function(technique) {
  356. if (defined(technique.program)) {
  357. technique.program = globalMapping.programs[technique.program];
  358. }
  359. ForEach.techniqueParameter(technique, function(parameter) {
  360. if (defined(parameter.node)) {
  361. parameter.node = globalMapping.nodes[parameter.node];
  362. }
  363. var value = parameter.value;
  364. if (typeof value === 'string') {
  365. parameter.value = {
  366. index: globalMapping.textures[value]
  367. };
  368. }
  369. });
  370. });
  371. ForEach.mesh(gltf, function(mesh) {
  372. ForEach.meshPrimitive(mesh, function(primitive) {
  373. if (defined(primitive.indices)) {
  374. primitive.indices = globalMapping.accessors[primitive.indices];
  375. }
  376. ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) {
  377. primitive.attributes[semantic] = globalMapping.accessors[accessorId];
  378. });
  379. if (defined(primitive.material)) {
  380. primitive.material = globalMapping.materials[primitive.material];
  381. }
  382. });
  383. });
  384. ForEach.node(gltf, function(node) {
  385. var children = node.children;
  386. if (defined(children)) {
  387. var childrenLength = children.length;
  388. for (i = 0; i < childrenLength; ++i) {
  389. children[i] = globalMapping.nodes[children[i]];
  390. }
  391. }
  392. if (defined(node.meshes)) {
  393. // Split out meshes on nodes
  394. var meshes = node.meshes;
  395. var meshesLength = meshes.length;
  396. if (meshesLength > 0) {
  397. node.mesh = globalMapping.meshes[meshes[0]];
  398. for (i = 1; i < meshesLength; ++i) {
  399. var meshNode = {
  400. mesh: globalMapping.meshes[meshes[i]]
  401. };
  402. var meshNodeId = addToArray(gltf.nodes, meshNode);
  403. if (!defined(children)) {
  404. children = [];
  405. node.children = children;
  406. }
  407. children.push(meshNodeId);
  408. }
  409. }
  410. delete node.meshes;
  411. }
  412. if (defined(node.camera)) {
  413. node.camera = globalMapping.cameras[node.camera];
  414. }
  415. if (defined(node.skin)) {
  416. node.skin = globalMapping.skins[node.skin];
  417. }
  418. if (defined(node.skeletons)) {
  419. // Assign skeletons to skins
  420. var skeletons = node.skeletons;
  421. var skeletonsLength = skeletons.length;
  422. if ((skeletonsLength > 0) && defined(node.skin)) {
  423. var skin = gltf.skins[node.skin];
  424. skin.skeleton = globalMapping.nodes[skeletons[0]];
  425. }
  426. delete node.skeletons;
  427. }
  428. if (defined(node.jointName)) {
  429. delete node.jointName;
  430. }
  431. });
  432. ForEach.skin(gltf, function(skin) {
  433. if (defined(skin.inverseBindMatrices)) {
  434. skin.inverseBindMatrices = globalMapping.accessors[skin.inverseBindMatrices];
  435. }
  436. var jointNames = skin.jointNames;
  437. if (defined(jointNames)) {
  438. var joints = [];
  439. var jointNamesLength = jointNames.length;
  440. for (i = 0; i < jointNamesLength; ++i) {
  441. joints[i] = jointNameToId[jointNames[i]];
  442. }
  443. skin.joints = joints;
  444. delete skin.jointNames;
  445. }
  446. });
  447. ForEach.scene(gltf, function(scene) {
  448. var sceneNodes = scene.nodes;
  449. if (defined(sceneNodes)) {
  450. var sceneNodesLength = sceneNodes.length;
  451. for (i = 0; i < sceneNodesLength; ++i) {
  452. sceneNodes[i] = globalMapping.nodes[sceneNodes[i]];
  453. }
  454. }
  455. });
  456. ForEach.animation(gltf, function(animation) {
  457. var samplerMapping = {};
  458. animation.samplers = objectToArray(animation.samplers, samplerMapping);
  459. ForEach.animationSampler(animation, function(sampler) {
  460. sampler.input = globalMapping.accessors[sampler.input];
  461. sampler.output = globalMapping.accessors[sampler.output];
  462. });
  463. ForEach.animationChannel(animation, function(channel) {
  464. channel.sampler = samplerMapping[channel.sampler];
  465. var target = channel.target;
  466. if (defined(target)) {
  467. target.node = globalMapping.nodes[target.id];
  468. delete target.id;
  469. }
  470. });
  471. });
  472. ForEach.material(gltf, function(material) {
  473. if (defined(material.technique)) {
  474. material.technique = globalMapping.techniques[material.technique];
  475. }
  476. ForEach.materialValue(material, function(value, name) {
  477. if (typeof value === 'string') {
  478. material.values[name] = {
  479. index: globalMapping.textures[value]
  480. };
  481. }
  482. });
  483. var extensions = material.extensions;
  484. if (defined(extensions)) {
  485. var materialsCommon = extensions.KHR_materials_common;
  486. if (defined(materialsCommon)) {
  487. ForEach.materialValue(materialsCommon, function(value, name) {
  488. if (typeof value === 'string') {
  489. materialsCommon.values[name] = {
  490. index: globalMapping.textures[value]
  491. };
  492. }
  493. });
  494. }
  495. }
  496. });
  497. ForEach.image(gltf, function(image) {
  498. var extensions = image.extensions;
  499. if (defined(extensions)) {
  500. var binaryGltf = extensions.KHR_binary_glTF;
  501. if (defined(binaryGltf)) {
  502. image.bufferView = globalMapping.bufferViews[binaryGltf.bufferView];
  503. image.mimeType = binaryGltf.mimeType;
  504. delete extensions.KHR_binary_glTF;
  505. }
  506. if (Object.keys(extensions).length === 0) {
  507. delete image.extensions;
  508. }
  509. }
  510. ForEach.compressedImage(image, function(compressedImage) {
  511. var compressedExtensions = compressedImage.extensions;
  512. if (defined(compressedExtensions)) {
  513. var compressedBinaryGltf = compressedExtensions.KHR_binary_glTF;
  514. if (defined(compressedBinaryGltf)) {
  515. compressedImage.bufferView = globalMapping.bufferViews[compressedBinaryGltf.bufferView];
  516. compressedImage.mimeType = compressedBinaryGltf.mimeType;
  517. delete compressedExtensions.KHR_binary_glTF;
  518. }
  519. if (Object.keys(extensions).length === 0) {
  520. delete compressedImage.extensions;
  521. }
  522. }
  523. });
  524. });
  525. ForEach.texture(gltf, function(texture) {
  526. if (defined(texture.sampler)) {
  527. texture.sampler = globalMapping.samplers[texture.sampler];
  528. }
  529. if (defined(texture.source)) {
  530. texture.source = globalMapping.images[texture.source];
  531. }
  532. });
  533. }
  534. function removeAnimationSamplerNames(gltf) {
  535. ForEach.animation(gltf, function(animation) {
  536. ForEach.animationSampler(animation, function(sampler) {
  537. delete sampler.name;
  538. });
  539. });
  540. }
  541. function removeEmptyArrays(gltf) {
  542. for (var topLevelId in gltf) {
  543. if (Object.prototype.hasOwnProperty.call(gltf, topLevelId)) {
  544. var array = gltf[topLevelId];
  545. if (Array.isArray(array) && array.length === 0) {
  546. delete gltf[topLevelId];
  547. }
  548. }
  549. }
  550. ForEach.node(gltf, function(node) {
  551. if (defined(node.children) && node.children.length === 0) {
  552. delete node.children;
  553. }
  554. });
  555. }
  556. function stripAsset(gltf) {
  557. var asset = gltf.asset;
  558. delete asset.profile;
  559. delete asset.premultipliedAlpha;
  560. }
  561. var knownExtensions = {
  562. CESIUM_RTC: true,
  563. KHR_materials_common: true,
  564. WEB3D_quantized_attributes: true
  565. };
  566. function requireKnownExtensions(gltf) {
  567. var extensionsUsed = gltf.extensionsUsed;
  568. gltf.extensionsRequired = defaultValue(gltf.extensionsRequired, []);
  569. if (defined(extensionsUsed)) {
  570. var extensionsUsedLength = extensionsUsed.length;
  571. for (var i = 0; i < extensionsUsedLength; ++i) {
  572. var extension = extensionsUsed[i];
  573. if (defined(knownExtensions[extension])) {
  574. gltf.extensionsRequired.push(extension);
  575. }
  576. }
  577. }
  578. }
  579. function removeBufferType(gltf) {
  580. ForEach.buffer(gltf, function(buffer) {
  581. delete buffer.type;
  582. });
  583. }
  584. function removeTextureProperties(gltf) {
  585. ForEach.texture(gltf, function(texture) {
  586. delete texture.format;
  587. delete texture.internalFormat;
  588. delete texture.target;
  589. delete texture.type;
  590. });
  591. }
  592. function requireAttributeSetIndex(gltf) {
  593. ForEach.mesh(gltf, function(mesh) {
  594. ForEach.meshPrimitive(mesh, function(primitive) {
  595. ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) {
  596. if (semantic === 'TEXCOORD') {
  597. primitive.attributes.TEXCOORD_0 = accessorId;
  598. } else if (semantic === 'COLOR') {
  599. primitive.attributes.COLOR_0 = accessorId;
  600. }
  601. });
  602. delete primitive.attributes.TEXCOORD;
  603. delete primitive.attributes.COLOR;
  604. });
  605. });
  606. ForEach.technique(gltf, function(technique) {
  607. ForEach.techniqueParameter(technique, function(parameter) {
  608. var semantic = parameter.semantic;
  609. if (defined(semantic)) {
  610. if (semantic === 'TEXCOORD') {
  611. parameter.semantic = 'TEXCOORD_0';
  612. } else if (semantic === 'COLOR') {
  613. parameter.semantic = 'COLOR_0';
  614. }
  615. }
  616. });
  617. });
  618. }
  619. var knownSemantics = {
  620. POSITION: true,
  621. NORMAL: true,
  622. TANGENT: true
  623. };
  624. var indexedSemantics = {
  625. COLOR: 'COLOR',
  626. JOINT : 'JOINTS',
  627. JOINTS: 'JOINTS',
  628. TEXCOORD: 'TEXCOORD',
  629. WEIGHT: 'WEIGHTS',
  630. WEIGHTS: 'WEIGHTS'
  631. };
  632. function underscoreApplicationSpecificSemantics(gltf) {
  633. var mappedSemantics = {};
  634. ForEach.mesh(gltf, function(mesh) {
  635. ForEach.meshPrimitive(mesh, function(primitive) {
  636. /*eslint-disable no-unused-vars*/
  637. ForEach.meshPrimitiveAttribute(primitive, function(accessorId, semantic) {
  638. if (semantic.charAt(0) !== '_') {
  639. var setIndex = semantic.search(/_[0-9]+/g);
  640. var strippedSemantic = semantic;
  641. var suffix = '_0';
  642. if (setIndex >= 0) {
  643. strippedSemantic = semantic.substring(0, setIndex);
  644. suffix = semantic.substring(setIndex);
  645. }
  646. var newSemantic;
  647. var indexedSemantic = indexedSemantics[strippedSemantic];
  648. if (defined(indexedSemantic)) {
  649. newSemantic = indexedSemantic + suffix;
  650. mappedSemantics[semantic] = newSemantic;
  651. } else if (!defined(knownSemantics[strippedSemantic])) {
  652. newSemantic = '_' + semantic;
  653. mappedSemantics[semantic] = newSemantic;
  654. }
  655. }
  656. });
  657. for (var semantic in mappedSemantics) {
  658. if (Object.prototype.hasOwnProperty.call(mappedSemantics, semantic)) {
  659. var mappedSemantic = mappedSemantics[semantic];
  660. var accessorId = primitive.attributes[semantic];
  661. if (defined(accessorId)) {
  662. delete primitive.attributes[semantic];
  663. primitive.attributes[mappedSemantic] = accessorId;
  664. }
  665. }
  666. }
  667. });
  668. });
  669. ForEach.technique(gltf, function(technique) {
  670. ForEach.techniqueParameter(technique, function(parameter) {
  671. var mappedSemantic = mappedSemantics[parameter.semantic];
  672. if (defined(mappedSemantic)) {
  673. parameter.semantic = mappedSemantic;
  674. }
  675. });
  676. });
  677. }
  678. function clampCameraParameters(gltf) {
  679. ForEach.camera(gltf, function(camera) {
  680. var perspective = camera.perspective;
  681. if (defined(perspective)) {
  682. var aspectRatio = perspective.aspectRatio;
  683. if (defined(aspectRatio) && aspectRatio === 0.0) {
  684. delete perspective.aspectRatio;
  685. }
  686. var yfov = perspective.yfov;
  687. if (defined(yfov) && yfov === 0.0) {
  688. perspective.yfov = 1.0;
  689. }
  690. }
  691. });
  692. }
  693. function computeAccessorByteStride(gltf, accessor) {
  694. return (defined(accessor.byteStride) && accessor.byteStride !== 0) ? accessor.byteStride : getAccessorByteStride(gltf, accessor);
  695. }
  696. function requireByteLength(gltf) {
  697. ForEach.buffer(gltf, function(buffer) {
  698. if (!defined(buffer.byteLength)) {
  699. buffer.byteLength = buffer.extras._pipeline.source.length;
  700. }
  701. });
  702. ForEach.accessor(gltf, function(accessor) {
  703. var bufferViewId = accessor.bufferView;
  704. if (defined(bufferViewId)) {
  705. var bufferView = gltf.bufferViews[bufferViewId];
  706. var accessorByteStride = computeAccessorByteStride(gltf, accessor);
  707. var accessorByteEnd = accessor.byteOffset + accessor.count * accessorByteStride;
  708. bufferView.byteLength = Math.max(defaultValue(bufferView.byteLength, 0), accessorByteEnd);
  709. }
  710. });
  711. }
  712. function moveByteStrideToBufferView(gltf) {
  713. var i;
  714. var j;
  715. var bufferView;
  716. var bufferViews = gltf.bufferViews;
  717. var bufferViewHasVertexAttributes = {};
  718. ForEach.accessorContainingVertexAttributeData(gltf, function(accessorId) {
  719. var accessor = gltf.accessors[accessorId];
  720. if (defined(accessor.bufferView)) {
  721. bufferViewHasVertexAttributes[accessor.bufferView] = true;
  722. }
  723. });
  724. // Map buffer views to a list of accessors
  725. var bufferViewMap = {};
  726. ForEach.accessor(gltf, function(accessor) {
  727. if (defined(accessor.bufferView)) {
  728. bufferViewMap[accessor.bufferView] = defaultValue(bufferViewMap[accessor.bufferView], []);
  729. bufferViewMap[accessor.bufferView].push(accessor);
  730. }
  731. });
  732. // Split accessors with different byte strides
  733. for (var bufferViewId in bufferViewMap) {
  734. if (Object.prototype.hasOwnProperty.call(bufferViewMap, bufferViewId)) {
  735. bufferView = bufferViews[bufferViewId];
  736. var accessors = bufferViewMap[bufferViewId];
  737. accessors.sort(function(a, b) {
  738. return a.byteOffset - b.byteOffset;
  739. });
  740. var currentByteOffset = 0;
  741. var currentIndex = 0;
  742. var accessorsLength = accessors.length;
  743. for (i = 0; i < accessorsLength; ++i) {
  744. var accessor = accessors[i];
  745. var accessorByteStride = computeAccessorByteStride(gltf, accessor);
  746. var accessorByteOffset = accessor.byteOffset;
  747. var accessorByteLength = accessor.count * accessorByteStride;
  748. delete accessor.byteStride;
  749. var hasNextAccessor = (i < accessorsLength - 1);
  750. var nextAccessorByteStride = hasNextAccessor ? computeAccessorByteStride(gltf, accessors[i + 1]) : undefined;
  751. if (accessorByteStride !== nextAccessorByteStride) {
  752. var newBufferView = clone(bufferView, true);
  753. if (bufferViewHasVertexAttributes[bufferViewId]) {
  754. newBufferView.byteStride = accessorByteStride;
  755. }
  756. newBufferView.byteOffset += currentByteOffset;
  757. newBufferView.byteLength = accessorByteOffset + accessorByteLength - currentByteOffset;
  758. var newBufferViewId = addToArray(bufferViews, newBufferView);
  759. for (j = currentIndex; j <= i; ++j) {
  760. accessor = accessors[j];
  761. accessor.bufferView = newBufferViewId;
  762. accessor.byteOffset = accessor.byteOffset - currentByteOffset;
  763. }
  764. // Set current byte offset to next accessor's byte offset
  765. currentByteOffset = hasNextAccessor ? accessors[i + 1].byteOffset : undefined;
  766. currentIndex = i + 1;
  767. }
  768. }
  769. }
  770. }
  771. // Remove unused buffer views
  772. removeUnusedElements(gltf, ['accessor', 'bufferView', 'buffer']);
  773. }
  774. function requirePositionAccessorMinMax(gltf) {
  775. ForEach.accessorWithSemantic(gltf, 'POSITION', function(accessorId) {
  776. var accessor = gltf.accessors[accessorId];
  777. if (!defined(accessor.min) || !defined(accessor.max)) {
  778. var minMax = findAccessorMinMax(gltf, accessor);
  779. accessor.min = minMax.min;
  780. accessor.max = minMax.max;
  781. }
  782. });
  783. }
  784. function isNodeEmpty(node) {
  785. return (!defined(node.children) || node.children.length === 0) &&
  786. (!defined(node.meshes) || node.meshes.length === 0) &&
  787. !defined(node.camera) && !defined(node.skin) && !defined(node.skeletons) && !defined(node.jointName) &&
  788. (!defined(node.translation) || Cartesian3.fromArray(node.translation).equals(Cartesian3.ZERO)) &&
  789. (!defined(node.scale) || Cartesian3.fromArray(node.scale).equals(new Cartesian3(1.0, 1.0, 1.0))) &&
  790. (!defined(node.rotation) || Cartesian4.fromArray(node.rotation).equals(new Cartesian4(0.0, 0.0, 0.0, 1.0))) &&
  791. (!defined(node.matrix) || Matrix4.fromColumnMajorArray(node.matrix).equals(Matrix4.IDENTITY)) &&
  792. !defined(node.extensions) && !defined(node.extras);
  793. }
  794. function deleteNode(gltf, nodeId) {
  795. // Remove from list of nodes in scene
  796. ForEach.scene(gltf, function(scene) {
  797. var sceneNodes = scene.nodes;
  798. if (defined(sceneNodes)) {
  799. var sceneNodesLength = sceneNodes.length;
  800. for (var i = sceneNodesLength; i >= 0; --i) {
  801. if (sceneNodes[i] === nodeId) {
  802. sceneNodes.splice(i, 1);
  803. return;
  804. }
  805. }
  806. }
  807. });
  808. // Remove parent node's reference to this node, and delete the parent if also empty
  809. ForEach.node(gltf, function(parentNode, parentNodeId) {
  810. if (defined(parentNode.children)) {
  811. var index = parentNode.children.indexOf(nodeId);
  812. if (index > -1) {
  813. parentNode.children.splice(index, 1);
  814. if (isNodeEmpty(parentNode)) {
  815. deleteNode(gltf, parentNodeId);
  816. }
  817. }
  818. }
  819. });
  820. delete gltf.nodes[nodeId];
  821. }
  822. function removeEmptyNodes(gltf) {
  823. ForEach.node(gltf, function(node, nodeId) {
  824. if (isNodeEmpty(node)) {
  825. deleteNode(gltf, nodeId);
  826. }
  827. });
  828. return gltf;
  829. }
  830. function requireAnimationAccessorMinMax(gltf) {
  831. ForEach.animation(gltf, function(animation) {
  832. ForEach.animationSampler(animation, function(sampler) {
  833. var accessor = gltf.accessors[sampler.input];
  834. if (!defined(accessor.min) || !defined(accessor.max)) {
  835. var minMax = findAccessorMinMax(gltf, accessor);
  836. accessor.min = minMax.min;
  837. accessor.max = minMax.max;
  838. }
  839. });
  840. });
  841. }
  842. function glTF10to20(gltf) {
  843. gltf.asset = defaultValue(gltf.asset, {});
  844. gltf.asset.version = '2.0';
  845. // material.instanceTechnique properties should be directly on the material. instanceTechnique is a gltf 0.8 property but is seen in some 1.0 models.
  846. updateInstanceTechniques(gltf);
  847. // animation.samplers now refers directly to accessors and animation.parameters should be removed
  848. removeAnimationSamplersIndirection(gltf);
  849. // Remove empty nodes and re-assign referencing indices
  850. removeEmptyNodes(gltf);
  851. // Top-level objects are now arrays referenced by index instead of id
  852. objectsToArrays(gltf);
  853. // Animation.sampler objects cannot have names
  854. removeAnimationSamplerNames(gltf);
  855. // asset.profile no longer exists
  856. stripAsset(gltf);
  857. // Move known extensions from extensionsUsed to extensionsRequired
  858. requireKnownExtensions(gltf);
  859. // bufferView.byteLength and buffer.byteLength are required
  860. requireByteLength(gltf);
  861. // byteStride moved from accessor to bufferView
  862. moveByteStrideToBufferView(gltf);
  863. // accessor.min and accessor.max must be defined for accessors containing POSITION attributes
  864. requirePositionAccessorMinMax(gltf);
  865. // An animation sampler's input accessor must have min and max properties defined
  866. requireAnimationAccessorMinMax(gltf);
  867. // buffer.type is unnecessary and should be removed
  868. removeBufferType(gltf);
  869. // Remove format, internalFormat, target, and type
  870. removeTextureProperties(gltf);
  871. // TEXCOORD and COLOR attributes must be written with a set index (TEXCOORD_#)
  872. requireAttributeSetIndex(gltf);
  873. // Add underscores to application-specific parameters
  874. underscoreApplicationSpecificSemantics(gltf);
  875. // Accessors referenced by JOINTS_0 and WEIGHTS_0 attributes must have correct component types
  876. updateAccessorComponentTypes(gltf);
  877. // Clamp camera parameters
  878. clampCameraParameters(gltf);
  879. // Move legacy technique render states to material properties and add KHR_blend extension blending functions
  880. moveTechniqueRenderStates(gltf);
  881. // Add material techniques to KHR_techniques_webgl extension, removing shaders, programs, and techniques
  882. moveTechniquesToExtension(gltf);
  883. // Remove empty arrays
  884. removeEmptyArrays(gltf);
  885. }
  886. export default updateVersion;