babylon.glTFLoader.ts 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  1. /// <reference path="../../../../dist/preview release/babylon.d.ts"/>
  2. module BABYLON.GLTF1 {
  3. /**
  4. * Tokenizer. Used for shaders compatibility
  5. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  6. */
  7. enum ETokenType {
  8. IDENTIFIER = 1,
  9. UNKNOWN = 2,
  10. END_OF_INPUT = 3
  11. }
  12. class Tokenizer {
  13. private _toParse: string;
  14. private _pos: number = 0;
  15. private _maxPos: number;
  16. public currentToken: ETokenType;
  17. public currentIdentifier: string;
  18. public currentString: string;
  19. public isLetterOrDigitPattern: RegExp = /^[a-zA-Z0-9]+$/;
  20. constructor(toParse: string) {
  21. this._toParse = toParse;
  22. this._maxPos = toParse.length;
  23. }
  24. public getNextToken(): ETokenType {
  25. if (this.isEnd()) return ETokenType.END_OF_INPUT;
  26. this.currentString = this.read();
  27. this.currentToken = ETokenType.UNKNOWN;
  28. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  29. this.currentToken = ETokenType.IDENTIFIER;
  30. this.currentIdentifier = this.currentString;
  31. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  32. this.currentIdentifier += this.currentString;
  33. this.forward();
  34. }
  35. }
  36. return this.currentToken;
  37. }
  38. public peek(): string {
  39. return this._toParse[this._pos];
  40. }
  41. public read(): string {
  42. return this._toParse[this._pos++];
  43. }
  44. public forward(): void {
  45. this._pos++;
  46. }
  47. public isEnd(): boolean {
  48. return this._pos >= this._maxPos;
  49. }
  50. }
  51. /**
  52. * Values
  53. */
  54. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  55. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  56. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  57. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  58. /**
  59. * Parse
  60. */
  61. var parseBuffers = (parsedBuffers: any, gltfRuntime: IGLTFRuntime) => {
  62. for (var buf in parsedBuffers) {
  63. var parsedBuffer = parsedBuffers[buf];
  64. gltfRuntime.buffers[buf] = parsedBuffer;
  65. gltfRuntime.buffersCount++;
  66. }
  67. };
  68. var parseShaders = (parsedShaders: any, gltfRuntime: IGLTFRuntime) => {
  69. for (var sha in parsedShaders) {
  70. var parsedShader = parsedShaders[sha];
  71. gltfRuntime.shaders[sha] = parsedShader;
  72. gltfRuntime.shaderscount++;
  73. }
  74. };
  75. var parseObject = (parsedObjects: any, runtimeProperty: string, gltfRuntime: IGLTFRuntime) => {
  76. for (var object in parsedObjects) {
  77. var parsedObject = parsedObjects[object];
  78. gltfRuntime[runtimeProperty][object] = parsedObject;
  79. }
  80. };
  81. /**
  82. * Utils
  83. */
  84. var normalizeUVs = (buffer: any) => {
  85. if (!buffer) {
  86. return;
  87. }
  88. for (var i = 0; i < buffer.length / 2; i++) {
  89. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  90. }
  91. };
  92. var replaceInString = (str: string, searchValue: string, replaceValue: string) => {
  93. while (str.indexOf(searchValue) !== -1) {
  94. str = str.replace(searchValue, replaceValue);
  95. }
  96. return str;
  97. };
  98. var getAttribute = (attributeParameter: IGLTFTechniqueParameter) => {
  99. if (attributeParameter.semantic === "NORMAL") {
  100. return "normal";
  101. } else if (attributeParameter.semantic === "POSITION") {
  102. return "position";
  103. } else if (attributeParameter.semantic === "JOINT") {
  104. return "matricesIndices";
  105. } else if (attributeParameter.semantic === "WEIGHT") {
  106. return "matricesWeights";
  107. } else if (attributeParameter.semantic === "COLOR") {
  108. return "color";
  109. } else if (attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  110. var channel = Number(attributeParameter.semantic.split("_")[1]);
  111. return "uv" + (channel === 0 ? "" : channel + 1);
  112. }
  113. };
  114. /**
  115. * Returns the animation path (glTF -> Babylon)
  116. */
  117. var getAnimationPath = (path: string): string => {
  118. var index = glTFAnimationPaths.indexOf(path);
  119. if (index !== -1) {
  120. return babylonAnimationPaths[index];
  121. }
  122. return path;
  123. };
  124. /**
  125. * Loads and creates animations
  126. */
  127. var loadAnimations = (gltfRuntime: IGLTFRuntime) => {
  128. for (var anim in gltfRuntime.animations) {
  129. var animation: IGLTFAnimation = gltfRuntime.animations[anim];
  130. var lastAnimation: Animation = null;
  131. for (var i = 0; i < animation.channels.length; i++) {
  132. // Get parameters and load buffers
  133. var channel = animation.channels[i];
  134. var sampler: IGLTFAnimationSampler = animation.samplers[channel.sampler];
  135. if (!sampler) {
  136. continue;
  137. }
  138. var inputData: string = null;
  139. var outputData: string = null;
  140. if (animation.parameters) {
  141. inputData = animation.parameters[sampler.input];
  142. outputData = animation.parameters[sampler.output];
  143. }
  144. else {
  145. inputData = sampler.input;
  146. outputData = sampler.output;
  147. }
  148. var bufferInput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  149. var bufferOutput = GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  150. var targetID = channel.target.id;
  151. var targetNode: any = gltfRuntime.scene.getNodeByID(targetID);
  152. if (targetNode === null) {
  153. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  154. }
  155. if (targetNode === null) {
  156. Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  157. continue;
  158. }
  159. var isBone = targetNode instanceof Bone;
  160. // Get target path (position, rotation or scaling)
  161. var targetPath = channel.target.path;
  162. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  163. if (targetPathIndex !== -1) {
  164. targetPath = babylonAnimationPaths[targetPathIndex];
  165. }
  166. // Determine animation type
  167. var animationType = Animation.ANIMATIONTYPE_MATRIX;
  168. if (!isBone) {
  169. if (targetPath === "rotationQuaternion") {
  170. animationType = Animation.ANIMATIONTYPE_QUATERNION;
  171. targetNode.rotationQuaternion = new Quaternion();
  172. }
  173. else {
  174. animationType = Animation.ANIMATIONTYPE_VECTOR3;
  175. }
  176. }
  177. // Create animation and key frames
  178. var babylonAnimation: Animation = null;
  179. var keys = [];
  180. var arrayOffset = 0;
  181. var modifyKey = false;
  182. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  183. babylonAnimation = lastAnimation;
  184. modifyKey = true;
  185. }
  186. if (!modifyKey) {
  187. babylonAnimation = new Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, Animation.ANIMATIONLOOPMODE_CYCLE);
  188. }
  189. // For each frame
  190. for (var j = 0; j < bufferInput.length; j++) {
  191. var value: any = null;
  192. if (targetPath === "rotationQuaternion") { // VEC4
  193. value = Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  194. arrayOffset += 4;
  195. }
  196. else { // Position and scaling are VEC3
  197. value = Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  198. arrayOffset += 3;
  199. }
  200. if (isBone) {
  201. var bone = <Bone>targetNode;
  202. var translation = Vector3.Zero();
  203. var rotationQuaternion = new Quaternion();
  204. var scaling = Vector3.Zero();
  205. // Warning on decompose
  206. var mat = bone.getBaseMatrix();
  207. if (modifyKey) {
  208. mat = lastAnimation.getKeys()[j].value;
  209. }
  210. mat.decompose(scaling, rotationQuaternion, translation);
  211. if (targetPath === "position") {
  212. translation = value;
  213. }
  214. else if (targetPath === "rotationQuaternion") {
  215. rotationQuaternion = value;
  216. }
  217. else {
  218. scaling = value;
  219. }
  220. value = Matrix.Compose(scaling, rotationQuaternion, translation);
  221. }
  222. if (!modifyKey) {
  223. keys.push({
  224. frame: bufferInput[j],
  225. value: value
  226. });
  227. }
  228. else {
  229. lastAnimation.getKeys()[j].value = value;
  230. }
  231. }
  232. // Finish
  233. if (!modifyKey) {
  234. babylonAnimation.setKeys(keys);
  235. targetNode.animations.push(babylonAnimation);
  236. }
  237. lastAnimation = babylonAnimation;
  238. gltfRuntime.scene.stopAnimation(targetNode);
  239. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  240. }
  241. }
  242. };
  243. /**
  244. * Returns the bones transformation matrix
  245. */
  246. var configureBoneTransformation = (node: IGLTFNode): Matrix => {
  247. var mat: Matrix = null;
  248. if (node.translation || node.rotation || node.scale) {
  249. var scale = Vector3.FromArray(node.scale || [1, 1, 1]);
  250. var rotation = Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  251. var position = Vector3.FromArray(node.translation || [0, 0, 0]);
  252. mat = Matrix.Compose(scale, rotation, position);
  253. }
  254. else {
  255. mat = Matrix.FromArray(node.matrix);
  256. }
  257. return mat;
  258. };
  259. /**
  260. * Returns the parent bone
  261. */
  262. var getParentBone = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, jointName: string, newSkeleton: Skeleton): Bone => {
  263. // Try to find
  264. for (var i = 0; i < newSkeleton.bones.length; i++) {
  265. if (newSkeleton.bones[i].name === jointName) {
  266. return newSkeleton.bones[i];
  267. }
  268. }
  269. // Not found, search in gltf nodes
  270. var nodes = gltfRuntime.nodes;
  271. for (var nde in nodes) {
  272. var node: IGLTFNode = nodes[nde];
  273. if (!node.jointName) {
  274. continue;
  275. }
  276. var children = node.children;
  277. for (var i = 0; i < children.length; i++) {
  278. var child: IGLTFNode = gltfRuntime.nodes[children[i]];
  279. if (!child.jointName) {
  280. continue;
  281. }
  282. if (child.jointName === jointName) {
  283. var mat = configureBoneTransformation(node);
  284. var bone = new Bone(node.name, newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  285. bone.id = nde;
  286. return bone;
  287. }
  288. }
  289. }
  290. return null;
  291. }
  292. /**
  293. * Returns the appropriate root node
  294. */
  295. var getNodeToRoot = (nodesToRoot: INodeToRoot[], id: string): Bone => {
  296. for (var i = 0; i < nodesToRoot.length; i++) {
  297. var nodeToRoot = nodesToRoot[i];
  298. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  299. var child = nodeToRoot.node.children[j];
  300. if (child === id) {
  301. return nodeToRoot.bone;
  302. }
  303. }
  304. }
  305. return null;
  306. };
  307. /**
  308. * Returns the node with the joint name
  309. */
  310. var getJointNode = (gltfRuntime: IGLTFRuntime, jointName: string): IJointNode => {
  311. var nodes = gltfRuntime.nodes;
  312. var node: IGLTFNode = nodes[jointName];
  313. if (node) {
  314. return {
  315. node: node,
  316. id: jointName
  317. };
  318. }
  319. for (var nde in nodes) {
  320. node = nodes[nde];
  321. if (node.jointName === jointName) {
  322. return {
  323. node: node,
  324. id: nde
  325. };
  326. }
  327. }
  328. return null;
  329. }
  330. /**
  331. * Checks if a nodes is in joints
  332. */
  333. var nodeIsInJoints = (skins: IGLTFSkins, id: string): boolean => {
  334. for (var i = 0; i < skins.jointNames.length; i++) {
  335. if (skins.jointNames[i] === id) {
  336. return true;
  337. }
  338. }
  339. return false;
  340. }
  341. /**
  342. * Fills the nodes to root for bones and builds hierarchy
  343. */
  344. var getNodesToRoot = (gltfRuntime: IGLTFRuntime, newSkeleton: Skeleton, skins: IGLTFSkins, nodesToRoot: INodeToRoot[]) => {
  345. // Creates nodes for root
  346. for (var nde in gltfRuntime.nodes) {
  347. var node: IGLTFNode = gltfRuntime.nodes[nde];
  348. var id = nde;
  349. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  350. continue;
  351. }
  352. // Create node to root bone
  353. var mat = configureBoneTransformation(node);
  354. var bone = new Bone(node.name, newSkeleton, null, mat);
  355. bone.id = id;
  356. nodesToRoot.push({ bone: bone, node: node, id: id });
  357. }
  358. // Parenting
  359. for (var i = 0; i < nodesToRoot.length; i++) {
  360. var nodeToRoot = nodesToRoot[i];
  361. var children = nodeToRoot.node.children;
  362. for (var j = 0; j < children.length; j++) {
  363. var child: INodeToRoot = null;
  364. for (var k = 0; k < nodesToRoot.length; k++) {
  365. if (nodesToRoot[k].id === children[j]) {
  366. child = nodesToRoot[k];
  367. break;
  368. }
  369. }
  370. if (child) {
  371. (<any>child.bone)._parent = nodeToRoot.bone;
  372. nodeToRoot.bone.children.push(child.bone);
  373. }
  374. }
  375. }
  376. };
  377. var printMat = (m: Float32Array) => {
  378. console.log(
  379. m[0] + "\t" + m[1] + "\t" + m[2] + "\t" + m[3] + "\n" +
  380. m[4] + "\t" + m[5] + "\t" + m[6] + "\t" + m[7] + "\n" +
  381. m[8] + "\t" + m[9] + "\t" + m[10] + "\t" + m[11] + "\n" +
  382. m[12] + "\t" + m[13] + "\t" + m[14] + "\t" + m[15] + "\n"
  383. );
  384. }
  385. /**
  386. * Imports a skeleton
  387. */
  388. var importSkeleton = (gltfRuntime: IGLTFRuntime, skins: IGLTFSkins, mesh: Mesh, newSkeleton: Skeleton, id: string): Skeleton => {
  389. if (!newSkeleton) {
  390. newSkeleton = new Skeleton(skins.name, "", gltfRuntime.scene);
  391. }
  392. if (!skins.babylonSkeleton) {
  393. return newSkeleton;
  394. }
  395. // Matrices
  396. var accessor = gltfRuntime.accessors[skins.inverseBindMatrices];
  397. var buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  398. var bindShapeMatrix = Matrix.FromArray(skins.bindShapeMatrix);
  399. // Find the root bones
  400. var nodesToRoot: INodeToRoot[] = [];
  401. var nodesToRootToAdd: Bone[] = [];
  402. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  403. newSkeleton.bones = [];
  404. // Joints
  405. for (var i = 0; i < skins.jointNames.length; i++) {
  406. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  407. var node = jointNode.node;
  408. if (!node) {
  409. Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  410. continue;
  411. }
  412. var id = jointNode.id;
  413. // Optimize, if the bone already exists...
  414. var existingBone = gltfRuntime.scene.getBoneByID(id);
  415. if (existingBone) {
  416. newSkeleton.bones.push(existingBone);
  417. continue;
  418. }
  419. // Search for parent bone
  420. var foundBone = false;
  421. var parentBone: Bone = null;
  422. for (var j = 0; j < i; j++) {
  423. var joint: IGLTFNode = getJointNode(gltfRuntime, skins.jointNames[j]).node;
  424. if (!joint) {
  425. Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  426. continue;
  427. }
  428. var children = joint.children;
  429. if (!children) {
  430. continue;
  431. }
  432. foundBone = false;
  433. for (var k = 0; k < children.length; k++) {
  434. if (children[k] === id) {
  435. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  436. foundBone = true;
  437. break;
  438. }
  439. }
  440. if (foundBone) {
  441. break;
  442. }
  443. }
  444. // Create bone
  445. var mat = configureBoneTransformation(node);
  446. if (!parentBone && nodesToRoot.length > 0) {
  447. parentBone = getNodeToRoot(nodesToRoot, id);
  448. if (parentBone) {
  449. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  450. nodesToRootToAdd.push(parentBone);
  451. }
  452. }
  453. }
  454. var bone = new Bone(node.jointName, newSkeleton, parentBone, mat);
  455. bone.id = id;
  456. }
  457. // Polish
  458. var bones = newSkeleton.bones;
  459. newSkeleton.bones = [];
  460. for (var i = 0; i < skins.jointNames.length; i++) {
  461. var jointNode: IJointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  462. if (!jointNode) {
  463. continue;
  464. }
  465. for (var j = 0; j < bones.length; j++) {
  466. if (bones[j].id === jointNode.id) {
  467. newSkeleton.bones.push(bones[j]);
  468. break;
  469. }
  470. }
  471. }
  472. newSkeleton.prepare();
  473. // Finish
  474. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  475. newSkeleton.bones.push(nodesToRootToAdd[i]);
  476. }
  477. return newSkeleton;
  478. };
  479. /**
  480. * Imports a mesh and its geometries
  481. */
  482. var importMesh = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, meshes: string[], id: string, newMesh: Mesh): Mesh => {
  483. if (!newMesh) {
  484. newMesh = new Mesh(node.name, gltfRuntime.scene);
  485. newMesh.id = id;
  486. }
  487. if (!node.babylonNode) {
  488. return newMesh;
  489. }
  490. var multiMat = new MultiMaterial("multimat" + id, gltfRuntime.scene);
  491. if (!newMesh.material) {
  492. newMesh.material = multiMat;
  493. }
  494. var vertexData = new VertexData();
  495. var geometry = new Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  496. var verticesStarts = [];
  497. var verticesCounts = [];
  498. var indexStarts = [];
  499. var indexCounts = [];
  500. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  501. var meshID = meshes[meshIndex];
  502. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  503. if (!mesh) {
  504. continue;
  505. }
  506. // Positions, normals and UVs
  507. for (var i = 0; i < mesh.primitives.length; i++) {
  508. // Temporary vertex data
  509. var tempVertexData = new VertexData();
  510. var primitive = mesh.primitives[i];
  511. if (primitive.mode !== 4) {
  512. // continue;
  513. }
  514. var attributes = primitive.attributes;
  515. var accessor: IGLTFAccessor = null;
  516. var buffer: any = null;
  517. // Set positions, normal and uvs
  518. for (var semantic in attributes) {
  519. // Link accessor and buffer view
  520. accessor = gltfRuntime.accessors[attributes[semantic]];
  521. buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  522. if (semantic === "NORMAL") {
  523. tempVertexData.normals = new Float32Array(buffer.length);
  524. (<Float32Array>tempVertexData.normals).set(buffer);
  525. }
  526. else if (semantic === "POSITION") {
  527. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  528. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  529. for (var j = 0; j < buffer.length; j += 4) {
  530. tempVertexData.positions[j] = buffer[j];
  531. tempVertexData.positions[j + 1] = buffer[j + 1];
  532. tempVertexData.positions[j + 2] = buffer[j + 2];
  533. }
  534. }
  535. else {
  536. tempVertexData.positions = new Float32Array(buffer.length);
  537. (<Float32Array>tempVertexData.positions).set(buffer);
  538. }
  539. verticesCounts.push(tempVertexData.positions.length);
  540. }
  541. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  542. var channel = Number(semantic.split("_")[1]);
  543. var uvKind = VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  544. var uvs = new Float32Array(buffer.length);
  545. (<Float32Array>uvs).set(buffer);
  546. normalizeUVs(uvs);
  547. tempVertexData.set(uvs, uvKind);
  548. }
  549. else if (semantic === "JOINT") {
  550. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  551. (<Float32Array>tempVertexData.matricesIndices).set(buffer);
  552. }
  553. else if (semantic === "WEIGHT") {
  554. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  555. (<Float32Array>tempVertexData.matricesWeights).set(buffer);
  556. }
  557. else if (semantic === "COLOR") {
  558. tempVertexData.colors = new Float32Array(buffer.length);
  559. (<Float32Array>tempVertexData.colors).set(buffer);
  560. }
  561. }
  562. // Indices
  563. accessor = gltfRuntime.accessors[primitive.indices];
  564. if (accessor) {
  565. buffer = GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  566. tempVertexData.indices = new Int32Array(buffer.length);
  567. (<Float32Array>tempVertexData.indices).set(buffer);
  568. indexCounts.push(tempVertexData.indices.length);
  569. }
  570. else {
  571. // Set indices on the fly
  572. var indices: number[] = [];
  573. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  574. indices.push(j);
  575. }
  576. tempVertexData.indices = new Int32Array(indices);
  577. indexCounts.push(tempVertexData.indices.length);
  578. }
  579. vertexData.merge(tempVertexData);
  580. tempVertexData = undefined;
  581. // Sub material
  582. var material = gltfRuntime.scene.getMaterialByID(primitive.material);
  583. multiMat.subMaterials.push(material === null ? GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material);
  584. // Update vertices start and index start
  585. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  586. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  587. }
  588. }
  589. // Apply geometry
  590. geometry.setAllVerticesData(vertexData, false);
  591. newMesh.computeWorldMatrix(true);
  592. // Apply submeshes
  593. newMesh.subMeshes = [];
  594. var index = 0;
  595. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  596. var meshID = meshes[meshIndex];
  597. var mesh: IGLTFMesh = gltfRuntime.meshes[meshID];
  598. if (!mesh) {
  599. continue;
  600. }
  601. for (var i = 0; i < mesh.primitives.length; i++) {
  602. if (mesh.primitives[i].mode !== 4) {
  603. //continue;
  604. }
  605. var subMesh = new SubMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  606. index++;
  607. }
  608. }
  609. // Finish
  610. return newMesh;
  611. };
  612. /**
  613. * Configure node transformation from position, rotation and scaling
  614. */
  615. var configureNode = (newNode: any, position: Vector3, rotation: Quaternion, scaling: Vector3) => {
  616. if (newNode.position) {
  617. newNode.position = position;
  618. }
  619. if (newNode.rotationQuaternion || newNode.rotation) {
  620. newNode.rotationQuaternion = rotation;
  621. }
  622. if (newNode.scaling) {
  623. newNode.scaling = scaling;
  624. }
  625. };
  626. /**
  627. * Configures node from transformation matrix
  628. */
  629. var configureNodeFromMatrix = (newNode: Mesh, node: IGLTFNode, parent: Node) => {
  630. if (node.matrix) {
  631. var position = new Vector3(0, 0, 0);
  632. var rotation = new Quaternion();
  633. var scaling = new Vector3(0, 0, 0);
  634. var mat = Matrix.FromArray(node.matrix);
  635. mat.decompose(scaling, rotation, position);
  636. configureNode(newNode, position, rotation, scaling);
  637. }
  638. else {
  639. configureNode(newNode, Vector3.FromArray(node.translation), Quaternion.FromArray(node.rotation), Vector3.FromArray(node.scale));
  640. }
  641. newNode.computeWorldMatrix(true);
  642. };
  643. /**
  644. * Imports a node
  645. */
  646. var importNode = (gltfRuntime: IGLTFRuntime, node: IGLTFNode, id: string, parent: Node): Node => {
  647. var lastNode: Node = null;
  648. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  649. if (gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name) === -1) {
  650. return null;
  651. }
  652. }
  653. // Meshes
  654. if (node.skin) {
  655. if (node.meshes) {
  656. var skin: IGLTFSkins = gltfRuntime.skins[node.skin];
  657. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, <Mesh>node.babylonNode);
  658. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  659. if (newMesh.skeleton === null) {
  660. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  661. if (!skin.babylonSkeleton) {
  662. skin.babylonSkeleton = newMesh.skeleton;
  663. }
  664. }
  665. lastNode = newMesh;
  666. }
  667. }
  668. else if (node.meshes) {
  669. /**
  670. * Improve meshes property
  671. */
  672. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, <Mesh>node.babylonNode);
  673. lastNode = newMesh;
  674. }
  675. // Lights
  676. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  677. var light: IGLTFLight = gltfRuntime.lights[node.light];
  678. if (light) {
  679. if (light.type === "ambient") {
  680. var ambienLight: IGLTFAmbienLight = light[light.type];
  681. var hemiLight = new HemisphericLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  682. hemiLight.name = node.name;
  683. if (ambienLight.color) {
  684. hemiLight.diffuse = Color3.FromArray(ambienLight.color);
  685. }
  686. lastNode = hemiLight;
  687. }
  688. else if (light.type === "directional") {
  689. var directionalLight: IGLTFDirectionalLight = light[light.type];
  690. var dirLight = new DirectionalLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  691. dirLight.name = node.name;
  692. if (directionalLight.color) {
  693. dirLight.diffuse = Color3.FromArray(directionalLight.color);
  694. }
  695. lastNode = dirLight;
  696. }
  697. else if (light.type === "point") {
  698. var pointLight: IGLTFPointLight = light[light.type];
  699. var ptLight = new PointLight(node.light, Vector3.Zero(), gltfRuntime.scene);
  700. ptLight.name = node.name;
  701. if (pointLight.color) {
  702. ptLight.diffuse = Color3.FromArray(pointLight.color);
  703. }
  704. lastNode = ptLight;
  705. }
  706. else if (light.type === "spot") {
  707. var spotLight: IGLTFSpotLight = light[light.type];
  708. var spLight = new SpotLight(node.light, Vector3.Zero(), Vector3.Zero(), 0, 0, gltfRuntime.scene);
  709. spLight.name = node.name;
  710. if (spotLight.color) {
  711. spLight.diffuse = Color3.FromArray(spotLight.color);
  712. }
  713. if (spotLight.fallOfAngle) {
  714. spLight.angle = spotLight.fallOfAngle;
  715. }
  716. if (spotLight.fallOffExponent) {
  717. spLight.exponent = spotLight.fallOffExponent;
  718. }
  719. lastNode = spLight;
  720. }
  721. }
  722. }
  723. // Cameras
  724. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  725. var camera: IGLTFCamera = gltfRuntime.cameras[node.camera];
  726. if (camera) {
  727. if (camera.type === "orthographic") {
  728. var orthographicCamera: IGLTFCameraOrthographic = camera[camera.type];
  729. var orthoCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  730. orthoCamera.name = node.name;
  731. orthoCamera.mode = Camera.ORTHOGRAPHIC_CAMERA;
  732. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  733. lastNode = orthoCamera;
  734. }
  735. else if (camera.type === "perspective") {
  736. var perspectiveCamera: IGLTFCameraPerspective = camera[camera.type];
  737. var persCamera = new FreeCamera(node.camera, Vector3.Zero(), gltfRuntime.scene);
  738. persCamera.name = node.name;
  739. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  740. if (!perspectiveCamera.aspectRatio) {
  741. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  742. }
  743. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  744. persCamera.maxZ = perspectiveCamera.zfar;
  745. persCamera.minZ = perspectiveCamera.znear;
  746. }
  747. lastNode = persCamera;
  748. }
  749. }
  750. }
  751. // Empty node
  752. if (!node.jointName) {
  753. if (node.babylonNode) {
  754. return node.babylonNode;
  755. }
  756. else if (lastNode === null) {
  757. var dummy = new Mesh(node.name, gltfRuntime.scene);
  758. node.babylonNode = dummy;
  759. lastNode = dummy;
  760. }
  761. }
  762. if (lastNode !== null) {
  763. if (node.matrix && lastNode instanceof Mesh) {
  764. configureNodeFromMatrix(lastNode, node, parent);
  765. }
  766. else {
  767. var translation = node.translation || [0, 0, 0];
  768. var rotation = node.rotation || [0, 0, 0, 1];
  769. var scale = node.scale || [1, 1, 1];
  770. configureNode(lastNode, Vector3.FromArray(translation), Quaternion.FromArray(rotation), Vector3.FromArray(scale));
  771. }
  772. lastNode.updateCache(true);
  773. node.babylonNode = lastNode;
  774. }
  775. return lastNode;
  776. };
  777. /**
  778. * Traverses nodes and creates them
  779. */
  780. var traverseNodes = (gltfRuntime: IGLTFRuntime, id: string, parent: Node, meshIncluded?: boolean) => {
  781. var node: IGLTFNode = gltfRuntime.nodes[id];
  782. var newNode: Node = null;
  783. if (gltfRuntime.importOnlyMeshes && !meshIncluded) {
  784. if (gltfRuntime.importMeshesNames.indexOf(node.name) !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  785. meshIncluded = true;
  786. }
  787. else {
  788. meshIncluded = false;
  789. }
  790. }
  791. else {
  792. meshIncluded = true;
  793. }
  794. if (!node.jointName && meshIncluded) {
  795. newNode = importNode(gltfRuntime, node, id, parent);
  796. if (newNode !== null) {
  797. newNode.id = id;
  798. newNode.parent = parent;
  799. }
  800. }
  801. if (node.children) {
  802. for (var i = 0; i < node.children.length; i++) {
  803. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  804. }
  805. }
  806. };
  807. /**
  808. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  809. */
  810. var postLoad = (gltfRuntime: IGLTFRuntime) => {
  811. // Nodes
  812. var currentScene: IGLTFScene = <IGLTFScene>gltfRuntime.currentScene;
  813. if (currentScene) {
  814. for (var i = 0; i < currentScene.nodes.length; i++) {
  815. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  816. }
  817. }
  818. else {
  819. for (var thing in gltfRuntime.scenes) {
  820. currentScene = <IGLTFScene>gltfRuntime.scenes[thing];
  821. for (var i = 0; i < currentScene.nodes.length; i++) {
  822. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  823. }
  824. }
  825. }
  826. // Set animations
  827. loadAnimations(gltfRuntime);
  828. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  829. var skeleton = gltfRuntime.scene.skeletons[i];
  830. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  831. }
  832. };
  833. /**
  834. * onBind shaderrs callback to set uniforms and matrices
  835. */
  836. var onBindShaderMaterial = (mesh: Mesh, gltfRuntime: IGLTFRuntime, unTreatedUniforms: Object, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, onSuccess: (shaderMaterial: ShaderMaterial) => void) => {
  837. var materialValues = material.values || technique.parameters;
  838. for (var unif in unTreatedUniforms) {
  839. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  840. var type = uniform.type;
  841. if (type === EParameterType.FLOAT_MAT2 || type === EParameterType.FLOAT_MAT3 || type === EParameterType.FLOAT_MAT4) {
  842. if (uniform.semantic && !uniform.source && !uniform.node) {
  843. GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  844. }
  845. else if (uniform.semantic && (uniform.source || uniform.node)) {
  846. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node);
  847. if (source === null) {
  848. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node);
  849. }
  850. if (source === null) {
  851. continue;
  852. }
  853. GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  854. }
  855. }
  856. else {
  857. var value = materialValues[technique.uniforms[unif]];
  858. if (!value) {
  859. continue;
  860. }
  861. if (type === EParameterType.SAMPLER_2D) {
  862. var texture: Texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  863. if (texture === null || texture === undefined) {
  864. continue;
  865. }
  866. shaderMaterial.getEffect().setTexture(unif, texture);
  867. }
  868. else {
  869. GLTFUtils.SetUniform(shaderMaterial.getEffect(), unif, value, type);
  870. }
  871. }
  872. }
  873. onSuccess(shaderMaterial);
  874. };
  875. /**
  876. * Prepare uniforms to send the only one time
  877. * Loads the appropriate textures
  878. */
  879. var prepareShaderMaterialUniforms = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: Object) => {
  880. var materialValues = material.values || technique.parameters;
  881. var techniqueUniforms = technique.uniforms;
  882. /**
  883. * Prepare values here (not matrices)
  884. */
  885. for (var unif in unTreatedUniforms) {
  886. var uniform: IGLTFTechniqueParameter = unTreatedUniforms[unif];
  887. var type = uniform.type;
  888. var value = materialValues[techniqueUniforms[unif]];
  889. if (value === undefined) {
  890. // In case the value is the same for all materials
  891. value = <any>uniform.value;
  892. }
  893. if (!value) {
  894. continue;
  895. }
  896. var onLoadTexture = (uniformName: string) => {
  897. return (texture: Texture) => {
  898. if (uniform.value) {
  899. // Static uniform
  900. shaderMaterial.setTexture(uniformName, texture);
  901. delete unTreatedUniforms[uniformName];
  902. }
  903. }
  904. };
  905. // Texture (sampler2D)
  906. if (type === EParameterType.SAMPLER_2D) {
  907. GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), () => onLoadTexture(null));
  908. }
  909. // Others
  910. else {
  911. if (uniform.value && GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  912. // Static uniform
  913. delete unTreatedUniforms[unif];
  914. }
  915. }
  916. }
  917. };
  918. /**
  919. * Shader compilation failed
  920. */
  921. var onShaderCompileError = (program: IGLTFProgram, shaderMaterial: ShaderMaterial, onError: () => void) => {
  922. return (effect: Effect, error: string) => {
  923. Tools.Error("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  924. shaderMaterial.dispose(true);
  925. onError();
  926. };
  927. };
  928. /**
  929. * Shader compilation success
  930. */
  931. var onShaderCompileSuccess = (gltfRuntime: IGLTFRuntime, shaderMaterial: ShaderMaterial, technique: IGLTFTechnique, material: IGLTFMaterial, unTreatedUniforms: Object, onSuccess: (shaderMaterial: ShaderMaterial) => void) => {
  932. return (_: Effect) => {
  933. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  934. shaderMaterial.onBind = (mesh: Mesh) => {
  935. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  936. };
  937. };
  938. };
  939. /**
  940. * Returns the appropriate uniform if already handled by babylon
  941. */
  942. var parseShaderUniforms = (tokenizer: Tokenizer, technique: IGLTFTechnique, unTreatedUniforms: Object): string => {
  943. for (var unif in technique.uniforms) {
  944. var uniform = technique.uniforms[unif];
  945. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  946. if (tokenizer.currentIdentifier === unif) {
  947. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  948. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  949. if (transformIndex !== -1) {
  950. delete unTreatedUniforms[unif];
  951. return babylonTransforms[transformIndex];
  952. }
  953. }
  954. }
  955. }
  956. return tokenizer.currentIdentifier;
  957. };
  958. /**
  959. * All shaders loaded. Create materials one by one
  960. */
  961. var importMaterials = (gltfRuntime: IGLTFRuntime) => {
  962. // Create materials
  963. for (var mat in gltfRuntime.materials) {
  964. GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, (material: Material) => { }, () => { });
  965. }
  966. };
  967. /**
  968. * Implementation of the base glTF spec
  969. */
  970. export class GLTFLoaderBase {
  971. public static CreateRuntime(parsedData: any, scene: Scene, rootUrl: string): IGLTFRuntime {
  972. var gltfRuntime: IGLTFRuntime = {
  973. extensions: {},
  974. accessors: {},
  975. buffers: {},
  976. bufferViews: {},
  977. meshes: {},
  978. lights: {},
  979. cameras: {},
  980. nodes: {},
  981. images: {},
  982. textures: {},
  983. shaders: {},
  984. programs: {},
  985. samplers: {},
  986. techniques: {},
  987. materials: {},
  988. animations: {},
  989. skins: {},
  990. extensionsUsed: [],
  991. scenes: {},
  992. buffersCount: 0,
  993. shaderscount: 0,
  994. scene: scene,
  995. rootUrl: rootUrl,
  996. loadedBufferCount: 0,
  997. loadedBufferViews: {},
  998. loadedShaderCount: 0,
  999. importOnlyMeshes: false,
  1000. dummyNodes: []
  1001. }
  1002. // Parse
  1003. if (parsedData.extensions) {
  1004. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  1005. }
  1006. if (parsedData.extensionsUsed) {
  1007. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  1008. }
  1009. if (parsedData.buffers) {
  1010. parseBuffers(parsedData.buffers, gltfRuntime);
  1011. }
  1012. if (parsedData.bufferViews) {
  1013. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  1014. }
  1015. if (parsedData.accessors) {
  1016. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  1017. }
  1018. if (parsedData.meshes) {
  1019. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  1020. }
  1021. if (parsedData.lights) {
  1022. parseObject(parsedData.lights, "lights", gltfRuntime);
  1023. }
  1024. if (parsedData.cameras) {
  1025. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  1026. }
  1027. if (parsedData.nodes) {
  1028. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  1029. }
  1030. if (parsedData.images) {
  1031. parseObject(parsedData.images, "images", gltfRuntime);
  1032. }
  1033. if (parsedData.textures) {
  1034. parseObject(parsedData.textures, "textures", gltfRuntime);
  1035. }
  1036. if (parsedData.shaders) {
  1037. parseShaders(parsedData.shaders, gltfRuntime);
  1038. }
  1039. if (parsedData.programs) {
  1040. parseObject(parsedData.programs, "programs", gltfRuntime);
  1041. }
  1042. if (parsedData.samplers) {
  1043. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  1044. }
  1045. if (parsedData.techniques) {
  1046. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  1047. }
  1048. if (parsedData.materials) {
  1049. parseObject(parsedData.materials, "materials", gltfRuntime);
  1050. }
  1051. if (parsedData.animations) {
  1052. parseObject(parsedData.animations, "animations", gltfRuntime);
  1053. }
  1054. if (parsedData.skins) {
  1055. parseObject(parsedData.skins, "skins", gltfRuntime);
  1056. }
  1057. if (parsedData.scenes) {
  1058. gltfRuntime.scenes = parsedData.scenes;
  1059. }
  1060. if (parsedData.scene && parsedData.scenes) {
  1061. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  1062. }
  1063. return gltfRuntime;
  1064. }
  1065. public static LoadBufferAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (buffer: ArrayBufferView) => void, onError: () => void, onProgress?: () => void): void {
  1066. var buffer: IGLTFBuffer = gltfRuntime.buffers[id];
  1067. if (GLTFUtils.IsBase64(buffer.uri)) {
  1068. setTimeout(() => onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(buffer.uri))));
  1069. }
  1070. else {
  1071. Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, data => onSuccess(new Uint8Array(data)), onProgress, null, true, onError);
  1072. }
  1073. }
  1074. public static LoadTextureBufferAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (buffer: ArrayBufferView) => void, onError: () => void): void {
  1075. var texture: IGLTFTexture = gltfRuntime.textures[id];
  1076. if (!texture || !texture.source) {
  1077. onError();
  1078. return;
  1079. }
  1080. if (texture.babylonTexture) {
  1081. onSuccess(null);
  1082. return;
  1083. }
  1084. var source: IGLTFImage = gltfRuntime.images[texture.source];
  1085. if (GLTFUtils.IsBase64(source.uri)) {
  1086. setTimeout(() => onSuccess(new Uint8Array(GLTFUtils.DecodeBase64(source.uri))));
  1087. }
  1088. else {
  1089. Tools.LoadFile(gltfRuntime.rootUrl + source.uri, data => onSuccess(new Uint8Array(data)), null, null, true, onError);
  1090. }
  1091. }
  1092. public static CreateTextureAsync(gltfRuntime: IGLTFRuntime, id: string, buffer: ArrayBufferView, onSuccess: (texture: Texture) => void, onError: () => void): void {
  1093. var texture: IGLTFTexture = gltfRuntime.textures[id];
  1094. if (texture.babylonTexture) {
  1095. onSuccess(texture.babylonTexture);
  1096. return;
  1097. }
  1098. var sampler: IGLTFSampler = gltfRuntime.samplers[texture.sampler];
  1099. var createMipMaps =
  1100. (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  1101. (sampler.minFilter === ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  1102. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  1103. (sampler.minFilter === ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  1104. var samplingMode = Texture.BILINEAR_SAMPLINGMODE;
  1105. var blob = new Blob([buffer]);
  1106. var blobURL = URL.createObjectURL(blob);
  1107. var revokeBlobURL = () => URL.revokeObjectURL(blobURL);
  1108. var newTexture = new Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  1109. newTexture.wrapU = GLTFUtils.GetWrapMode(sampler.wrapS);
  1110. newTexture.wrapV = GLTFUtils.GetWrapMode(sampler.wrapT);
  1111. newTexture.name = id;
  1112. texture.babylonTexture = newTexture;
  1113. onSuccess(newTexture);
  1114. }
  1115. public static LoadShaderStringAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (shaderString: string) => void, onError: () => void): void {
  1116. var shader: IGLTFShader = gltfRuntime.shaders[id];
  1117. if (GLTFUtils.IsBase64(shader.uri)) {
  1118. var shaderString = atob(shader.uri.split(",")[1]);
  1119. onSuccess(shaderString);
  1120. }
  1121. else {
  1122. Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, null, null, false, onError);
  1123. }
  1124. }
  1125. public static LoadMaterialAsync(gltfRuntime: IGLTFRuntime, id: string, onSuccess: (material: Material) => void, onError: () => void): void {
  1126. var material: IGLTFMaterial = gltfRuntime.materials[id];
  1127. var technique: IGLTFTechnique = gltfRuntime.techniques[material.technique];
  1128. if (!technique) {
  1129. var defaultMaterial = new StandardMaterial(id, gltfRuntime.scene);
  1130. defaultMaterial.diffuseColor = new Color3(0.5, 0.5, 0.5);
  1131. defaultMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  1132. onSuccess(defaultMaterial);
  1133. return;
  1134. }
  1135. var program: IGLTFProgram = gltfRuntime.programs[technique.program];
  1136. var states: IGLTFTechniqueStates = technique.states;
  1137. var vertexShader: string = Effect.ShadersStore[program.vertexShader + "VertexShader"];
  1138. var pixelShader: string = Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  1139. var newVertexShader = "";
  1140. var newPixelShader = "";
  1141. var vertexTokenizer = new Tokenizer(vertexShader);
  1142. var pixelTokenizer = new Tokenizer(pixelShader);
  1143. var unTreatedUniforms: Object = {};
  1144. var uniforms = [];
  1145. var attributes = [];
  1146. var samplers = [];
  1147. // Fill uniform, sampler2D and attributes
  1148. for (var unif in technique.uniforms) {
  1149. var uniform = technique.uniforms[unif];
  1150. var uniformParameter: IGLTFTechniqueParameter = technique.parameters[uniform];
  1151. unTreatedUniforms[unif] = uniformParameter;
  1152. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  1153. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  1154. if (transformIndex !== -1) {
  1155. uniforms.push(babylonTransforms[transformIndex]);
  1156. delete unTreatedUniforms[unif];
  1157. }
  1158. else {
  1159. uniforms.push(unif);
  1160. }
  1161. }
  1162. else if (uniformParameter.type === EParameterType.SAMPLER_2D) {
  1163. samplers.push(unif);
  1164. }
  1165. else {
  1166. uniforms.push(unif);
  1167. }
  1168. }
  1169. for (var attr in technique.attributes) {
  1170. var attribute = technique.attributes[attr];
  1171. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1172. if (attributeParameter.semantic) {
  1173. attributes.push(getAttribute(attributeParameter));
  1174. }
  1175. }
  1176. // Configure vertex shader
  1177. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  1178. var tokenType = vertexTokenizer.currentToken;
  1179. if (tokenType !== ETokenType.IDENTIFIER) {
  1180. newVertexShader += vertexTokenizer.currentString;
  1181. continue;
  1182. }
  1183. var foundAttribute = false;
  1184. for (var attr in technique.attributes) {
  1185. var attribute = technique.attributes[attr];
  1186. var attributeParameter: IGLTFTechniqueParameter = technique.parameters[attribute];
  1187. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  1188. newVertexShader += getAttribute(attributeParameter);
  1189. foundAttribute = true;
  1190. break;
  1191. }
  1192. }
  1193. if (foundAttribute) {
  1194. continue;
  1195. }
  1196. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  1197. }
  1198. // Configure pixel shader
  1199. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  1200. var tokenType = pixelTokenizer.currentToken;
  1201. if (tokenType !== ETokenType.IDENTIFIER) {
  1202. newPixelShader += pixelTokenizer.currentString;
  1203. continue;
  1204. }
  1205. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  1206. }
  1207. // Create shader material
  1208. var shaderPath = {
  1209. vertex: program.vertexShader + id,
  1210. fragment: program.fragmentShader + id
  1211. };
  1212. var options = {
  1213. attributes: attributes,
  1214. uniforms: uniforms,
  1215. samplers: samplers,
  1216. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  1217. };
  1218. Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  1219. Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  1220. var shaderMaterial = new ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  1221. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  1222. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  1223. shaderMaterial.sideOrientation = Material.CounterClockWiseSideOrientation;
  1224. if (states && states.functions) {
  1225. var functions = states.functions;
  1226. if (functions.cullFace && functions.cullFace[0] !== ECullingType.BACK) {
  1227. shaderMaterial.backFaceCulling = false;
  1228. }
  1229. var blendFunc = functions.blendFuncSeparate;
  1230. if (blendFunc) {
  1231. if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_ALPHA && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1232. shaderMaterial.alphaMode = Engine.ALPHA_COMBINE;
  1233. }
  1234. else if (blendFunc[0] === EBlendingFunction.ONE && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1235. shaderMaterial.alphaMode = Engine.ALPHA_ONEONE;
  1236. }
  1237. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE && blendFunc[2] === EBlendingFunction.ZERO && blendFunc[3] === EBlendingFunction.ONE) {
  1238. shaderMaterial.alphaMode = Engine.ALPHA_ADD;
  1239. }
  1240. else if (blendFunc[0] === EBlendingFunction.ZERO && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1241. shaderMaterial.alphaMode = Engine.ALPHA_SUBTRACT;
  1242. }
  1243. else if (blendFunc[0] === EBlendingFunction.DST_COLOR && blendFunc[1] === EBlendingFunction.ZERO && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1244. shaderMaterial.alphaMode = Engine.ALPHA_MULTIPLY;
  1245. }
  1246. else if (blendFunc[0] === EBlendingFunction.SRC_ALPHA && blendFunc[1] === EBlendingFunction.ONE_MINUS_SRC_COLOR && blendFunc[2] === EBlendingFunction.ONE && blendFunc[3] === EBlendingFunction.ONE) {
  1247. shaderMaterial.alphaMode = Engine.ALPHA_MAXIMIZED;
  1248. }
  1249. }
  1250. }
  1251. }
  1252. }
  1253. /**
  1254. * glTF V1 Loader
  1255. */
  1256. export class GLTFLoader implements IGLTFLoader {
  1257. public static Extensions: { [name: string]: GLTFLoaderExtension } = {};
  1258. public static RegisterExtension(extension: GLTFLoaderExtension): void {
  1259. if (GLTFLoader.Extensions[extension.name]) {
  1260. Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  1261. return;
  1262. }
  1263. GLTFLoader.Extensions[extension.name] = extension;
  1264. }
  1265. public importMeshAsync(meshesNames: any, scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess?: (meshes: AbstractMesh[], particleSystems: ParticleSystem[], skeletons: Skeleton[]) => void, onError?: () => void, onProgress?: () => void): boolean {
  1266. scene.useRightHandedSystem = true;
  1267. var gltfRuntime = GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, gltfRuntime => {
  1268. gltfRuntime.importOnlyMeshes = true;
  1269. if (meshesNames === "") {
  1270. gltfRuntime.importMeshesNames = [];
  1271. }
  1272. else if (typeof meshesNames === "string") {
  1273. gltfRuntime.importMeshesNames = [meshesNames];
  1274. }
  1275. else if (meshesNames && !(meshesNames instanceof Array)) {
  1276. gltfRuntime.importMeshesNames = [meshesNames];
  1277. }
  1278. else {
  1279. gltfRuntime.importMeshesNames = [];
  1280. Tools.Warn("Argument meshesNames must be of type string or string[]");
  1281. }
  1282. // Create nodes
  1283. this._createNodes(gltfRuntime);
  1284. var meshes = [];
  1285. var skeletons = [];
  1286. // Fill arrays of meshes and skeletons
  1287. for (var nde in gltfRuntime.nodes) {
  1288. var node: IGLTFNode = gltfRuntime.nodes[nde];
  1289. if (node.babylonNode instanceof AbstractMesh) {
  1290. meshes.push(<AbstractMesh>node.babylonNode);
  1291. }
  1292. }
  1293. for (var skl in gltfRuntime.skins) {
  1294. var skin: IGLTFSkins = gltfRuntime.skins[skl];
  1295. if (skin.babylonSkeleton instanceof Skeleton) {
  1296. skeletons.push(skin.babylonSkeleton);
  1297. }
  1298. }
  1299. // Load buffers, shaders, materials, etc.
  1300. this._loadBuffersAsync(gltfRuntime, () => {
  1301. this._loadShadersAsync(gltfRuntime, () => {
  1302. importMaterials(gltfRuntime);
  1303. postLoad(gltfRuntime);
  1304. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1305. onSuccess(meshes, null, skeletons);
  1306. }
  1307. });
  1308. },
  1309. onProgress);
  1310. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  1311. onSuccess(meshes, null, skeletons);
  1312. }
  1313. }, onError);
  1314. return true;
  1315. }
  1316. public loadAsync(scene: Scene, data: IGLTFLoaderData, rootUrl: string, onSuccess: () => void, onError: () => void): void {
  1317. scene.useRightHandedSystem = true;
  1318. GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, gltfRuntime => {
  1319. // Load runtime extensios
  1320. GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, () => {
  1321. // Create nodes
  1322. this._createNodes(gltfRuntime);
  1323. // Load buffers, shaders, materials, etc.
  1324. this._loadBuffersAsync(gltfRuntime, () => {
  1325. this._loadShadersAsync(gltfRuntime, () => {
  1326. importMaterials(gltfRuntime);
  1327. postLoad(gltfRuntime);
  1328. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  1329. onSuccess();
  1330. }
  1331. });
  1332. });
  1333. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  1334. onSuccess();
  1335. }
  1336. }, onError);
  1337. }, onError);
  1338. }
  1339. private _loadShadersAsync(gltfRuntime: IGLTFRuntime, onload: () => void): void {
  1340. var hasShaders = false;
  1341. var processShader = (sha: string, shader: IGLTFShader) => {
  1342. GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, shaderString => {
  1343. gltfRuntime.loadedShaderCount++;
  1344. if (shaderString) {
  1345. Effect.ShadersStore[sha + (shader.type === EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  1346. }
  1347. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  1348. onload();
  1349. }
  1350. }, () => {
  1351. Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  1352. });
  1353. };
  1354. for (var sha in gltfRuntime.shaders) {
  1355. hasShaders = true;
  1356. var shader: IGLTFShader = gltfRuntime.shaders[sha];
  1357. if (shader) {
  1358. processShader.bind(this, sha, shader)();
  1359. }
  1360. else {
  1361. Tools.Error("No shader named: " + sha);
  1362. }
  1363. }
  1364. if (!hasShaders) {
  1365. onload();
  1366. }
  1367. };
  1368. private _loadBuffersAsync(gltfRuntime: IGLTFRuntime, onload: () => void, onProgress?: () => void): void {
  1369. var hasBuffers = false;
  1370. var processBuffer = (buf: string, buffer: IGLTFBuffer) => {
  1371. GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, bufferView => {
  1372. gltfRuntime.loadedBufferCount++;
  1373. if (bufferView) {
  1374. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  1375. Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  1376. }
  1377. gltfRuntime.loadedBufferViews[buf] = bufferView;
  1378. }
  1379. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  1380. onload();
  1381. }
  1382. }, () => {
  1383. Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  1384. });
  1385. };
  1386. for (var buf in gltfRuntime.buffers) {
  1387. hasBuffers = true;
  1388. var buffer: IGLTFBuffer = gltfRuntime.buffers[buf];
  1389. if (buffer) {
  1390. processBuffer.bind(this, buf, buffer)();
  1391. }
  1392. else {
  1393. Tools.Error("No buffer named: " + buf);
  1394. }
  1395. }
  1396. if (!hasBuffers) {
  1397. onload();
  1398. }
  1399. }
  1400. private _createNodes(gltfRuntime: IGLTFRuntime): void {
  1401. var currentScene = <IGLTFScene>gltfRuntime.currentScene;
  1402. if (currentScene) {
  1403. // Only one scene even if multiple scenes are defined
  1404. for (var i = 0; i < currentScene.nodes.length; i++) {
  1405. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1406. }
  1407. }
  1408. else {
  1409. // Load all scenes
  1410. for (var thing in gltfRuntime.scenes) {
  1411. currentScene = <IGLTFScene>gltfRuntime.scenes[thing];
  1412. for (var i = 0; i < currentScene.nodes.length; i++) {
  1413. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  1414. }
  1415. }
  1416. }
  1417. }
  1418. };
  1419. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = () => new GLTFLoader();
  1420. }