/home/lindsay/xeolabs/xeogl-next/xeogl/examples/js/models/glTFModel.js
API Docs for:

File: /home/lindsay/xeolabs/xeogl-next/xeogl/examples/js/models/glTFModel.js

  1. /**
  2. A **GLTFModel** is a {{#crossLink "Model"}}{{/crossLink}} that's loaded from a <a href="https://github.com/KhronosGroup/glTF" target = "_other">glTF</a> file.
  3.  
  4. <a href="../../examples/#importing_gltf_GearboxAssy"><img src="../../../assets/images/gltf/glTF_gearbox_squashed.png"></img></a>
  5.  
  6. ## Overview
  7.  
  8. * Extends {{#crossLink "Model"}}{{/crossLink}}, which extends {{#crossLink "Group"}}{{/crossLink}}, which extends {{#crossLink "Object"}}{{/crossLink}}.
  9. * Plugs into the scene graph and contains child {{#crossLink "Objects"}}{{/crossLink}} that represent its glTF model's scene node elements.
  10. * Can be configured with a handleNode callback to customize the way child Objects are created from glTF scene nodes.
  11. * Provides its dynamic World-space axis-aligned bounding box (AABB).
  12. * May be transformed, shown, hidden, ghosted, highlighted etc. as a unit.
  13. * May be configured to compress and batch geometries.
  14. * May be configured to convert materials to {{#crossLink "LambertMaterial"}}{{/crossLink}} for faster rendering.
  15.  
  16. ## Supported glTF 2.0 features
  17.  
  18. So far, GLTFModel loads only geometry, materials and modeling transform hierarchies, without animations. It does not
  19. load cameras or lights because its purpose is to import models into environments that have already been created using
  20. the xeogl API.
  21.  
  22. In addition to glTF's core metal-roughness material workflow, GLTFModel also supports two material extensions:
  23.  
  24. * KHR_materials_pbrSpecularGlossiness
  25. * KHR_materials_common
  26.  
  27. ## Examples
  28.  
  29. * [Damaged Helmet with metal/rough PBR materials](../../examples/#importing_gltf_DamagedHelmet)
  30. * [Hover bike with specular/glossiness PBR materials](../../examples/#importing_gltf_Hoverbike)
  31. * [Loading glTF with embedded assets](../../examples/#importing_gltf_embedded)
  32. * [Parsing glTF JSON with embedded assets](../../examples/#importing_gltf_parsing_embedded)
  33. * [Ignoring materials when loading](../../examples/#importing_gltf_options_ignoreMaterials)
  34. * [Converting materials to simple Lambertian when loading](../../examples/#importing_gltf_options_lambertMaterials)
  35. * [All loading options for max performance](../../examples/#importing_gltf_options_maxPerformance)
  36. * [Models within object hierarchies](../../examples/#objects_hierarchy_models)
  37.  
  38. ## Usage
  39.  
  40. * [Loading glTF](#loading-gltf)
  41. * [Parsing glTF](#parsing-gltf)
  42. * [Loading options](#loading-options)
  43. * [handleNode callback](#handlenode-callback)
  44. * [Generating IDs for loaded Objects](#generating-ids-for-loaded-objects)
  45. * [Transforming a GLTFModel](#transforming-a-gltfmodel)
  46. * [Getting the World-space boundary of a GLTFModel](#getting-the-world-space-boundary-of-a-gltfmodel)
  47. * [Clearing a GLTFModel](#clearing-a-gltfmodel)
  48. * [Destroying a GLTFModel](#destroying-a-gltfmodel)
  49.  
  50. ### Loading glTF
  51.  
  52. Load a glTF file by creating a GLTFModel:
  53.  
  54. ````javascript
  55. var model = new xeogl.GLTFModel({
  56. id: "gearbox",
  57. src: "models/gltf/gearbox_conical/scene.gltf",
  58. });
  59. ````
  60.  
  61. A GLTFModel prefixes its own ID to those of its components. The ID is optional, but in this example we're providing our own custom ID.
  62.  
  63. The GLTFModel begins loading the glTF file immediately.
  64.  
  65. To bind a callback to be notified when the file has loaded (which fires immediately if already loaded):
  66.  
  67. ````javascript
  68. model.on("loaded", function() {
  69. // GLTFModel has loaded!
  70. });
  71. ````
  72.  
  73. You can also bind a callback to fire if loading fails:
  74.  
  75. ````javascript
  76. model.on("error", function(msg) {
  77. // Error occurred
  78. });
  79. ````
  80.  
  81. To switch to a different glTF file, simply update {{#crossLink "GLTFModel/src:property"}}{{/crossLink}}:
  82.  
  83. ````javascript
  84. model.src = "models/gltf/Buggy/glTF/Buggy.gltf"
  85. ````
  86.  
  87. #### Finding GLTFModels in Scenes
  88.  
  89. Our GLTFModel will now be registered by ID on its {{#crossLink "Scene"}}{{/crossLink}}, so we can now find it like this:
  90.  
  91. ````javascript
  92. var scene = xeogl.getDefaultScene();
  93. model = scene.models["gearbox"];
  94. ````
  95.  
  96. That's assuming that we've created the GLTFModel in the default Scene, which we're doing in these examples.
  97.  
  98. We can also get all the GLTFModels in a Scene, using the Scene's {{#crossLink "Scene/types:property"}}{{/crossLink}} map:
  99.  
  100. ````javascript
  101. var gltfModels = scene.types["xeogl.GLTFModel"];
  102.  
  103. model = gltfModels["myModel"];
  104. ````
  105.  
  106. ### Parsing glTF
  107.  
  108. If we have a glTF JSON with embedded assets in memory, then we can parse it straight into a GLTFModel using the
  109. static {{#crossLink "GLTFModel/parse:method"}}{{/crossLink}} method:
  110.  
  111. ````javascript
  112. xeogl.GLTFModel.parse(model, json); // Clears the target model first
  113. ````
  114.  
  115. ### Loading options
  116.  
  117. The following options may be specified when loading glTF:
  118.  
  119. | Option | Type | Range | Default Value | Description |
  120. |:--------:|:----:|:-----:|:-------------:|:-----:|:-----------:|
  121. | lambertMaterials | Boolean | | false | When true, gives each {{#crossLink "Mesh"}}{{/crossLink}} the same {{#crossLink "LambertMaterial"}}{{/crossLink}} and a {{#crossLink "Mesh/colorize:property"}}{{/crossLink}} set the to diffuse color extracted from the glTF material. This is typically used for CAD models with huge amounts of objects, and will ignore textures.|
  122. | quantizeGeometry | Boolean | | true | When true, quantizes geometry to reduce memory and GPU bus usage (see {{#crossLink "Geometry"}}{{/crossLink}}). |
  123. | combineGeometry | Boolean | | true | When true, combines geometry vertex buffers to improve rendering performance (see {{#crossLink "Geometry"}}{{/crossLink}}). |
  124. | backfaces | Boolean | | true | When true, allows visible backfaces, wherever specified in the glTF. When false, ignores backfaces. |
  125. | ghosted | Boolean | | false | When true, ghosts all the model's Meshes (see {{#crossLink "Mesh"}}{{/crossLink}} and {{#crossLink "EmphasisMaterial"}}{{/crossLink}}). |
  126. | outlined | Boolean | | false | When true, outlines all the model's Meshes (see {{#crossLink "Mesh"}}{{/crossLink}} and {{#crossLink "OutlineMaterial"}}{{/crossLink}}). |
  127. | selected | Boolean | | false | When true, renders all the model's Meshes (see {{#crossLink "Mesh"}}{{/crossLink}} and {{#crossLink "OutlineMaterial"}}{{/crossLink}}). |
  128. | highlighted | Boolean | | false | When true, highlights all the model's Meshes (see {{#crossLink "Mesh"}}{{/crossLink}} and {{#crossLink "EmphasisMaterial"}}{{/crossLink}}). |
  129. | edges | Boolean | | false | When true, emphasizes the edges on all the model's Meshes (see {{#crossLink "Mesh"}}{{/crossLink}} and {{#crossLink "EdgeMaterial"}}{{/crossLink}}). |
  130. | edgeThreshold | Number | [0..180] | 20 | When ghosting, highlighting, selecting or edging, this is the threshold angle between normals of adjacent triangles, below which their shared wireframe edge is not drawn. |
  131. | handleNode | Function(object, object) | | null | Optional callback to mask which {{#crossLink "Object"}}Objects{{/crossLink}} are loaded. Each Object will only be loaded when this callback returns ````true```. |
  132.  
  133. As mentioned above, GLTFModels are {{#crossLink "Object"}}Objects{{/crossLink}} that plug into the scene graph, containing
  134. child Objects of their own, that represent their glTF
  135. model's ````scene```` ````node```` elements.
  136.  
  137. GLTFModels can also be configured with a ````handleNode```` callback to determine how their child
  138. {{#crossLink "Object"}}{{/crossLink}} hierarchies are created as they load the ````node```` elements.
  139.  
  140. #### handleNode callback
  141.  
  142. As a GLTFModel parses glTF, it creates child {{#crossLink "Object"}}Objects{{/crossLink}} from the ````node```` elements in the glTF ````scene````.
  143.  
  144. GLTFModel traverses the ````node```` elements in depth-first order. We can configure a GLTFModel with
  145. a ````handleNode```` callback to call at each ````node````, to indicate how to process the ````node````.
  146.  
  147. Typically, we would use the callback to selectively create Objects from the glTF ````scene````, while maybe also
  148. configuring those Objects depending on what the callback finds on their glTF ````node```` elements.
  149.  
  150. For example, we might want to load a building model and set all its wall objects initially highlighted. For ````node```` elements
  151. that have some sort of attribute that indicate that they are walls, then the callback can indicate that the GLTFModel
  152. should create Objects that are initially highlighted.
  153.  
  154. The callback accepts two arguments:
  155.  
  156. * ````nodeInfo```` - the glTF node element.
  157. * ````actions```` - an object on to which the callback may attach optional configs for each Object to create.
  158.  
  159. When the callback returns nothing or ````false````, then GLTFModel skips the given ````node```` and its children.
  160.  
  161. When the callback returns ````true````, then the GLTFModel may process the ````node````.
  162.  
  163. For each Object to create, the callback can specify initial properties for it by creating a ````createObject```` on
  164. its ````actions```` argument, containing values for those properties.
  165.  
  166. In the example below, we're loading a GLTF model of a building. We use the callback create Objects only
  167. for ````node```` elements who name is not "dontLoadMe". For those Objects, we set them highlighted if
  168. their ````node```` element's name happens to be "wall".
  169.  
  170. ````javascript
  171. var model = new xeogl.GLTFModel({
  172. src: "models/myBuilding.gltf",
  173.  
  174. // Callback to intercept creation of objects while parsing glTF scene nodes
  175.  
  176. handleNode: function (nodeInfo, actions) {
  177.  
  178. var name = nodeInfo.name;
  179.  
  180. // Don't parse glTF scene nodes that have no "name" attribute,
  181. // but do continue down to parse their children.
  182. if (!name) {
  183. return true; // Continue descending this node subtree
  184. }
  185.  
  186. // Don't parse glTF scene nodes named "dontLoadMe",
  187. // and skip their children as well.
  188. if (name === "dontLoadMe") {
  189. return false; // Stop descending this node subtree
  190. }
  191.  
  192. // Create an Object for each glTF scene node.
  193.  
  194. // Highlight the Object if the name is "wall"
  195.  
  196. actions.createObject = {
  197. highlighted: name === "wall"
  198. };
  199.  
  200. return true; // Continue descending this glTF node subtree
  201. }
  202. });
  203. ````
  204.  
  205. #### Generating IDs for loaded Objects
  206.  
  207. You can use the ````handleNodeNode```` callback to generate a unique ID for each loaded {{#crossLink "Object"}}Object{{/crossLink}}:
  208.  
  209. ````javascript
  210. var model = new xeogl.GLTFModel({
  211. id: "gearbox",
  212. src: "models/gltf/gearbox_conical/scene.gltf",
  213. handleNode: (function() {
  214. var objectCount = 0;
  215. return function (nodeInfo, actions) {
  216. if (nodeInfo.mesh !== undefined) { // Node has a mesh
  217. actions.createObject = {
  218. id: "gearbox." + objectCount++
  219. };
  220. }
  221. return true;
  222. };
  223. })()
  224. });
  225.  
  226. // Highlight a couple of Objects by ID
  227. model.on("loaded", function () {
  228. model.objects["gearbox.83"].highlighted = true;
  229. model.objects["gearbox.81"].highlighted = true;
  230. });
  231. ````
  232.  
  233. If the ````node```` elements have ````name```` attributes, then we can also use those names with the ````handleNodeNode```` callback
  234. to generate a (hopefully) unique ID for each loaded {{#crossLink "Object"}}Object{{/crossLink}}:
  235.  
  236. ````javascript
  237. var adamModel = new xeogl.GLTFModel({
  238. id: "adam",
  239. src: "models/gltf/adamHead/adamHead.gltf",
  240. handleNode: function (nodeInfo, actions) {
  241. if (nodeInfo.name && nodeInfo.mesh !== undefined) { // Node has a name and a mesh
  242. actions.createObject = {
  243. id: "adam." + nodeInfo.name
  244. };
  245. }
  246. return true;
  247. }
  248. });
  249.  
  250. // Highlight a couple of Objects by ID
  251. model.on("loaded", function () {
  252. model.objects["adam.node_mesh_Adam_mask_-4108.0"].highlighted = true; // ID contains name
  253. model.objects["adam.node_Object001_-4112.5"].highlighted = true;
  254. });
  255. ````
  256.  
  257. ### Transforming a GLTFModel
  258.  
  259. A GLTFModel lets us transform its Objects as a group:
  260.  
  261. ```` Javascript
  262. var model = new xeogl.GLTFModel({
  263. src: "models/carModel.gltf",
  264. position: [-35, 0, 0],
  265. rotation: [0, 45, 0],
  266. scale: [0.5, 0.5, 0.5]
  267. });
  268.  
  269. model.position = [-20, 0, 0];
  270. ````
  271.  
  272. ### Getting the World-space boundary of a GLTFModel
  273.  
  274. Get the World-space axis-aligned boundary like this:
  275.  
  276. ```` Javascript
  277. model.on("boundary", function() {
  278. var aabb = model.aabb; // [xmin, ymin,zmin,xmax,ymax, zmax]
  279. //...
  280. });
  281. ````
  282.  
  283. We can also subscribe to changes to that boundary, which will happen whenever
  284.  
  285. * the GLTFModel's {{#crossLink "Transform"}}{{/crossLink}} is updated,
  286. * components are added or removed, or
  287. * the GLTF model is reloaded from a different source,
  288. * its {{#crossLink "Geometry"}}Geometries{{/crossLink}} or {{#crossLink "Object"}}Objects{{/crossLink}} are updated.
  289.  
  290. ````javascript
  291. model.on("boundary", function() {
  292. var aabb = model.aabb; // [xmin, ymin,zmin,xmax,ymax, zmax]
  293. });
  294. ````
  295.  
  296. ### Clearing a GLTFModel
  297.  
  298. ```` Javascript
  299. model.clear();
  300. ````
  301.  
  302. ### Destroying a GLTFModel
  303.  
  304. ```` Javascript
  305. model.destroy();
  306. ````
  307.  
  308. @class GLTFModel
  309. @module xeogl
  310. @submodule models
  311. @constructor
  312. @param [scene] {Scene} Parent {{#crossLink "Scene"}}Scene{{/crossLink}} - creates this GLTFModel in the default
  313. {{#crossLink "Scene"}}Scene{{/crossLink}} when omitted.
  314. @param [cfg] {*} Configs
  315. @param [cfg.id] {String} Optional ID, unique among all components in the parent {{#crossLink "Scene"}}Scene{{/crossLink}},
  316. generated automatically when omitted.
  317. @param [cfg.entityType] {String} Optional entity classification when using within a semantic data model. See the {{#crossLink "Object"}}{{/crossLink}} documentation for usage.
  318. @param [cfg.meta] {String:Object} Optional map of user-defined metadata to attach to this GLTFModel.
  319. @param [cfg.parent] The parent Object.
  320. @param [cfg.visible=true] {Boolean} Indicates if this GLTFModel is visible.
  321. @param [cfg.culled=false] {Boolean} Indicates if this GLTFModel is culled from view.
  322. @param [cfg.pickable=true] {Boolean} Indicates if this GLTFModel is pickable.
  323. @param [cfg.clippable=true] {Boolean} Indicates if this GLTFModel is clippable.
  324. @param [cfg.outlined=false] {Boolean} Whether an outline is rendered around this GLTFModel.
  325. @param [cfg.ghosted=false] {Boolean} Whether this GLTFModel is rendered ghosted.
  326. @param [cfg.highlighted=false] {Boolean} Whether this GLTFModel is rendered highlighted.
  327. @param [cfg.selected=false] {Boolean} Whether this GLTFModel is rendered selected.
  328. @param [cfg.edges=false] {Boolean} Whether this GLTFModel is rendered with edges emphasized.
  329. @param [cfg.colorize=[1.0,1.0,1.0]] {Float32Array} RGB colorize color, multiplies by the rendered fragment colors.
  330. @param [cfg.opacity=1.0] {Number} Opacity factor, multiplies by the rendered fragment alpha.
  331. @param [cfg.position=[0,0,0]] {Float32Array} The GLTFModel's local 3D position.
  332. @param [cfg.scale=[1,1,1]] {Float32Array} The GLTFModel's local scale.
  333. @param [cfg.rotation=[0,0,0]] {Float32Array} The GLTFModel's local rotation, as Euler angles given in degrees, for each of the X, Y and Z axis.
  334. @param [cfg.matrix=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] {Float32Array} GLTFThe Model's local modelling transform matrix. Overrides the position, scale and rotation parameters.
  335. @param [cfg.src] {String} Path to a glTF file. You can set this to a new file path at any time, which will cause the
  336. @param [cfg.loaded=true] {Boolean} Indicates whether this GLTFModel is loaded or not. If initially set false, then the GLTFModel will load as soon as you set it true while {{#crossLink "GLTFModel/src:property"}}{{/crossLink}} is set to the location of a glTF file.
  337. @param [cfg.lambertMaterials=false] {Boolean} When true, gives each {{#crossLink "Mesh"}}{{/crossLink}} the same {{#crossLink "LambertMaterial"}}{{/crossLink}} and a {{#crossLink "Mesh/colorize:property"}}{{/crossLink}} value set the to diffuse color extracted from the glTF material. This is typically used for CAD models with huge amounts of objects, and will ignore textures.
  338. @param [cfg.quantizeGeometry=true] {Boolean} When true, quantizes geometry to reduce memory and GPU bus usage.
  339. @param [cfg.combineGeometry=true] {Boolean} When true, combines geometry vertex buffers to improve rendering performance.
  340. @param [cfg.backfaces=false] {Boolean} When true, allows visible backfaces, wherever specified in the glTF. When false, ignores backfaces.
  341. @param [cfg.edgeThreshold=20] {Number} When ghosting, highlighting, selecting or edging, this is the threshold angle between normals of adjacent triangles, below which their shared wireframe edge is not drawn.
  342. @param [cfg.handleNode] {Function} Optional callback to mask which {{#crossLink "Object"}}Objects{{/crossLink}} are loaded. Each Object will only be loaded when this callback returns ````true``` for its ID.
  343.  
  344. @extends Model
  345. */
  346. {
  347. xeogl.GLTFModel = class xeoglGLTFModel extends xeogl.Model {
  348.  
  349. init(cfg) {
  350.  
  351. super.init(cfg); // Call xeogl.Model._init()
  352.  
  353. this._src = null;
  354. this._options = {
  355. ignoreMaterials: !!cfg.ignoreMaterials,
  356. combineGeometry: cfg.combineGeometry !== false,
  357. quantizeGeometry: cfg.quantizeGeometry !== false,
  358. edgeThreshold: cfg.edgeThreshold || 20,
  359. lambertMaterials: !!cfg.lambertMaterials,
  360. handleNode: cfg.handleNode
  361. };
  362. this.loaded = cfg.loaded;
  363. this.src = cfg.src;
  364. }
  365.  
  366.  
  367. /**
  368. Array of all the root {{#crossLink "Object"}}Objects{{/crossLink}} in this GLTFModel.
  369.  
  370. @property children
  371. @final
  372. @type Array
  373. */
  374.  
  375. /**
  376. Map of all the root {{#crossLink "Object"}}Objects{{/crossLink}} in this GLTFModel, mapped to their IDs.
  377.  
  378. @property childMap
  379. @final
  380. @type {*}
  381. */
  382.  
  383. /**
  384. Indicates whether this GLTFModel is loaded or not.
  385.  
  386. @property loaded
  387. @default true
  388. @type Boolean
  389. */
  390. set loaded(value) {
  391. value = value !== false;
  392. if (this._loaded === value) {
  393. return;
  394. }
  395. this._loaded = value;
  396. this.clear();
  397. if (this._loaded) {
  398. if (this._src) {
  399. xeogl.GLTFModel.load(this, this._src, this._options);
  400. }
  401. }
  402. }
  403.  
  404. get loaded() {
  405. return this._loaded;
  406. }
  407.  
  408. /**
  409. Path to a glTF file.
  410.  
  411. You can set this to a new file path at any time (except while loading), which will cause the GLTFModel to load components from
  412. the new file (after first destroying any components loaded from a previous file path).
  413.  
  414. Fires a {{#crossLink "GLTFModel/loaded:event"}}{{/crossLink}} event when the glTF has loaded.
  415.  
  416. @property src
  417. @type String
  418. */
  419. set src(value) {
  420. if (!value) {
  421. this.clear();
  422. this._src = null;
  423. return;
  424. }
  425. if (!xeogl._isString(value)) {
  426. this.error("Value for 'src' should be a string");
  427. return;
  428. }
  429. if (value === this._src) { // Already loaded this GLTFModel
  430. /**
  431. Fired whenever this GLTFModel has finished loading components from the glTF file
  432. specified by {{#crossLink "GLTFModel/src:property"}}{{/crossLink}}.
  433. @event loaded
  434. */
  435. this.fire("loaded", true, true);
  436. return;
  437. }
  438. this.clear();
  439. this._src = value;
  440. if (this._loaded) {
  441. xeogl.GLTFModel.load(this, this._src, this._options);
  442. }
  443. }
  444.  
  445. get src() {
  446. return this._src;
  447. }
  448.  
  449. /**
  450. * Loads glTF from a URL into a {{#crossLink "Model"}}{{/crossLink}}.
  451. *
  452. * @method load
  453. * @static
  454. * @param {Model} model Model to load into.
  455. * @param {String} src Path to glTF file.
  456. * @param {Object} options Loading options.
  457. * @param {Function} [ok] Completion callback.
  458. * @param {Function} [error] Error callback.
  459. */
  460. static load(model, src, options, ok, error) {
  461. var spinner = model.scene.canvas.spinner;
  462. spinner.processes++;
  463. loadGLTF(model, src, options, function () {
  464. spinner.processes--;
  465. xeogl.scheduleTask(function () {
  466. model.fire("loaded", true, true);
  467. });
  468. if (ok) {
  469. ok();
  470. }
  471. },
  472. function (msg) {
  473. spinner.processes--;
  474. model.error(msg);
  475. if (error) {
  476. error(msg);
  477. }
  478. /**
  479. Fired whenever this GLTFModel fails to load the glTF file
  480. specified by {{#crossLink "GLTFModel/src:property"}}{{/crossLink}}.
  481. @event error
  482. @param msg {String} Description of the error
  483. */
  484. model.fire("error", msg);
  485. });
  486. }
  487.  
  488. /**
  489. * Parses glTF JSON into a {{#crossLink "Model"}}{{/crossLink}}.
  490. *
  491. * @method parse
  492. * @static
  493. * @param {Model} model Model to parse into.
  494. * @param {Object} gltf The glTF JSON.
  495. * @param {Object} [options] Parsing options
  496. * @param {String} [options.basePath] Base path path to find external resources on, if any.
  497. * @param {String} [options.loadBuffer] Callback to load buffer files.
  498. */
  499. static parse(model, gltf, options, ok, error) {
  500. options = options || {};
  501. var spinner = model.scene.canvas.spinner;
  502. spinner.processes++;
  503. parseGLTF(gltf, "", options, model, function () {
  504. spinner.processes--;
  505. model.fire("loaded", true, true);
  506. if (ok) {
  507. ok();
  508. }
  509. },
  510. function (msg) {
  511. spinner.processes--;
  512. model.error(msg);
  513. model.fire("error", msg);
  514. if (error) {
  515. error(msg);
  516. }
  517. });
  518. }
  519. };
  520.  
  521. //--------------------------------------------------------------------------------------------
  522. // Loads glTF V2.0
  523. //--------------------------------------------------------------------------------------------
  524.  
  525. var loadGLTF = (function () {
  526.  
  527. return function (model, src, options, ok, error) {
  528.  
  529. loadJSON(src, function (response) { // OK
  530. var json;
  531. try {
  532. json = JSON.parse(response);
  533. } catch (e) {
  534. error(e);
  535. }
  536. options.basePath = getBasePath(src);
  537. parseGLTF(json, src, options, model, ok, error);
  538. },
  539. error);
  540. };
  541.  
  542. function loadJSON(url, ok, err) {
  543. var request = new XMLHttpRequest();
  544. request.overrideMimeType("application/json");
  545. request.open('GET', url, true);
  546. request.addEventListener('load', function (event) {
  547. var response = event.target.response;
  548. if (this.status === 200) {
  549. if (ok) {
  550. ok(response);
  551. }
  552. } else if (this.status === 0) {
  553. // Some browsers return HTTP Status 0 when using non-http protocol
  554. // e.g. 'file://' or 'data://'. Handle as success.
  555. console.warn('loadFile: HTTP Status 0 received.');
  556. if (ok) {
  557. ok(response);
  558. }
  559. } else {
  560. if (err) {
  561. err(event);
  562. }
  563. }
  564. }, false);
  565.  
  566. request.addEventListener('error', function (event) {
  567. if (err) {
  568. err(event);
  569. }
  570. }, false);
  571. request.send(null);
  572. }
  573.  
  574. function getBasePath(src) {
  575. var i = src.lastIndexOf("/");
  576. return (i !== 0) ? src.substring(0, i + 1) : "";
  577. }
  578. })();
  579.  
  580. var parseGLTF = (function () {
  581.  
  582. const WebGLConstants = {
  583. 34963: 'ELEMENT_ARRAY_BUFFER', //0x8893
  584. 34962: 'ARRAY_BUFFER', //0x8892
  585. 5123: 'UNSIGNED_SHORT', //0x1403
  586. 5126: 'FLOAT', //0x1406
  587. 4: 'TRIANGLES', //0x0004
  588. 35678: 'SAMPLER_2D', //0x8B5E
  589. 35664: 'FLOAT_VEC2', //0x8B50
  590. 35665: 'FLOAT_VEC3', //0x8B51
  591. 35666: 'FLOAT_VEC4', //0x8B52
  592. 35676: 'FLOAT_MAT4' //0x8B5C
  593. };
  594.  
  595. const WEBGL_COMPONENT_TYPES = {
  596. 5120: Int8Array,
  597. 5121: Uint8Array,
  598. 5122: Int16Array,
  599. 5123: Uint16Array,
  600. 5125: Uint32Array,
  601. 5126: Float32Array
  602. };
  603.  
  604. const WEBGL_TYPE_SIZES = {
  605. 'SCALAR': 1,
  606. 'VEC2': 2,
  607. 'VEC3': 3,
  608. 'VEC4': 4,
  609. 'MAT2': 4,
  610. 'MAT3': 9,
  611. 'MAT4': 16
  612. };
  613.  
  614. return function (json, src, options, model, ok) {
  615.  
  616. model.clear();
  617.  
  618. var ctx = {
  619. src: src,
  620. loadBuffer: options.loadBuffer,
  621. basePath: options.basePath,
  622. handleNode: options.handleNode,
  623. ignoreMaterials: !!options.ignoreMaterials,
  624. combineGeometry: options.combineGeometry,
  625. quantizeGeometry: options.quantizeGeometry,
  626. edgeThreshold: options.edgeThreshold,
  627. lambertMaterials: !!options.lambertMaterials,
  628. json: json,
  629. scene: model.scene,
  630. model: model,
  631. modelProps: {
  632. visible: model.visible,
  633. culled: model.culled,
  634. ghosted: model.ghosted,
  635. highlighted: model.highlighted,
  636. selected: model.selected,
  637. outlined: model.outlined,
  638. clippable: model.clippable,
  639. pickable: model.pickable,
  640. collidable: model.collidable,
  641. castShadow: model.castShadow,
  642. receiveShadow: model.receiveShadow,
  643. colorize: model.colorize,
  644. opacity: model.opacity,
  645. edges: model.edges
  646. },
  647. numObjects: 0
  648. };
  649.  
  650. model.scene.loading++; // Disables (re)compilation
  651.  
  652. loadBuffers(ctx, function () {
  653.  
  654. loadBufferViews(ctx);
  655. loadAccessors(ctx);
  656. if (!ctx.lambertMaterials) {
  657. loadTextures(ctx);
  658. }
  659. if (!ctx.ignoreMaterials) {
  660. loadMaterials(ctx);
  661. }
  662. loadMeshes(ctx);
  663. loadDefaultScene(ctx);
  664.  
  665. model.scene.loading--; // Re-enables (re)compilation
  666.  
  667. ok();
  668. });
  669. };
  670.  
  671. function loadBuffers(ctx, ok) {
  672. var buffers = ctx.json.buffers;
  673. if (buffers) {
  674. var numToLoad = buffers.length;
  675. for (var i = 0, len = buffers.length; i < len; i++) {
  676. loadBuffer(ctx, buffers[i], function () {
  677. if (--numToLoad === 0) {
  678. ok();
  679. }
  680. }, function (msg) {
  681. ctx.model.error(msg);
  682. if (--numToLoad === 0) {
  683. ok();
  684. }
  685. });
  686. }
  687. } else {
  688. ok();
  689. }
  690. }
  691.  
  692. function loadBuffer(ctx, bufferInfo, ok, err) {
  693. var uri = bufferInfo.uri;
  694. if (uri) {
  695. loadArrayBuffer(ctx, uri, function (data) {
  696. bufferInfo._buffer = data;
  697. ok();
  698. },
  699. err);
  700. }
  701. else {
  702. err('gltf/handleBuffer missing uri in ' + JSON.stringify(bufferInfo));
  703. }
  704. }
  705.  
  706. function loadArrayBuffer(ctx, url, ok, err) {
  707.  
  708. // Check for data: URI
  709.  
  710. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  711. var dataUriRegexResult = url.match(dataUriRegex);
  712.  
  713. if (dataUriRegexResult) { // Safari can't handle data URIs through XMLHttpRequest
  714.  
  715. var mimeType = dataUriRegexResult[1];
  716. var isBase64 = !!dataUriRegexResult[2];
  717. var data = dataUriRegexResult[3];
  718.  
  719. data = window.decodeURIComponent(data);
  720.  
  721. if (isBase64) {
  722. data = window.atob(data);
  723. }
  724.  
  725. try {
  726. var buffer = new ArrayBuffer(data.length);
  727. var view = new Uint8Array(buffer);
  728. for (var i = 0; i < data.length; i++) {
  729. view[i] = data.charCodeAt(i);
  730. }
  731. window.setTimeout(function () {
  732. ok(buffer);
  733. }, 0);
  734. } catch (error) {
  735. window.setTimeout(function () {
  736. err(error);
  737. }, 0);
  738. }
  739. } else {
  740.  
  741. if (ctx.loadBuffer) {
  742. ctx.loadBuffer(url, ok, err);
  743.  
  744. } else {
  745.  
  746. var request = new XMLHttpRequest();
  747. request.open('GET', ctx.basePath + url, true);
  748. request.responseType = 'arraybuffer';
  749. request.onreadystatechange = function () {
  750. if (request.readyState == 4) {
  751. if (request.status == "200") {
  752. ok(request.response);
  753. } else {
  754. err('loadArrayBuffer error : ' + request.response);
  755. }
  756. }
  757. };
  758. request.send(null);
  759. }
  760. }
  761. }
  762.  
  763. function loadBufferViews(ctx) {
  764. var bufferViewsInfo = ctx.json.bufferViews;
  765. if (bufferViewsInfo) {
  766. for (var i = 0, len = bufferViewsInfo.length; i < len; i++) {
  767. loadBufferView(ctx, bufferViewsInfo[i]);
  768. }
  769. }
  770. }
  771.  
  772. function loadBufferView(ctx, bufferViewInfo) {
  773.  
  774. var buffer = ctx.json.buffers[bufferViewInfo.buffer];
  775.  
  776. bufferViewInfo._typedArray = null;
  777.  
  778. var byteLength = bufferViewInfo.byteLength || 0;
  779. var byteOffset = bufferViewInfo.byteOffset || 0;
  780.  
  781. bufferViewInfo._buffer = buffer._buffer.slice(byteOffset, byteOffset + byteLength);
  782.  
  783. if (bufferViewInfo.target === 34963) {
  784. bufferViewInfo._typedArray = new Uint16Array(bufferViewInfo._buffer);
  785.  
  786. } else if (bufferViewInfo.target == 34962) {
  787. bufferViewInfo._typedArray = new Float32Array(bufferViewInfo._buffer);
  788.  
  789. } else {
  790. //ctx.model.log(bufferViewInfo._typedArray)
  791. }
  792. }
  793.  
  794. function loadAccessors(ctx) {
  795. var accessorsInfo = ctx.json.accessors;
  796. if (accessorsInfo) {
  797. for (var i = 0, len = accessorsInfo.length; i < len; i++) {
  798. loadAccessor(ctx, accessorsInfo[i]);
  799. }
  800. }
  801. }
  802.  
  803. function loadAccessor(ctx, accessorInfo) {
  804. var arraybuffer = ctx.json.bufferViews[accessorInfo.bufferView];
  805. var itemSize = WEBGL_TYPE_SIZES[accessorInfo.type];
  806. var TypedArray = WEBGL_COMPONENT_TYPES[accessorInfo.componentType];
  807.  
  808. // For VEC3: itemSize is 3, elementBytes is 4, itemBytes is 12.
  809. var elementBytes = TypedArray.BYTES_PER_ELEMENT;
  810. var itemBytes = elementBytes * itemSize;
  811.  
  812. // The buffer is not interleaved if the stride is the item size in bytes.
  813. if (accessorInfo.byteStride && accessorInfo.byteStride !== itemBytes) {
  814.  
  815. //TODO
  816.  
  817. // alert("interleaved buffer!");
  818.  
  819. } else {
  820. accessorInfo._typedArray = new TypedArray(arraybuffer._buffer, accessorInfo.byteOffset || 0, accessorInfo.count * itemSize);
  821. accessorInfo._itemSize = itemSize;
  822. }
  823. }
  824.  
  825.  
  826. function loadTextures(ctx) {
  827. var texturesInfo = ctx.json.textures;
  828. if (texturesInfo) {
  829. for (var i = 0, len = texturesInfo.length; i < len; i++) {
  830. loadTexture(ctx, texturesInfo[i]);
  831. }
  832. }
  833. }
  834.  
  835. function loadTexture(ctx, textureInfo) {
  836. var texture = new xeogl.Texture(ctx.scene, {
  837. src: ctx.json.images[textureInfo.source].uri ? ctx.basePath + ctx.json.images[textureInfo.source].uri : undefined,
  838. flipY: !!textureInfo.flipY
  839. });
  840. ctx.model._addComponent(texture);
  841. textureInfo._texture = texture;
  842. }
  843.  
  844. function loadMaterials(ctx) {
  845. var materialsInfo = ctx.json.materials;
  846. if (materialsInfo) {
  847. var materialInfo;
  848. var material;
  849. for (var i = 0, len = materialsInfo.length; i < len; i++) {
  850. materialInfo = materialsInfo[i];
  851. if (ctx.lambertMaterials) {
  852. // Substitute RGBA for material, to use fast flat shading instead
  853. material = loadMaterialColorize(ctx, materialInfo);
  854. } else {
  855. material = loadMaterial(ctx, materialInfo);
  856. ctx.model._addComponent(material);
  857. }
  858. materialInfo._material = material;
  859. }
  860. }
  861. }
  862.  
  863. function loadMaterial(ctx, materialInfo) {
  864.  
  865. var json = ctx.json;
  866. var cfg = {};
  867. var textureInfo;
  868.  
  869. // Common attributes
  870.  
  871. var normalTexture = materialInfo.normalTexture;
  872. if (normalTexture) {
  873. textureInfo = json.textures[normalTexture.index];
  874. if (textureInfo) {
  875. cfg.normalMap = textureInfo._texture;
  876. cfg.normalMap.encoding = "linear";
  877. }
  878. }
  879.  
  880. var occlusionTexture = materialInfo.occlusionTexture;
  881. if (occlusionTexture) {
  882. textureInfo = json.textures[occlusionTexture.index];
  883. if (textureInfo) {
  884. cfg.occlusionMap = textureInfo._texture;
  885. }
  886. }
  887.  
  888. var emissiveTexture = materialInfo.emissiveTexture;
  889. if (emissiveTexture) {
  890. textureInfo = json.textures[emissiveTexture.index];
  891. if (textureInfo) {
  892. cfg.emissiveMap = textureInfo._texture;
  893. cfg.emissiveMap.encoding = "sRGB";
  894. }
  895. }
  896.  
  897. var emissiveFactor = materialInfo.emissiveFactor;
  898. if (emissiveFactor) {
  899. cfg.emissive = emissiveFactor;
  900. }
  901.  
  902. cfg.backfaces = !!materialInfo.doubleSided;
  903.  
  904. var alphaMode = materialInfo.alphaMode;
  905. switch (alphaMode) {
  906. case "OPAQUE":
  907. cfg.alphaMode = "opaque";
  908. break;
  909. case "MASK":
  910. cfg.alphaMode = "mask";
  911. break;
  912. case "BLEND":
  913. cfg.alphaMode = "blend";
  914. break;
  915. default:
  916. }
  917.  
  918. var alphaCutoff = materialInfo.alphaCutoff;
  919. if (alphaCutoff !== undefined) {
  920. cfg.alphaCutoff = alphaCutoff;
  921. }
  922.  
  923. var extensions = materialInfo.extensions;
  924. if (extensions) {
  925.  
  926. // Specular PBR material
  927.  
  928. var specularPBR = extensions["KHR_materials_pbrSpecularGlossiness"];
  929. if (specularPBR) {
  930.  
  931. var diffuseFactor = specularPBR.diffuseFactor;
  932. if (diffuseFactor !== null && diffuseFactor !== undefined) {
  933. cfg.diffuse = diffuseFactor.slice(0, 3);
  934. cfg.alpha = diffuseFactor[3];
  935. }
  936.  
  937. var diffuseTexture = specularPBR.diffuseTexture;
  938. if (diffuseTexture) {
  939. textureInfo = json.textures[diffuseTexture.index];
  940. if (textureInfo) {
  941. cfg.diffuseMap = textureInfo._texture;
  942. cfg.diffuseMap.encoding = "sRGB";
  943. }
  944. }
  945.  
  946. var specularFactor = specularPBR.specularFactor;
  947. if (specularFactor !== null && specularFactor !== undefined) {
  948. cfg.specular = specularFactor.slice(0, 3);
  949. }
  950.  
  951. var glossinessFactor = specularPBR.glossinessFactor;
  952. if (glossinessFactor !== null && glossinessFactor !== undefined) {
  953. cfg.glossiness = glossinessFactor;
  954. }
  955.  
  956. var specularGlossinessTexture = specularPBR.specularGlossinessTexture;
  957. if (specularGlossinessTexture) {
  958. textureInfo = json.textures[specularGlossinessTexture.index];
  959. if (textureInfo) {
  960. cfg.specularGlossinessMap = textureInfo._texture;
  961. cfg.specularGlossinessMap.encoding = "linear";
  962. }
  963. }
  964.  
  965. return new xeogl.SpecularMaterial(ctx.scene, cfg);
  966. }
  967.  
  968. // Common Phong, Blinn, Lambert or Constant materials
  969.  
  970. var common = extensions["KHR_materials_common"];
  971. if (common) {
  972.  
  973. var technique = common.technique;
  974. var values = common.values || {};
  975.  
  976. var blinn = technique === "BLINN";
  977. var phong = technique === "PHONG";
  978. var lambert = technique === "LAMBERT";
  979. var constant = technique === "CONSTANT";
  980.  
  981. var shininess = values.shininess;
  982. if ((blinn || phong) && shininess !== null && shininess !== undefined) {
  983. cfg.shininess = shininess;
  984. } else {
  985. cfg.shininess = 0;
  986. }
  987. var texture;
  988. var diffuse = values.diffuse;
  989. if (diffuse && (blinn || phong || lambert)) {
  990. if (xeogl._isString(diffuse)) {
  991. texture = ctx.textures[diffuse];
  992. if (texture) {
  993. cfg.diffuseMap = texture;
  994. cfg.diffuseMap.encoding = "sRGB";
  995. }
  996. } else {
  997. cfg.diffuse = diffuse.slice(0, 3);
  998. }
  999. } else {
  1000. cfg.diffuse = [0, 0, 0];
  1001. }
  1002.  
  1003. var specular = values.specular;
  1004. if (specular && (blinn || phong)) {
  1005. if (xeogl._isString(specular)) {
  1006. texture = ctx.textures[specular];
  1007. if (texture) {
  1008. cfg.specularMap = texture;
  1009. }
  1010. } else {
  1011. cfg.specular = specular.slice(0, 3);
  1012. }
  1013. } else {
  1014. cfg.specular = [0, 0, 0];
  1015. }
  1016.  
  1017. var emission = values.emission;
  1018. if (emission) {
  1019. if (xeogl._isString(emission)) {
  1020. texture = ctx.textures[emission];
  1021. if (texture) {
  1022. cfg.emissiveMap = texture;
  1023. }
  1024. } else {
  1025. cfg.emissive = emission.slice(0, 3);
  1026. }
  1027. } else {
  1028. cfg.emissive = [0, 0, 0];
  1029. }
  1030.  
  1031. var transparency = values.transparency;
  1032. if (transparency !== null && transparency !== undefined) {
  1033. cfg.alpha = transparency;
  1034. } else {
  1035. cfg.alpha = 1.0;
  1036. }
  1037.  
  1038. var transparent = values.transparent;
  1039. if (transparent !== null && transparent !== undefined) {
  1040. //cfg.transparent = transparent;
  1041. } else {
  1042. //cfg.transparent = 1.0;
  1043. }
  1044.  
  1045. return new xeogl.PhongMaterial(ctx.scene, cfg);
  1046. }
  1047. }
  1048.  
  1049. // Metallic PBR naterial
  1050.  
  1051. var metallicPBR = materialInfo.pbrMetallicRoughness;
  1052. if (metallicPBR) {
  1053.  
  1054. var baseColorFactor = metallicPBR.baseColorFactor;
  1055. if (baseColorFactor) {
  1056. cfg.baseColor = baseColorFactor.slice(0, 3);
  1057. cfg.alpha = baseColorFactor[3];
  1058. }
  1059.  
  1060. var baseColorTexture = metallicPBR.baseColorTexture;
  1061. if (baseColorTexture) {
  1062. textureInfo = json.textures[baseColorTexture.index];
  1063. if (textureInfo) {
  1064. cfg.baseColorMap = textureInfo._texture;
  1065. cfg.baseColorMap.encoding = "sRGB";
  1066. }
  1067. }
  1068.  
  1069. var metallicFactor = metallicPBR.metallicFactor;
  1070. if (metallicFactor !== null && metallicFactor !== undefined) {
  1071. cfg.metallic = metallicFactor;
  1072. }
  1073.  
  1074. var roughnessFactor = metallicPBR.roughnessFactor;
  1075. if (roughnessFactor !== null && roughnessFactor !== undefined) {
  1076. cfg.roughness = roughnessFactor;
  1077. }
  1078.  
  1079. var metallicRoughnessTexture = metallicPBR.metallicRoughnessTexture;
  1080. if (metallicRoughnessTexture) {
  1081. textureInfo = json.textures[metallicRoughnessTexture.index];
  1082. if (textureInfo) {
  1083. cfg.metallicRoughnessMap = textureInfo._texture;
  1084. cfg.metallicRoughnessMap.encoding = "linear";
  1085. }
  1086. }
  1087.  
  1088. return new xeogl.MetallicMaterial(ctx.scene, cfg);
  1089. }
  1090.  
  1091. // Default material
  1092.  
  1093. return new xeogl.PhongMaterial(ctx.scene, cfg);
  1094. }
  1095.  
  1096. // Extract diffuse/baseColor and alpha into RGBA Mesh 'colorize' property
  1097. function loadMaterialColorize(ctx, materialInfo) {
  1098.  
  1099. var json = ctx.json;
  1100. var colorize = new Float32Array([1, 1, 1, 1]);
  1101.  
  1102. var extensions = materialInfo.extensions;
  1103. if (extensions) {
  1104.  
  1105. // Specular PBR material
  1106.  
  1107. var specularPBR = extensions["KHR_materials_pbrSpecularGlossiness"];
  1108. if (specularPBR) {
  1109. var diffuseFactor = specularPBR.diffuseFactor;
  1110. if (diffuseFactor !== null && diffuseFactor !== undefined) {
  1111. colorize.set(diffuseFactor);
  1112. }
  1113. }
  1114.  
  1115. // Common Phong, Blinn, Lambert or Constant materials
  1116.  
  1117. var common = extensions["KHR_materials_common"];
  1118. if (common) {
  1119.  
  1120. var technique = common.technique;
  1121. var values = common.values || {};
  1122.  
  1123. var blinn = technique === "BLINN";
  1124. var phong = technique === "PHONG";
  1125. var lambert = technique === "LAMBERT";
  1126. var constant = technique === "CONSTANT";
  1127.  
  1128. var diffuse = values.diffuse;
  1129. if (diffuse && (blinn || phong || lambert)) {
  1130. if (!xeogl._isString(diffuse)) {
  1131. colorize.set(diffuse);
  1132. }
  1133. }
  1134.  
  1135. var transparency = values.transparency;
  1136. if (transparency !== null && transparency !== undefined) {
  1137. colorize[3] = transparency;
  1138. }
  1139.  
  1140. var transparent = values.transparent;
  1141. if (transparent !== null && transparent !== undefined) {
  1142. colorize[3] = transparent;
  1143. }
  1144. }
  1145. }
  1146.  
  1147. // Metallic PBR naterial
  1148.  
  1149. var metallicPBR = materialInfo.pbrMetallicRoughness;
  1150. if (metallicPBR) {
  1151. var baseColorFactor = metallicPBR.baseColorFactor;
  1152. if (baseColorFactor) {
  1153. colorize.set(baseColorFactor);
  1154. }
  1155. }
  1156.  
  1157. return colorize;
  1158. }
  1159.  
  1160. function loadMeshes(ctx) {
  1161. var meshes = ctx.json.meshes;
  1162. if (meshes) {
  1163. for (var i = 0, len = meshes.length; i < len; i++) {
  1164. loadMesh(ctx, meshes[i]);
  1165. }
  1166. }
  1167. }
  1168.  
  1169. function loadMesh(ctx, meshInfo) {
  1170. var json = ctx.json;
  1171. var mesh = [];
  1172. var primitivesInfo = meshInfo.primitives;
  1173. var materialIndex;
  1174. var materialInfo;
  1175. var accessorInfo;
  1176. var bufferViewInfo;
  1177. var attributes;
  1178.  
  1179. if (primitivesInfo) {
  1180.  
  1181. var primitiveInfo;
  1182. var indicesIndex;
  1183. var positionsIndex;
  1184. var normalsIndex;
  1185. var uv0Index;
  1186. var geometryCfg;
  1187. var meshCfg;
  1188. var geometry;
  1189.  
  1190. for (var i = 0, len = primitivesInfo.length; i < len; i++) {
  1191.  
  1192. geometryCfg = {
  1193. primitive: "triangles",
  1194. combined: ctx.combineGeometry,
  1195. quantized: ctx.quantizeGeometry,
  1196. edgeThreshold: ctx.edgeThreshold
  1197. };
  1198.  
  1199. primitiveInfo = primitivesInfo[i];
  1200. indicesIndex = primitiveInfo.indices;
  1201.  
  1202. if (indicesIndex !== null && indicesIndex !== undefined) {
  1203. accessorInfo = json.accessors[indicesIndex];
  1204. bufferViewInfo = json.bufferViews[accessorInfo.bufferView];
  1205. geometryCfg.indices = accessorInfo._typedArray;
  1206. }
  1207.  
  1208. attributes = primitiveInfo.attributes;
  1209. if (!attributes) {
  1210. continue;
  1211. }
  1212.  
  1213. positionsIndex = attributes.POSITION;
  1214.  
  1215. if (positionsIndex !== null && positionsIndex !== undefined) {
  1216. accessorInfo = json.accessors[positionsIndex];
  1217. bufferViewInfo = json.bufferViews[accessorInfo.bufferView];
  1218. geometryCfg.positions = accessorInfo._typedArray;
  1219. }
  1220.  
  1221. normalsIndex = attributes.NORMAL;
  1222.  
  1223. if (normalsIndex !== null && normalsIndex !== undefined) {
  1224. accessorInfo = json.accessors[normalsIndex];
  1225. bufferViewInfo = json.bufferViews[accessorInfo.bufferView];
  1226. geometryCfg.normals = accessorInfo._typedArray;
  1227. }
  1228.  
  1229. uv0Index = attributes.TEXCOORD_0;
  1230.  
  1231. if (uv0Index !== null && uv0Index !== undefined) {
  1232. accessorInfo = json.accessors[uv0Index];
  1233. bufferViewInfo = json.bufferViews[accessorInfo.bufferView];
  1234. geometryCfg.uv = accessorInfo._typedArray;
  1235. }
  1236.  
  1237. meshCfg = {};
  1238.  
  1239. geometry = new xeogl.Geometry(ctx.scene, geometryCfg);
  1240.  
  1241. ctx.model._addComponent(geometry);
  1242. meshCfg.geometry = geometry;
  1243.  
  1244. materialIndex = primitiveInfo.material;
  1245. if (materialIndex !== null && materialIndex !== undefined) {
  1246. materialInfo = json.materials[materialIndex];
  1247. if (materialInfo) {
  1248. meshCfg.material = materialInfo._material;
  1249. }
  1250. }
  1251.  
  1252. mesh.push(meshCfg);
  1253. }
  1254. }
  1255. meshInfo._mesh = mesh;
  1256. }
  1257.  
  1258. function loadDefaultScene(ctx) {
  1259. var json = ctx.json;
  1260. var scene = json.scene || 0;
  1261. var defaultSceneInfo = json.scenes[scene];
  1262. if (!defaultSceneInfo) {
  1263. error(ctx, "glTF has no default scene");
  1264. return;
  1265. }
  1266. loadScene(ctx, defaultSceneInfo);
  1267. }
  1268.  
  1269. function loadScene(ctx, sceneInfo) {
  1270. var nodes = sceneInfo.nodes;
  1271. if (!nodes) {
  1272. return;
  1273. }
  1274. var json = ctx.json;
  1275. var nodeInfo;
  1276. for (var i = 0, len = nodes.length; i < len; i++) {
  1277. nodeInfo = json.nodes[nodes[i]];
  1278. if (!nodeInfo) {
  1279. error(ctx, "Node not found: " + i);
  1280. continue;
  1281. }
  1282. loadNode(ctx, i, nodeInfo, null, null);
  1283. }
  1284. }
  1285.  
  1286. function loadNode(ctx, nodeIdx, nodeInfo, matrix, parent, parentCfg) {
  1287.  
  1288. parent = parent || ctx.model;
  1289. var createObject;
  1290.  
  1291. if (ctx.handleNode) {
  1292. var actions = {};
  1293. if (!ctx.handleNode(nodeInfo, actions)) {
  1294. return;
  1295. }
  1296. if (actions.createObject) {
  1297. createObject = actions.createObject;
  1298. }
  1299. // if (actions.createMesh) {
  1300. // createMesh = actions.createMesh;
  1301. // }
  1302. }
  1303.  
  1304. var json = ctx.json;
  1305. var model = ctx.model;
  1306. var math = xeogl.math;
  1307. var localMatrix;
  1308. var hasChildNodes = nodeInfo.children && nodeInfo.children.length > 0;
  1309. var group;
  1310.  
  1311. if (nodeInfo.matrix) {
  1312. localMatrix = nodeInfo.matrix;
  1313. if (matrix) {
  1314. matrix = math.mulMat4(matrix, localMatrix, math.mat4());
  1315. } else {
  1316. matrix = localMatrix;
  1317. }
  1318. }
  1319.  
  1320. if (nodeInfo.translation) {
  1321. localMatrix = math.translationMat4v(nodeInfo.translation);
  1322. if (matrix) {
  1323. matrix = math.mulMat4(matrix, localMatrix, localMatrix);
  1324. } else {
  1325. matrix = localMatrix;
  1326. }
  1327. }
  1328.  
  1329. if (nodeInfo.rotation) {
  1330. localMatrix = math.quaternionToMat4(nodeInfo.rotation);
  1331. if (matrix) {
  1332. matrix = math.mulMat4(matrix, localMatrix, localMatrix);
  1333. } else {
  1334. matrix = localMatrix;
  1335. }
  1336. }
  1337.  
  1338. if (nodeInfo.scale) {
  1339. localMatrix = math.scalingMat4v(nodeInfo.scale);
  1340. if (matrix) {
  1341. matrix = math.mulMat4(matrix, localMatrix, localMatrix);
  1342. } else {
  1343. matrix = localMatrix;
  1344. }
  1345. }
  1346.  
  1347. ctx.numObjects++;
  1348.  
  1349. if (nodeInfo.mesh !== undefined) {
  1350.  
  1351. var meshInfo = json.meshes[nodeInfo.mesh];
  1352.  
  1353. if (meshInfo) {
  1354.  
  1355. var meshesInfo = meshInfo._mesh;
  1356. var meshesInfoMesh;
  1357. var mesh;
  1358. var numMeshes = meshesInfo.length;
  1359.  
  1360. if (!createObject && numMeshes > 0 && !hasChildNodes) {
  1361.  
  1362. // Case 1: Not creating object, node has meshes, node has no child nodes
  1363.  
  1364. for (var i = 0, len = numMeshes; i < len; i++) {
  1365. meshesInfoMesh = meshesInfo[i];
  1366. var meshCfg = {
  1367. geometry: meshesInfoMesh.geometry,
  1368. matrix: matrix
  1369. };
  1370. xeogl._apply(ctx.modelProps, meshCfg);
  1371. if (ctx.lambertMaterials) {
  1372. if (!model.material) {
  1373. model.material = new xeogl.LambertMaterial(ctx.scene, {
  1374. backfaces: true
  1375. });
  1376. }
  1377. meshCfg.material = model.material;
  1378. meshCfg.colorize = meshesInfoMesh.material;
  1379. meshCfg.opacity = meshesInfoMesh.material[3];
  1380. } else {
  1381. meshCfg.material = meshesInfoMesh.material;
  1382. }
  1383. mesh = new xeogl.Mesh(ctx.scene, meshCfg);
  1384. parent.addChild(mesh, false); // Don't automatically inherit properties
  1385. model._addComponent(mesh);
  1386. }
  1387. return;
  1388. }
  1389.  
  1390. if (createObject && numMeshes === 1 && !hasChildNodes) {
  1391.  
  1392. // Case 2: Creating object, node has one mesh, node has no child nodes
  1393.  
  1394. meshesInfoMesh = meshesInfo[0];
  1395. var meshCfg = {
  1396. geometry: meshesInfoMesh.geometry,
  1397. matrix: matrix
  1398. };
  1399. xeogl._apply(ctx.modelProps, meshCfg);
  1400. if (ctx.lambertMaterials) {
  1401. if (!model.material) {
  1402. model.material = new xeogl.LambertMaterial(ctx.scene, {
  1403. backfaces: true
  1404. });
  1405. }
  1406. meshCfg.material = model.material;
  1407. meshCfg.colorize = meshesInfoMesh.material; // [R,G,B,A]
  1408. meshCfg.opacity = meshesInfoMesh.material[3];
  1409. } else {
  1410. meshCfg.material = meshesInfoMesh.material;
  1411. }
  1412. xeogl._apply(createObject, meshCfg);
  1413. mesh = new xeogl.Mesh(ctx.scene, meshCfg);
  1414. parent.addChild(mesh, false); // Don't automatically inherit properties
  1415. model._addComponent(mesh);
  1416. return;
  1417. }
  1418.  
  1419. if (createObject && numMeshes > 0 && !hasChildNodes) {
  1420.  
  1421. // Case 3: Creating object, node has meshes, node has no child nodes
  1422.  
  1423. var groupCfg = {
  1424. matrix: matrix
  1425. };
  1426. xeogl._apply(ctx.modelProps, groupCfg);
  1427. xeogl._apply(createObject, groupCfg);
  1428. var group = new xeogl.Group(ctx.scene, groupCfg);
  1429. parent.addChild(group, false);
  1430. model._addComponent(group);
  1431. for (var i = 0, len = numMeshes; i < len; i++) {
  1432. meshesInfoMesh = meshesInfo[i];
  1433. var meshCfg = {
  1434. geometry: meshesInfoMesh.geometry
  1435. };
  1436. xeogl._apply(ctx.modelProps, meshCfg);
  1437. if (ctx.lambertMaterials) {
  1438. if (!model.material) {
  1439. model.material = new xeogl.LambertMaterial(ctx.scene, {
  1440. backfaces: true
  1441. });
  1442. }
  1443. meshCfg.material = model.material;
  1444. meshCfg.colorize = meshesInfoMesh.material;
  1445. meshCfg.opacity = meshesInfoMesh.material[3];
  1446. } else {
  1447. meshCfg.material = meshesInfoMesh.material;
  1448. }
  1449. xeogl._apply(createObject, meshCfg);
  1450. meshCfg.id = createObject.id + "." + i;
  1451. meshCfg.entityType = null;
  1452. mesh = new xeogl.Mesh(ctx.scene, meshCfg);
  1453. group.addChild(mesh, false);
  1454. model._addComponent(mesh);
  1455. }
  1456. return;
  1457. }
  1458.  
  1459. if (!createObject && numMeshes > 0 && hasChildNodes) {
  1460.  
  1461. // Case 4: Not creating object, node has meshes, node has child nodes
  1462.  
  1463. var groupCfg = {
  1464. matrix: matrix
  1465. };
  1466. xeogl._apply(ctx.modelProps, groupCfg);
  1467. var group = new xeogl.Group(ctx.scene, groupCfg);
  1468. parent.addChild(group, false);
  1469. model._addComponent(group);
  1470. for (var i = 0, len = numMeshes; i < len; i++) {
  1471. meshesInfoMesh = meshesInfo[i];
  1472. var meshCfg = {
  1473. geometry: meshesInfoMesh.geometry
  1474. };
  1475. xeogl._apply(groupCfg, meshCfg);
  1476. meshCfg.entityType = null;
  1477. meshCfg.matrix = null; // Group has matrix
  1478. if (ctx.lambertMaterials) {
  1479. if (!model.material) {
  1480. model.material = new xeogl.LambertMaterial(ctx.scene, {
  1481. backfaces: true
  1482. });
  1483. }
  1484. meshCfg.material = model.material;
  1485. meshCfg.colorize = meshesInfoMesh.material;
  1486. meshCfg.opacity = meshesInfoMesh.material[3];
  1487. } else {
  1488. meshCfg.material = meshesInfoMesh.material;
  1489. }
  1490. mesh = new xeogl.Mesh(ctx.scene, meshCfg);
  1491. group.addChild(mesh, false);
  1492. model._addComponent(mesh);
  1493. }
  1494. matrix = null;
  1495. parent = group;
  1496. parentCfg = groupCfg;
  1497. }
  1498.  
  1499. if (createObject && numMeshes === 0 && hasChildNodes) {
  1500.  
  1501. // Case 5: Creating explicit object, node has meshes OR node has child nodes
  1502.  
  1503. var groupCfg = {
  1504. matrix: matrix
  1505. };
  1506. xeogl._apply(ctx.modelProps, groupCfg);
  1507. xeogl._apply(createObject, groupCfg);
  1508. createObject.matrix = matrix;
  1509. var group = new xeogl.Group(ctx.scene, groupCfg);
  1510. parent.addChild(group, false); // Don't automatically inherit properties
  1511. model._addComponent(group);
  1512. matrix = null;
  1513. parent = group;
  1514. parentCfg = groupCfg;
  1515. }
  1516.  
  1517. if (createObject && numMeshes > 0 || hasChildNodes) {
  1518.  
  1519. // Case 6: Creating explicit object, node has meshes OR node has child nodes
  1520.  
  1521. console.log("Case 6");
  1522.  
  1523. var groupCfg = {
  1524. matrix: matrix
  1525. };
  1526. xeogl._apply(ctx.modelProps, groupCfg);
  1527. if (createObject) {
  1528. xeogl._apply(createObject, groupCfg);
  1529. }
  1530. var group = new xeogl.Group(ctx.scene, groupCfg);
  1531. parent.addChild(group, false); // Don't automatically inherit properties
  1532. model._addComponent(group);
  1533. for (var i = 0, len = numMeshes; i < len; i++) {
  1534. meshesInfoMesh = meshesInfo[i];
  1535. var meshCfg = {
  1536. geometry: meshesInfoMesh.geometry
  1537. };
  1538. xeogl._apply(ctx.modelProps, meshCfg);
  1539. if (ctx.lambertMaterials) {
  1540. if (!model.material) {
  1541. model.material = new xeogl.LambertMaterial(ctx.scene, {
  1542. backfaces: true
  1543. });
  1544. }
  1545. meshCfg.material = model.material;
  1546. meshCfg.colorize = meshesInfoMesh.material; // [R,G,B,A]
  1547. meshCfg.opacity = meshesInfoMesh.material[3];
  1548. } else {
  1549. meshCfg.material = meshesInfoMesh.material;
  1550. }
  1551. if (createObject) {
  1552. xeogl._apply(createObject, meshCfg);
  1553. meshCfg.id = createObject.id + "." + i;
  1554. }
  1555. meshCfg.entityType = null;
  1556. mesh = new xeogl.Mesh(ctx.scene, meshCfg);
  1557. group.addChild(mesh, false); // Don't automatically inherit properties
  1558. model._addComponent(mesh);
  1559. }
  1560. matrix = null;
  1561. parent = group;
  1562. parentCfg = groupCfg;
  1563. }
  1564. }
  1565. }
  1566.  
  1567. if (nodeInfo.children) {
  1568. var children = nodeInfo.children;
  1569. var childNodeInfo;
  1570. var childNodeIdx;
  1571. for (var i = 0, len = children.length; i < len; i++) {
  1572. childNodeIdx = children[i];
  1573. childNodeInfo = json.nodes[childNodeIdx];
  1574. if (!childNodeInfo) {
  1575. error(ctx, "Node not found: " + i);
  1576. continue;
  1577. }
  1578. loadNode(ctx, nodeIdx, childNodeInfo, matrix, parent, parentCfg);
  1579. }
  1580. }
  1581. }
  1582.  
  1583. function error(ctx, msg) {
  1584. ctx.model.error(msg);
  1585. }
  1586.  
  1587. })();
  1588. }