babylon.glTFLoader.ts 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF2 {
  3. var getNodeID = (index: number): string => {
  4. return "node" + index;
  5. };
  6. var loadAnimation = (runtime: IGLTFRuntime, animation: IGLTFAnimation, animationIndex: number): void => {
  7. for (var channelIndex = 0; channelIndex < animation.channels.length; channelIndex++) {
  8. var channel = animation.channels[channelIndex];
  9. if (!channel) {
  10. Tools.Warn("[Animation " + animationIndex + "] Channel " + channelIndex + " does not exist");
  11. continue;
  12. }
  13. var samplerIndex = channel.sampler;
  14. if (samplerIndex === undefined) {
  15. Tools.Warn("[Animation " + animationIndex + ", Channel + " + samplerIndex + "] Sampler is not defined");
  16. continue;
  17. }
  18. var sampler = animation.samplers[samplerIndex];
  19. if (!sampler) {
  20. Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Sampler " + samplerIndex + " does not exist");
  21. continue;
  22. }
  23. if (!channel.target) {
  24. Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Target does not exist");
  25. continue;
  26. }
  27. var targetNode = runtime.babylonScene.getNodeByID(getNodeID(channel.target.node));
  28. if (!targetNode) {
  29. Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Target node " + channel.target.node + " does not exist");
  30. continue;
  31. }
  32. var targetPath = {
  33. "translation": "position",
  34. "rotation": "rotationQuaternion",
  35. "scale": "scaling",
  36. "weights": "influence"
  37. }[channel.target.path];
  38. if (!targetPath) {
  39. Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Target path " + channel.target.path + " is invalid");
  40. continue;
  41. }
  42. if (targetNode instanceof Bone) {
  43. // TODO: Fix bones
  44. continue;
  45. }
  46. var inputBuffer = <Float32Array>GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[sampler.input]);
  47. var outputBuffer = <Float32Array>GLTFUtils.GetBufferFromAccessor(runtime, runtime.gltf.accessors[sampler.output]);
  48. var outputBufferOffset = 0;
  49. var getNextOutputValue: () => any = {
  50. "position": () => {
  51. var value = Vector3.FromArray(outputBuffer, outputBufferOffset);
  52. outputBufferOffset += 3;
  53. return value;
  54. },
  55. "rotationQuaternion": () => {
  56. var value = Quaternion.FromArray(outputBuffer, outputBufferOffset);
  57. outputBufferOffset += 4;
  58. return value;
  59. },
  60. "scale": () => {
  61. var value = Vector3.FromArray(outputBuffer, outputBufferOffset);
  62. outputBufferOffset += 3;
  63. return value;
  64. },
  65. "influence": () => {
  66. var numTargets = (<Mesh>targetNode).morphTargetManager.numTargets;
  67. var value = new Array(numTargets);
  68. for (var i = 0; i < numTargets; i++) {
  69. value[i] = outputBuffer[outputBufferOffset++];
  70. }
  71. return value;
  72. },
  73. }[targetPath];
  74. var getNextKey: (frameIndex) => any = {
  75. "LINEAR": frameIndex => ({
  76. frame: inputBuffer[frameIndex],
  77. value: getNextOutputValue()
  78. }),
  79. "CUBICSPLINE": frameIndex => ({
  80. frame: inputBuffer[frameIndex],
  81. inTangent: getNextOutputValue(),
  82. value: getNextOutputValue(),
  83. outTangent: getNextOutputValue()
  84. })
  85. }[sampler.interpolation];
  86. if (!getNextKey) {
  87. Tools.Warn("[Animation " + animationIndex + ", Channel + " + channelIndex + "] Sampler interpolation '" + sampler.interpolation + "' is invalid");
  88. continue;
  89. }
  90. var keys = new Array(inputBuffer.length);
  91. for (var frameIndex = 0; frameIndex < inputBuffer.length; frameIndex++) {
  92. keys[frameIndex] = getNextKey(frameIndex);
  93. }
  94. if (targetPath === "influence") {
  95. var targetMesh = <Mesh>targetNode;
  96. for (var targetIndex = 0; targetIndex < targetMesh.morphTargetManager.numTargets; targetIndex++) {
  97. var morphTarget = targetMesh.morphTargetManager.getTarget(targetIndex);
  98. var animationName = (animation.name || "anim" + animationIndex) + "_" + targetIndex;
  99. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, BABYLON.Animation.ANIMATIONTYPE_FLOAT);
  100. babylonAnimation.setKeys(keys.map(key => ({
  101. frame: key.frame,
  102. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  103. value: key.value[targetIndex],
  104. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  105. })));
  106. morphTarget.animations.push(babylonAnimation);
  107. runtime.babylonScene.beginAnimation(morphTarget, 0, inputBuffer[inputBuffer.length - 1], true);
  108. }
  109. }
  110. else {
  111. var targetMesh = <Mesh>targetNode;
  112. var animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  113. if (targetPath === "rotationQuaternion") {
  114. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  115. targetMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  116. }
  117. var animationName = animation.name || "anim" + animationIndex;
  118. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  119. babylonAnimation.setKeys(keys);
  120. targetNode.animations.push(babylonAnimation);
  121. runtime.babylonScene.beginAnimation(targetNode, 0, inputBuffer[inputBuffer.length - 1], true);
  122. }
  123. }
  124. }
  125. /**
  126. * Loads and creates animations
  127. */
  128. var loadAnimations = (runtime: IGLTFRuntime): void => {
  129. var animations = runtime.gltf.animations;
  130. if (!animations) {
  131. return;
  132. }
  133. for (var animationIndex = 0; animationIndex < animations.length; animationIndex++) {
  134. var animation = animations[animationIndex];
  135. if (!animation) {
  136. Tools.Warn("Animation " + animationIndex + " not found");
  137. continue;
  138. }
  139. if (!animation.channels || animation.channels.length === 0) {
  140. Tools.Warn("Animation " + animationIndex + " has no channels");
  141. }
  142. if (!animation.samplers || animation.samplers.length === 0) {
  143. Tools.Warn("Animation " + animationIndex + " has no samplers");
  144. continue;
  145. }
  146. loadAnimation(runtime, animation, animationIndex);
  147. }
  148. };
  149. /**
  150. * Returns the bones transformation matrix
  151. */
  152. var configureBoneTransformation = (node: IGLTFNode): Matrix => {
  153. var mat: Matrix = null;
  154. if (node.translation || node.rotation || node.scale) {
  155. var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
  156. var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  157. var position = Vector3.FromArray(node.translation || [0, 0, 0]);
  158. mat = Matrix.Compose(scale, rotation, position);
  159. }
  160. else {
  161. mat = node.matrix ? Matrix.FromArray(node.matrix) : Matrix.Identity();
  162. }
  163. return mat;
  164. };
  165. /**
  166. * Returns the parent bone
  167. */
  168. var getParentBone = (runtime: IGLTFRuntime, skin: IGLTFSkin, index: number, newSkeleton: Skeleton): Bone => {
  169. // Try to find
  170. var nodeStringID = getNodeID(index);
  171. for (var i = 0; i < newSkeleton.bones.length; i++) {
  172. if (newSkeleton.bones[i].id === nodeStringID) {
  173. return newSkeleton.bones[i].getParent();
  174. }
  175. }
  176. // Not found, search in gltf nodes
  177. var joints = skin.joints;
  178. for (var j = 0; j < joints.length; j++) {
  179. var parentID = joints[j];
  180. var parent = runtime.gltf.nodes[parentID];
  181. var children = parent.children;
  182. for (var i = 0; i < children.length; i++) {
  183. var childID = children[i];
  184. var child = runtime.gltf.nodes[childID];
  185. if (!nodeIsInJoints(skin, childID)) {
  186. continue;
  187. }
  188. if (childID === index)
  189. {
  190. var mat = configureBoneTransformation(parent);
  191. var bone = new Bone(parent.name || getNodeID(parentID), newSkeleton, getParentBone(runtime, skin, parentID, newSkeleton), mat);
  192. bone.id = getNodeID(parentID);
  193. return bone;
  194. }
  195. }
  196. }
  197. return null;
  198. }
  199. /**
  200. * Returns the appropriate root node
  201. */
  202. var getNodeToRoot = (nodesToRoot: INodeToRoot[], index: number): Bone => {
  203. for (var i = 0; i < nodesToRoot.length; i++) {
  204. var nodeToRoot = nodesToRoot[i];
  205. if (nodeToRoot.node.children) {
  206. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  207. var child = nodeToRoot.node.children[j];
  208. if (child === index) {
  209. return nodeToRoot.bone;
  210. }
  211. }
  212. }
  213. }
  214. return null;
  215. };
  216. /**
  217. * Returns the node with the node index
  218. */
  219. var getJointNode = (runtime: IGLTFRuntime, index: number): IJointNode => {
  220. var node = runtime.gltf.nodes[index];
  221. if (node) {
  222. return {
  223. node: node,
  224. index: index
  225. };
  226. }
  227. return null;
  228. }
  229. /**
  230. * Checks if a nodes is in joints
  231. */
  232. var nodeIsInJoints = (skin: IGLTFSkin, index: number): boolean => {
  233. for (var i = 0; i < skin.joints.length; i++) {
  234. if (skin.joints[i] === index) {
  235. return true;
  236. }
  237. }
  238. return false;
  239. }
  240. /**
  241. * Fills the nodes to root for bones and builds hierarchy
  242. */
  243. var getNodesToRoot = (runtime: IGLTFRuntime, newSkeleton: Skeleton, skin: IGLTFSkin, nodesToRoot: INodeToRoot[]): void => {
  244. // Creates nodes for root
  245. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  246. var node = runtime.gltf.nodes[i];
  247. if (nodeIsInJoints(skin, i)) {
  248. continue;
  249. }
  250. // Create node to root bone
  251. var mat = configureBoneTransformation(node);
  252. var bone = new Bone(node.name || getNodeID(i), newSkeleton, null, mat);
  253. bone.id = getNodeID(i);
  254. nodesToRoot.push({ bone: bone, node: node, index: i });
  255. }
  256. // Parenting
  257. for (var i = 0; i < nodesToRoot.length; i++) {
  258. var nodeToRoot = nodesToRoot[i];
  259. var children = nodeToRoot.node.children;
  260. if (children) {
  261. for (var j = 0; j < children.length; j++) {
  262. var child: INodeToRoot = null;
  263. for (var k = 0; k < nodesToRoot.length; k++) {
  264. if (nodesToRoot[k].index === children[j]) {
  265. child = nodesToRoot[k];
  266. break;
  267. }
  268. }
  269. if (child) {
  270. (<any>child.bone)._parent = nodeToRoot.bone;
  271. nodeToRoot.bone.children.push(child.bone);
  272. }
  273. }
  274. }
  275. }
  276. };
  277. /**
  278. * Imports a skeleton
  279. */
  280. var importSkeleton = (runtime: IGLTFRuntime, skinNode: IGLTFNode, skin: IGLTFSkin): Skeleton => {
  281. var name = skin.name || "skin" + skinNode.skin;
  282. var babylonSkeleton = <Skeleton>skin.babylonSkeleton;
  283. if (!babylonSkeleton) {
  284. babylonSkeleton = new Skeleton(name, "skin" + skinNode.skin, runtime.babylonScene);
  285. }
  286. if (!skin.babylonSkeleton) {
  287. return babylonSkeleton;
  288. }
  289. // Matrices
  290. var accessor = runtime.gltf.accessors[skin.inverseBindMatrices];
  291. var buffer = GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  292. // Find the root bones
  293. var nodesToRoot: INodeToRoot[] = [];
  294. var nodesToRootToAdd: Bone[] = [];
  295. getNodesToRoot(runtime, babylonSkeleton, skin, nodesToRoot);
  296. babylonSkeleton.bones = [];
  297. // Joints
  298. for (var i = 0; i < skin.joints.length; i++) {
  299. var jointNode = getJointNode(runtime, skin.joints[i]);
  300. var node = jointNode.node;
  301. if (!node) {
  302. Tools.Warn("Joint index " + skin.joints[i] + " does not exist");
  303. continue;
  304. }
  305. var index = jointNode.index;
  306. var stringID = getNodeID(index);
  307. // Optimize, if the bone already exists...
  308. var existingBone = runtime.babylonScene.getBoneByID(stringID);
  309. if (existingBone) {
  310. babylonSkeleton.bones.push(existingBone);
  311. continue;
  312. }
  313. // Search for parent bone
  314. var foundBone = false;
  315. var parentBone: Bone = null;
  316. for (var j = 0; j < i; j++) {
  317. var joint: IGLTFNode = getJointNode(runtime, skin.joints[j]).node;
  318. if (!joint) {
  319. Tools.Warn("Joint index " + skin.joints[j] + " does not exist when looking for parent");
  320. continue;
  321. }
  322. var children = joint.children;
  323. foundBone = false;
  324. for (var k = 0; k < children.length; k++) {
  325. if (children[k] === index) {
  326. parentBone = getParentBone(runtime, skin, skin.joints[j], babylonSkeleton);
  327. foundBone = true;
  328. break;
  329. }
  330. }
  331. if (foundBone) {
  332. break;
  333. }
  334. }
  335. // Create bone
  336. var mat = configureBoneTransformation(node);
  337. if (!parentBone && nodesToRoot.length > 0) {
  338. parentBone = getNodeToRoot(nodesToRoot, index);
  339. if (parentBone) {
  340. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  341. nodesToRootToAdd.push(parentBone);
  342. }
  343. }
  344. }
  345. var bone = new Bone(node.name || stringID, babylonSkeleton, parentBone, mat);
  346. bone.id = stringID;
  347. }
  348. // Polish
  349. var bones = babylonSkeleton.bones;
  350. babylonSkeleton.bones = [];
  351. for (var i = 0; i < skin.joints.length; i++) {
  352. var jointNode = getJointNode(runtime, skin.joints[i]);
  353. if (!jointNode) {
  354. continue;
  355. }
  356. var jointNodeStringId = getNodeID(jointNode.index);
  357. for (var j = 0; j < bones.length; j++) {
  358. if (bones[j].id === jointNodeStringId) {
  359. babylonSkeleton.bones.push(bones[j]);
  360. break;
  361. }
  362. }
  363. }
  364. babylonSkeleton.prepare();
  365. // Finish
  366. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  367. babylonSkeleton.bones.push(nodesToRootToAdd[i]);
  368. }
  369. return babylonSkeleton;
  370. };
  371. /**
  372. * Gets a material
  373. */
  374. var getMaterial = (runtime: IGLTFRuntime, index?: number): PBRMaterial => {
  375. if (index === undefined) {
  376. return GLTFUtils.GetDefaultMaterial(runtime);
  377. }
  378. var materials = runtime.gltf.materials;
  379. if (!materials || index < 0 || index >= materials.length) {
  380. Tools.Error("Invalid material index");
  381. return GLTFUtils.GetDefaultMaterial(runtime);
  382. }
  383. var material = runtime.gltf.materials[index].babylonMaterial;
  384. if (!material)
  385. {
  386. return GLTFUtils.GetDefaultMaterial(runtime);
  387. }
  388. return material;
  389. };
  390. /**
  391. * Imports a mesh and its geometries
  392. */
  393. var importMesh = (runtime: IGLTFRuntime, node: IGLTFNode, mesh: IGLTFMesh): Mesh => {
  394. var name = mesh.name || node.name || "mesh" + node.mesh;
  395. var babylonMesh = <Mesh>node.babylonNode;
  396. if (!babylonMesh) {
  397. babylonMesh = new Mesh(name, runtime.babylonScene);
  398. }
  399. if (!node.babylonNode) {
  400. return babylonMesh;
  401. }
  402. var multiMat = new MultiMaterial(name, runtime.babylonScene);
  403. if (!babylonMesh.material) {
  404. babylonMesh.material = multiMat;
  405. }
  406. var vertexData = new VertexData();
  407. var geometry = new Geometry(name, runtime.babylonScene, vertexData, false, babylonMesh);
  408. var verticesStarts = [];
  409. var verticesCounts = [];
  410. var indexStarts = [];
  411. var indexCounts = [];
  412. var morphTargetManager: BABYLON.MorphTargetManager;
  413. // Positions, normals and UVs
  414. for (var primitiveIndex = 0; primitiveIndex < mesh.primitives.length; primitiveIndex++) {
  415. // Temporary vertex data
  416. var tempVertexData = new VertexData();
  417. var primitive = mesh.primitives[primitiveIndex];
  418. if (primitive.mode !== EMeshPrimitiveMode.TRIANGLES) {
  419. // continue;
  420. }
  421. var attributes = primitive.attributes;
  422. var accessor: IGLTFAccessor = null;
  423. var buffer: ArrayBufferView = null;
  424. // Set positions, normal and uvs
  425. for (var semantic in attributes) {
  426. // Link accessor and buffer view
  427. accessor = runtime.gltf.accessors[attributes[semantic]];
  428. buffer = GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  429. if (semantic === "NORMAL") {
  430. tempVertexData.normals = <Float32Array>buffer;
  431. }
  432. else if (semantic === "POSITION") {
  433. tempVertexData.positions = <Float32Array>buffer;
  434. verticesCounts.push(tempVertexData.positions.length);
  435. }
  436. else if (semantic === "TANGENT") {
  437. tempVertexData.tangents = <Float32Array>buffer;
  438. }
  439. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  440. var channel = Number(semantic.split("_")[1]);
  441. var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  442. tempVertexData.set(<Float32Array>buffer, uvKind);
  443. }
  444. else if (semantic === "JOINT") {
  445. tempVertexData.matricesIndices = <Float32Array>buffer;
  446. }
  447. else if (semantic === "WEIGHT") {
  448. tempVertexData.matricesWeights = <Float32Array>buffer;
  449. }
  450. else if (semantic === "COLOR_0") {
  451. tempVertexData.colors = <Float32Array>buffer;
  452. }
  453. else {
  454. Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  455. }
  456. }
  457. // Indices
  458. accessor = runtime.gltf.accessors[primitive.indices];
  459. if (accessor) {
  460. buffer = GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  461. tempVertexData.indices = <Uint32Array>buffer;
  462. indexCounts.push(tempVertexData.indices.length);
  463. }
  464. else {
  465. // Set indices on the fly
  466. tempVertexData.indices = new Uint32Array(tempVertexData.positions.length / 3);
  467. for (var index = 0; index < tempVertexData.indices.length; index++) {
  468. tempVertexData.indices[index] = index;
  469. }
  470. indexCounts.push(tempVertexData.indices.length);
  471. }
  472. vertexData.merge(tempVertexData);
  473. tempVertexData = undefined;
  474. // Sub material
  475. var material = getMaterial(runtime, primitive.material);
  476. multiMat.subMaterials.push(material);
  477. // Morph Targets
  478. if (primitive.targets) {
  479. for (var targetsIndex = 0; targetsIndex < primitive.targets.length; targetsIndex++) {
  480. var target = primitive.targets[targetsIndex];
  481. var weight = 0.0;
  482. if (node.weights) {
  483. weight = node.weights[targetsIndex];
  484. }
  485. else if (mesh.weights) {
  486. weight = mesh.weights[targetsIndex];
  487. }
  488. var morph = new BABYLON.MorphTarget("morph" + targetsIndex, weight);
  489. for (var semantic in target) {
  490. // Link accessor and buffer view
  491. accessor = runtime.gltf.accessors[target[semantic]];
  492. var values = <Float32Array>GLTFUtils.GetBufferFromAccessor(runtime, accessor);
  493. if (accessor.name) {
  494. morph.name = accessor.name;
  495. }
  496. // glTF stores morph target information as deltas
  497. // while babylon.js expects the final data.
  498. // As a result we have to add the original data to the delta to calculate
  499. // the final data.
  500. if (semantic === "NORMAL") {
  501. for (var i = 0; i < values.length; i++) {
  502. values[i] += vertexData.normals[i];
  503. }
  504. morph.setNormals(values);
  505. }
  506. else if (semantic === "POSITION") {
  507. for (var i = 0; i < values.length; i++) {
  508. values[i] += vertexData.positions[i];
  509. }
  510. morph.setPositions(values);
  511. }
  512. else if (semantic === "TANGENT") {
  513. // Tangent data for morph targets is stored as xyz delta.
  514. // The vertexData.tangent is stored as xyzw.
  515. // So we need to skip every fourth vertexData.tangent.
  516. for (var i = 0, j = 0; i < values.length; i++, j++) {
  517. values[i] += vertexData.tangents[j];
  518. if ((i + 1) % 3 == 0) {
  519. j++;
  520. }
  521. }
  522. morph.setTangents(values);
  523. }
  524. else {
  525. Tools.Warn("Ignoring unrecognized semantic '" + semantic + "'");
  526. }
  527. }
  528. if (morph.getPositions()) {
  529. if (!morphTargetManager) {
  530. morphTargetManager = new BABYLON.MorphTargetManager();
  531. babylonMesh.morphTargetManager = morphTargetManager;
  532. }
  533. morphTargetManager.addTarget(morph);
  534. }
  535. else {
  536. Tools.Warn("Not adding morph target '" + morph.name + "' because it has no position data");
  537. }
  538. }
  539. }
  540. // Update vertices start and index start
  541. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  542. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  543. }
  544. // Apply geometry
  545. geometry.setAllVerticesData(vertexData, false);
  546. babylonMesh.computeWorldMatrix(true);
  547. // Apply submeshes
  548. babylonMesh.subMeshes = [];
  549. for (var primitiveIndex = 0; primitiveIndex < mesh.primitives.length; primitiveIndex++) {
  550. if (mesh.primitives[primitiveIndex].mode !== EMeshPrimitiveMode.TRIANGLES) {
  551. //continue;
  552. }
  553. var subMesh = new SubMesh(primitiveIndex, verticesStarts[primitiveIndex], verticesCounts[primitiveIndex], indexStarts[primitiveIndex], indexCounts[primitiveIndex], babylonMesh, babylonMesh, true);
  554. }
  555. // Finish
  556. return babylonMesh;
  557. };
  558. /**
  559. * Configures node transformation
  560. */
  561. var configureNode = (babylonNode: Mesh | TargetCamera, node: IGLTFNode): void => {
  562. var position = Vector3.Zero();
  563. var rotation = Quaternion.Identity();
  564. var scaling = new Vector3(1, 1, 1);
  565. if (node.matrix) {
  566. var mat = Matrix.FromArray(node.matrix);
  567. mat.decompose(scaling, rotation, position);
  568. }
  569. else {
  570. if (node.translation) {
  571. position = Vector3.FromArray(node.translation);
  572. }
  573. if (node.rotation) {
  574. rotation = Quaternion.FromArray(node.rotation);
  575. }
  576. if (node.scale) {
  577. scaling = Vector3.FromArray(node.scale);
  578. }
  579. }
  580. babylonNode.position = position;
  581. babylonNode.rotationQuaternion = rotation;
  582. if (babylonNode instanceof Mesh) {
  583. var mesh = <Mesh>babylonNode;
  584. mesh.scaling = scaling;
  585. }
  586. };
  587. /**
  588. * Imports a node
  589. */
  590. var importNode = (runtime: IGLTFRuntime, node: IGLTFNode): Node => {
  591. var babylonNode: Mesh | TargetCamera = null;
  592. if (runtime.importOnlyMeshes && (node.skin !== undefined || node.mesh !== undefined)) {
  593. if (runtime.importMeshesNames.length > 0 && runtime.importMeshesNames.indexOf(node.name) === -1) {
  594. return null;
  595. }
  596. }
  597. // Meshes
  598. if (node.skin !== undefined) {
  599. if (node.mesh !== undefined) {
  600. var skin = runtime.gltf.skins[node.skin];
  601. var newMesh = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  602. var newSkeleton = importSkeleton(runtime, node, skin);
  603. if (newSkeleton)
  604. {
  605. newMesh.skeleton = newSkeleton;
  606. skin.babylonSkeleton = newSkeleton;
  607. }
  608. babylonNode = newMesh;
  609. }
  610. }
  611. else if (node.mesh !== undefined) {
  612. babylonNode = importMesh(runtime, node, runtime.gltf.meshes[node.mesh]);
  613. }
  614. // Cameras
  615. else if (node.camera !== undefined && !node.babylonNode && !runtime.importOnlyMeshes) {
  616. var camera = runtime.gltf.cameras[node.camera];
  617. if (camera !== undefined) {
  618. if (camera.type === "orthographic") {
  619. var orthographicCamera = camera.orthographic;
  620. var orthoCamera = new FreeCamera(node.name || "camera" + node.camera, Vector3.Zero(), runtime.babylonScene);
  621. orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  622. orthoCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  623. babylonNode = orthoCamera;
  624. }
  625. else if (camera.type === "perspective") {
  626. var perspectiveCamera = camera.perspective;
  627. var persCamera = new FreeCamera(node.name || "camera" + node.camera, Vector3.Zero(), runtime.babylonScene);
  628. persCamera.attachControl(runtime.babylonScene.getEngine().getRenderingCanvas());
  629. if (!perspectiveCamera.aspectRatio) {
  630. perspectiveCamera.aspectRatio = runtime.babylonScene.getEngine().getRenderWidth() / runtime.babylonScene.getEngine().getRenderHeight();
  631. }
  632. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  633. persCamera.maxZ = perspectiveCamera.zfar;
  634. persCamera.minZ = perspectiveCamera.znear;
  635. }
  636. babylonNode = persCamera;
  637. }
  638. }
  639. }
  640. // Empty node
  641. if (node.babylonNode) {
  642. return node.babylonNode;
  643. }
  644. else if (babylonNode === null) {
  645. var dummy = new Mesh(node.name || "mesh" + node.mesh, runtime.babylonScene);
  646. node.babylonNode = dummy;
  647. babylonNode = dummy;
  648. }
  649. if (babylonNode !== null) {
  650. configureNode(babylonNode, node);
  651. babylonNode.updateCache(true);
  652. node.babylonNode = babylonNode;
  653. }
  654. return babylonNode;
  655. };
  656. /**
  657. * Traverses nodes and creates them
  658. */
  659. var traverseNodes = (runtime: IGLTFRuntime, index: number, parent: Node, meshIncluded?: boolean): void => {
  660. var node = runtime.gltf.nodes[index];
  661. var newNode: Node = null;
  662. if (runtime.importOnlyMeshes && !meshIncluded) {
  663. if (runtime.importMeshesNames.indexOf(node.name) !== -1 || runtime.importMeshesNames.length === 0) {
  664. meshIncluded = true;
  665. }
  666. else {
  667. meshIncluded = false;
  668. }
  669. }
  670. else {
  671. meshIncluded = true;
  672. }
  673. if (meshIncluded) {
  674. newNode = importNode(runtime, node);
  675. if (newNode !== null) {
  676. newNode.id = getNodeID(index);
  677. newNode.parent = parent;
  678. }
  679. }
  680. if (node.children) {
  681. for (var i = 0; i < node.children.length; i++) {
  682. traverseNodes(runtime, node.children[i], newNode, meshIncluded);
  683. }
  684. }
  685. };
  686. var importScene = (runtime: IGLTFRuntime): void => {
  687. var scene = runtime.gltf.scene || 0;
  688. var scenes = runtime.gltf.scenes;
  689. if (scenes) {
  690. var nodes = scenes[scene].nodes;
  691. for (var i = 0; i < nodes.length; i++) {
  692. traverseNodes(runtime, nodes[i], null);
  693. }
  694. }
  695. else {
  696. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  697. traverseNodes(runtime, i, null);
  698. }
  699. }
  700. };
  701. /**
  702. * do stuff after buffers are loaded (e.g. hook up materials, load animations, etc.)
  703. */
  704. var postLoad = (runtime: IGLTFRuntime): void => {
  705. importScene(runtime);
  706. // Set animations
  707. loadAnimations(runtime);
  708. for (var i = 0; i < runtime.babylonScene.skeletons.length; i++) {
  709. var skeleton = runtime.babylonScene.skeletons[i];
  710. runtime.babylonScene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  711. }
  712. // Revoke object urls created during load
  713. if (runtime.gltf.textures) {
  714. for (var i = 0; i < runtime.gltf.textures.length; i++) {
  715. var texture = runtime.gltf.textures[i];
  716. if (texture.blobURL) {
  717. URL.revokeObjectURL(texture.blobURL);
  718. }
  719. }
  720. }
  721. };
  722. class BinaryReader {
  723. private _arrayBuffer: ArrayBuffer;
  724. private _dataView: DataView;
  725. private _byteOffset: number;
  726. constructor(arrayBuffer: ArrayBuffer) {
  727. this._arrayBuffer = arrayBuffer;
  728. this._dataView = new DataView(arrayBuffer);
  729. this._byteOffset = 0;
  730. }
  731. public getPosition(): number {
  732. return this._byteOffset;
  733. }
  734. public getLength(): number {
  735. return this._arrayBuffer.byteLength;
  736. }
  737. public readUint32(): number {
  738. var value = this._dataView.getUint32(this._byteOffset, true);
  739. this._byteOffset += 4;
  740. return value;
  741. }
  742. public readUint8Array(length: number): Uint8Array {
  743. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  744. this._byteOffset += length;
  745. return value;
  746. }
  747. public skipBytes(length: number): void {
  748. this._byteOffset += length;
  749. }
  750. }
  751. /**
  752. * glTF File Loader Plugin
  753. */
  754. export class GLTFLoader implements IGLTFLoader {
  755. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  756. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  757. if (GLTFLoader.Extensions[extension.name]) {
  758. Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  759. return;
  760. }
  761. GLTFLoader.Extensions[extension.name] = extension;
  762. }
  763. public static LoadMaterial(runtime: IGLTFRuntime, index: number): IGLTFMaterial {
  764. var material = runtime.gltf.materials[index];
  765. if (!material) return null;
  766. material.babylonMaterial = new PBRMaterial(material.name || "mat" + index, runtime.babylonScene);
  767. material.babylonMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  768. material.babylonMaterial.useScalarInLinearSpace = true;
  769. return material;
  770. }
  771. public static LoadMetallicRoughnessMaterialPropertiesAsync(runtime: IGLTFRuntime, material: IGLTFMaterial, onSuccess: () => void, onError: () => void): void {
  772. // Ensure metallic workflow
  773. material.babylonMaterial.metallic = 1;
  774. material.babylonMaterial.roughness = 1;
  775. var properties = material.pbrMetallicRoughness;
  776. if (!properties) {
  777. onSuccess();
  778. return;
  779. }
  780. //
  781. // Load Factors
  782. //
  783. material.babylonMaterial.albedoColor = properties.baseColorFactor ? Color3.FromArray(properties.baseColorFactor) : new Color3(1, 1, 1);
  784. material.babylonMaterial.metallic = properties.metallicFactor || 1;
  785. material.babylonMaterial.roughness = properties.roughnessFactor || 1;
  786. //
  787. // Load Textures
  788. //
  789. if (!properties.baseColorTexture && !properties.metallicRoughnessTexture) {
  790. onSuccess();
  791. return;
  792. }
  793. var checkSuccess = () => {
  794. if ((!properties.baseColorTexture || material.babylonMaterial.albedoTexture) &&
  795. (!properties.metallicRoughnessTexture || material.babylonMaterial.metallicTexture))
  796. {
  797. onSuccess();
  798. }
  799. };
  800. if (properties.baseColorTexture) {
  801. GLTFLoader.LoadTextureAsync(runtime, properties.baseColorTexture,
  802. texture => {
  803. material.babylonMaterial.albedoTexture = texture;
  804. GLTFLoader.LoadAlphaProperties(runtime, material);
  805. checkSuccess();
  806. },
  807. () => {
  808. Tools.Error("Failed to load base color texture");
  809. onError();
  810. });
  811. }
  812. if (properties.metallicRoughnessTexture) {
  813. GLTFLoader.LoadTextureAsync(runtime, properties.metallicRoughnessTexture,
  814. texture => {
  815. material.babylonMaterial.metallicTexture = texture;
  816. material.babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  817. material.babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  818. material.babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  819. checkSuccess();
  820. },
  821. () => {
  822. Tools.Error("Failed to load metallic roughness texture");
  823. onError();
  824. });
  825. }
  826. }
  827. public static LoadCommonMaterialPropertiesAsync(runtime: IGLTFRuntime, material: IGLTFMaterial, onSuccess: () => void, onError: () => void): void {
  828. //
  829. // Load Factors
  830. //
  831. material.babylonMaterial.useEmissiveAsIllumination = (material.emissiveFactor || material.emissiveTexture) ? true : false;
  832. material.babylonMaterial.emissiveColor = material.emissiveFactor ? Color3.FromArray(material.emissiveFactor) : new Color3(0, 0, 0);
  833. if (material.doubleSided) {
  834. material.babylonMaterial.backFaceCulling = false;
  835. material.babylonMaterial.twoSidedLighting = true;
  836. }
  837. //
  838. // Load Textures
  839. //
  840. if (!material.normalTexture && !material.occlusionTexture && !material.emissiveTexture) {
  841. onSuccess();
  842. return;
  843. }
  844. var checkSuccess = () => {
  845. if ((!material.normalTexture || material.babylonMaterial.bumpTexture) &&
  846. (!material.occlusionTexture || material.babylonMaterial.ambientTexture) &&
  847. (!material.emissiveTexture || material.babylonMaterial.emissiveTexture)) {
  848. onSuccess();
  849. }
  850. }
  851. if (material.normalTexture) {
  852. GLTFLoader.LoadTextureAsync(runtime, material.normalTexture, babylonTexture => {
  853. material.babylonMaterial.bumpTexture = babylonTexture;
  854. if (material.normalTexture.scale !== undefined) {
  855. material.babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  856. }
  857. checkSuccess();
  858. },
  859. () => {
  860. Tools.Error("Failed to load normal texture");
  861. onError();
  862. });
  863. }
  864. if (material.occlusionTexture) {
  865. GLTFLoader.LoadTextureAsync(runtime, material.occlusionTexture, babylonTexture => {
  866. material.babylonMaterial.ambientTexture = babylonTexture;
  867. material.babylonMaterial.useAmbientInGrayScale = true;
  868. if (material.occlusionTexture.strength !== undefined) {
  869. material.babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  870. }
  871. checkSuccess();
  872. },
  873. () => {
  874. Tools.Error("Failed to load occlusion texture");
  875. onError();
  876. });
  877. }
  878. if (material.emissiveTexture) {
  879. GLTFLoader.LoadTextureAsync(runtime, material.emissiveTexture, babylonTexture => {
  880. material.babylonMaterial.emissiveTexture = babylonTexture;
  881. checkSuccess();
  882. },
  883. () => {
  884. Tools.Error("Failed to load emissive texture");
  885. onError();
  886. });
  887. }
  888. }
  889. public static LoadAlphaProperties(runtime: IGLTFRuntime, material: IGLTFMaterial): void {
  890. var alphaMode = material.alphaMode || "OPAQUE";
  891. switch (alphaMode) {
  892. case "OPAQUE":
  893. // default is opaque
  894. break;
  895. case "MASK":
  896. material.babylonMaterial.albedoTexture.hasAlpha = true;
  897. material.babylonMaterial.useAlphaFromAlbedoTexture = false;
  898. material.babylonMaterial.alphaMode = Engine.ALPHA_DISABLE;
  899. break;
  900. case "BLEND":
  901. material.babylonMaterial.albedoTexture.hasAlpha = true;
  902. material.babylonMaterial.useAlphaFromAlbedoTexture = true;
  903. material.babylonMaterial.alphaMode = Engine.ALPHA_COMBINE;
  904. break;
  905. default:
  906. Tools.Error("Invalid alpha mode '" + material.alphaMode + "'");
  907. }
  908. }
  909. public static LoadTextureAsync(runtime: IGLTFRuntime, textureInfo: IGLTFTextureInfo, onSuccess: (babylonTexture: Texture) => void, onError: () => void): void {
  910. var texture = runtime.gltf.textures[textureInfo.index];
  911. var texCoord = textureInfo.texCoord || 0;
  912. if (!texture || texture.source === undefined) {
  913. onError();
  914. return;
  915. }
  916. if (texture.babylonTextures) {
  917. var babylonTexture = texture.babylonTextures[texCoord];
  918. if (!babylonTexture) {
  919. for (var i = 0; i < texture.babylonTextures.length; i++) {
  920. babylonTexture = texture.babylonTextures[i];
  921. if (babylonTexture) {
  922. babylonTexture = babylonTexture.clone();
  923. babylonTexture.coordinatesIndex = texCoord;
  924. break;
  925. }
  926. }
  927. }
  928. onSuccess(babylonTexture);
  929. return;
  930. }
  931. var source = runtime.gltf.images[texture.source];
  932. var sourceURL = runtime.rootUrl + source.uri;
  933. if (texture.blobURL) {
  934. sourceURL = texture.blobURL;
  935. }
  936. else {
  937. if (source.uri === undefined) {
  938. var bufferView = runtime.gltf.bufferViews[source.bufferView];
  939. var buffer = GLTFUtils.GetBufferFromBufferView(runtime, bufferView, 0, bufferView.byteLength, EComponentType.UNSIGNED_BYTE);
  940. texture.blobURL = URL.createObjectURL(new Blob([buffer], { type: source.mimeType }));
  941. sourceURL = texture.blobURL;
  942. }
  943. else if (GLTFUtils.IsBase64(source.uri)) {
  944. var decodedBuffer = new Uint8Array(GLTFUtils.DecodeBase64(source.uri));
  945. texture.blobURL = URL.createObjectURL(new Blob([decodedBuffer], { type: source.mimeType }));
  946. sourceURL = texture.blobURL;
  947. }
  948. }
  949. GLTFLoader._createTextureAsync(runtime, texture, texCoord, sourceURL, onSuccess, onError);
  950. }
  951. private static _createTextureAsync(runtime: IGLTFRuntime, texture: IGLTFTexture, texCoord: number, url: string, onSuccess: (babylonTexture: Texture) => void, onError: () => void): void {
  952. var sampler: IGLTFSampler = (texture.sampler === undefined ? {} : runtime.gltf.samplers[texture.sampler]);
  953. var noMipMaps = (sampler.minFilter === ETextureMinFilter.NEAREST || sampler.minFilter === ETextureMinFilter.LINEAR);
  954. var samplingMode = GLTFUtils.GetTextureFilterMode(sampler.minFilter);
  955. var babylonTexture = new Texture(url, runtime.babylonScene, noMipMaps, true, samplingMode, () => {
  956. onSuccess(babylonTexture);
  957. }, onError);
  958. babylonTexture.coordinatesIndex = texCoord;
  959. babylonTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
  960. babylonTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
  961. babylonTexture.name = texture.name;
  962. // Cache the texture
  963. texture.babylonTextures = texture.babylonTextures || [];
  964. texture.babylonTextures[texCoord] = babylonTexture;
  965. }
  966. /**
  967. * Import meshes
  968. */
  969. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onError?: () => void): void {
  970. scene.useRightHandedSystem = true;
  971. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, true);
  972. if (!runtime) {
  973. onError();
  974. return;
  975. }
  976. if (meshesNames === "") {
  977. runtime.importMeshesNames = [];
  978. }
  979. else if (typeof meshesNames === "string") {
  980. runtime.importMeshesNames = [meshesNames];
  981. }
  982. else if (meshesNames && !(meshesNames instanceof Array)) {
  983. runtime.importMeshesNames = [meshesNames];
  984. }
  985. else {
  986. runtime.importMeshesNames = [];
  987. Tools.Warn("Argument meshesNames must be of type string or string[]");
  988. }
  989. // Load scene
  990. importScene(runtime);
  991. var meshes = [];
  992. var skeletons = [];
  993. // Fill arrays of meshes and skeletons
  994. for (var i = 0; i < runtime.gltf.nodes.length; i++) {
  995. var node = runtime.gltf.nodes[i];
  996. if (node.babylonNode instanceof AbstractMesh) {
  997. meshes.push(<AbstractMesh>node.babylonNode);
  998. }
  999. }
  1000. for (var i = 0; i < runtime.gltf.skins.length; i++) {
  1001. var skin = runtime.gltf.skins[i];
  1002. if (skin.babylonSkeleton instanceof Skeleton) {
  1003. skeletons.push(skin.babylonSkeleton);
  1004. }
  1005. }
  1006. // Load buffers, materials, etc.
  1007. GLTFLoader._loadBuffersAsync(runtime, () => {
  1008. GLTFLoader._loadMaterialsAsync(runtime, () => {
  1009. postLoad(runtime);
  1010. onSuccess(meshes, null, skeletons);
  1011. }, onError);
  1012. }, onError);
  1013. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1014. onSuccess(meshes, null, skeletons);
  1015. }
  1016. }
  1017. /**
  1018. * Load scene
  1019. */
  1020. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onError: () => void): void {
  1021. scene.useRightHandedSystem = true;
  1022. var runtime = GLTFLoader._createRuntime(scene, data, rootUrl, false);
  1023. if (!runtime) {
  1024. onError();
  1025. return;
  1026. }
  1027. importScene(runtime);
  1028. GLTFLoader._loadBuffersAsync(runtime, () => {
  1029. GLTFLoader._loadMaterialsAsync(runtime, () => {
  1030. postLoad(runtime);
  1031. onSuccess();
  1032. }, onError);
  1033. }, onError);
  1034. }
  1035. private static _loadBuffersAsync(runtime: IGLTFRuntime, onSuccess: () => void, onError: () => void): void {
  1036. if (runtime.gltf.buffers.length == 0) {
  1037. onSuccess();
  1038. return;
  1039. }
  1040. var successCount = 0;
  1041. runtime.gltf.buffers.forEach((buffer, index) => {
  1042. this._loadBufferAsync(runtime, index, () => {
  1043. if (++successCount === runtime.gltf.buffers.length) {
  1044. onSuccess();
  1045. }
  1046. }, onError);
  1047. });
  1048. }
  1049. private static _loadBufferAsync(runtime: IGLTFRuntime, index: number, onSuccess: () => void, onError: () => void): void {
  1050. var buffer = runtime.gltf.buffers[index];
  1051. if (buffer.uri === undefined) {
  1052. // buffer.loadedBufferView should already be set
  1053. onSuccess();
  1054. }
  1055. else if (GLTFUtils.IsBase64(buffer.uri)) {
  1056. var data = GLTFUtils.DecodeBase64(buffer.uri);
  1057. setTimeout(() => {
  1058. buffer.loadedBufferView = new Uint8Array(data);
  1059. onSuccess();
  1060. });
  1061. }
  1062. else {
  1063. Tools.LoadFile(runtime.rootUrl + buffer.uri, data => {
  1064. buffer.loadedBufferView = new Uint8Array(data);
  1065. onSuccess();
  1066. }, null, null, true, onError);
  1067. }
  1068. }
  1069. private static _loadMaterialsAsync(runtime: IGLTFRuntime, onSuccess: () => void, onError: () => void): void {
  1070. var materials = runtime.gltf.materials;
  1071. if (!materials) {
  1072. onSuccess();
  1073. return;
  1074. }
  1075. var successCount = 0;
  1076. for (var i = 0; i < materials.length; i++) {
  1077. GLTFLoaderExtension.LoadMaterialAsync(runtime, i, () => {
  1078. if (++successCount === materials.length) {
  1079. onSuccess();
  1080. }
  1081. }, onError);
  1082. }
  1083. }
  1084. private static _createRuntime(scene: Scene, data: IGLTFLoaderData, rootUrl: string, importOnlyMeshes: boolean): IGLTFRuntime {
  1085. var runtime: IGLTFRuntime = {
  1086. gltf: <IGLTF>data.json,
  1087. babylonScene: scene,
  1088. rootUrl: rootUrl,
  1089. importOnlyMeshes: importOnlyMeshes,
  1090. }
  1091. var binaryBuffer: IGLTFBuffer;
  1092. var buffers = runtime.gltf.buffers;
  1093. if (buffers.length > 0 && buffers[0].uri === undefined) {
  1094. binaryBuffer = buffers[0];
  1095. }
  1096. if (data.bin) {
  1097. if (!binaryBuffer) {
  1098. Tools.Error("Unexpected BIN chunk");
  1099. return null;
  1100. }
  1101. if (binaryBuffer.byteLength != data.bin.byteLength) {
  1102. Tools.Error("Binary buffer length from JSON does not match chunk length");
  1103. return null;
  1104. }
  1105. binaryBuffer.loadedBufferView = data.bin;
  1106. }
  1107. GLTFLoaderExtension.PostCreateRuntime(runtime);
  1108. return runtime;
  1109. }
  1110. }
  1111. BABYLON.GLTFFileLoader.GLTFLoaderV2 = new GLTFLoader();
  1112. }