babylon.glTFFileLoader.ts 65 KB

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