LoaderSupport.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. 'use strict';
  6. if ( THREE.LoaderSupport === undefined ) { THREE.LoaderSupport = {} }
  7. /**
  8. * Validation functions
  9. * @class
  10. */
  11. THREE.LoaderSupport.Validator = {
  12. /**
  13. * If given input is null or undefined, false is returned otherwise true.
  14. *
  15. * @param input Anything
  16. * @returns {boolean}
  17. */
  18. isValid: function( input ) {
  19. return ( input !== null && input !== undefined );
  20. },
  21. /**
  22. * If given input is null or undefined, the defaultValue is returned otherwise the given input.
  23. *
  24. * @param input Anything
  25. * @param defaultValue Anything
  26. * @returns {*}
  27. */
  28. verifyInput: function( input, defaultValue ) {
  29. return ( input === null || input === undefined ) ? defaultValue : input;
  30. }
  31. };
  32. /**
  33. * Callbacks utilized by functions working with WWLoader implementations
  34. * @class
  35. */
  36. THREE.LoaderSupport.Callbacks = (function () {
  37. var Validator = THREE.LoaderSupport.Validator;
  38. function Callbacks() {
  39. this.onProgress = null;
  40. this.onMeshAlter = null;
  41. this.onLoad = null;
  42. }
  43. /**
  44. * Register callback function that is invoked by internal function "announceProgress" to print feedback.
  45. * @memberOf THREE.LoaderSupport.Callbacks
  46. *
  47. * @param {callback} callbackOnProgress Callback function for described functionality
  48. */
  49. Callbacks.prototype.setCallbackOnProgress = function ( callbackOnProgress ) {
  50. this.onProgress = Validator.verifyInput( callbackOnProgress, this.onProgress );
  51. };
  52. /**
  53. * Register callback function that is called every time a mesh was loaded.
  54. * Use {@link THREE.LoaderSupport.LoadedMeshUserOverride} for alteration instructions (geometry, material or disregard mesh).
  55. * @memberOf THREE.LoaderSupport.Callbacks
  56. *
  57. * @param {callback} callbackOnMeshAlter Callback function for described functionality
  58. */
  59. Callbacks.prototype.setCallbackOnMeshAlter = function ( callbackOnMeshAlter ) {
  60. this.onMeshAlter = Validator.verifyInput( callbackOnMeshAlter, this.onMeshAlter );
  61. };
  62. /**
  63. * Register callback function that is called once loading of the complete model is completed.
  64. * @memberOf THREE.LoaderSupport.Callbacks
  65. *
  66. * @param {callback} callbackOnLoad Callback function for described functionality
  67. */
  68. Callbacks.prototype.setCallbackOnLoad = function ( callbackOnLoad ) {
  69. this.onLoad = Validator.verifyInput( callbackOnLoad, this.onLoad );
  70. };
  71. return Callbacks;
  72. })();
  73. /**
  74. * Global callback definition
  75. * @class
  76. */
  77. THREE.LoaderSupport.Builder = (function () {
  78. var Validator = THREE.LoaderSupport.Validator;
  79. function Builder() {
  80. this.callbacks = new THREE.LoaderSupport.Callbacks();
  81. this.materials = [];
  82. this.materialNames = [];
  83. this._createDefaultMaterials();
  84. }
  85. Builder.prototype._createDefaultMaterials = function () {
  86. var defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  87. defaultMaterial.name = 'defaultMaterial';
  88. if ( ! Validator.isValid( this.materials[ defaultMaterial ] ) ) {
  89. this.materials[ defaultMaterial.name ] = defaultMaterial;
  90. }
  91. this.materialNames.push( defaultMaterial.name );
  92. var vertexColorMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  93. vertexColorMaterial.name = 'vertexColorMaterial';
  94. vertexColorMaterial.vertexColors = THREE.VertexColors;
  95. if ( ! Validator.isValid( this.materials[ vertexColorMaterial.name ] ) ) {
  96. this.materials[ vertexColorMaterial.name ] = vertexColorMaterial;
  97. }
  98. this.materialNames.push( vertexColorMaterial.name );
  99. };
  100. /**
  101. * Set materials loaded by any supplier of an Array of {@link THREE.Material}.
  102. * @memberOf THREE.LoaderSupport.Builder
  103. *
  104. * @param {THREE.Material[]} materials Array of {@link THREE.Material}
  105. */
  106. Builder.prototype.setMaterials = function ( materials ) {
  107. if ( Validator.isValid( materials ) && Object.keys( materials ).length > 0 ) {
  108. var materialName;
  109. for ( materialName in materials ) {
  110. if ( materials.hasOwnProperty( materialName ) && ! this.materials.hasOwnProperty( materialName) ) {
  111. this.materials[ materialName ] = materials[ materialName ];
  112. }
  113. }
  114. // always reset list of names as they are an array
  115. this.materialNames = [];
  116. for ( materialName in materials ) this.materialNames.push( materialName );
  117. }
  118. };
  119. Builder.prototype._setCallbacks = function ( callbackOnProgress, callbackOnMeshAlter, callbackOnLoad ) {
  120. this.callbacks.setCallbackOnProgress( callbackOnProgress );
  121. this.callbacks.setCallbackOnMeshAlter( callbackOnMeshAlter );
  122. this.callbacks.setCallbackOnLoad( callbackOnLoad );
  123. };
  124. /**
  125. * Builds one or multiple meshes from the data described in the payload (buffers, params, material info,
  126. *
  127. * @param {Object} payload buffers, params, materials
  128. * @returns {THREE.Mesh[]} mesh Array of {@link THREE.Mesh}
  129. */
  130. Builder.prototype.buildMeshes = function ( payload ) {
  131. var meshName = payload.params.meshName;
  132. var bufferGeometry = new THREE.BufferGeometry();
  133. bufferGeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( payload.buffers.vertices ), 3 ) );
  134. if ( Validator.isValid( payload.buffers.indices ) ) {
  135. bufferGeometry.setIndex( new THREE.BufferAttribute( new Uint32Array( payload.buffers.indices ), 1 ));
  136. }
  137. var haveVertexColors = Validator.isValid( payload.buffers.colors );
  138. if ( haveVertexColors ) {
  139. bufferGeometry.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( payload.buffers.colors ), 3 ) );
  140. }
  141. if ( Validator.isValid( payload.buffers.normals ) ) {
  142. bufferGeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( payload.buffers.normals ), 3 ) );
  143. } else {
  144. bufferGeometry.computeVertexNormals();
  145. }
  146. if ( Validator.isValid( payload.buffers.uvs ) ) {
  147. bufferGeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( payload.buffers.uvs ), 2 ) );
  148. }
  149. var materialDescriptions = payload.materials.materialDescriptions;
  150. var materialDescription;
  151. var material;
  152. var materialName;
  153. var createMultiMaterial = payload.materials.multiMaterial;
  154. var multiMaterials = [];
  155. var key;
  156. for ( key in materialDescriptions ) {
  157. materialDescription = materialDescriptions[ key ];
  158. material = this.materials[ materialDescription.name ];
  159. material = Validator.verifyInput( material, this.materials[ 'defaultMaterial' ] );
  160. if ( haveVertexColors ) {
  161. if ( material.hasOwnProperty( 'vertexColors' ) ) {
  162. materialName = material.name + '_vertexColor';
  163. var materialClone = this.materials[ materialName ];
  164. if ( ! Validator.isValid( materialClone ) ) {
  165. materialClone = material.clone();
  166. materialClone.name = materialName;
  167. materialClone.vertexColors = THREE.VertexColors;
  168. this.materials[ materialName ] = materialClone;
  169. }
  170. material = materialClone;
  171. } else {
  172. material = this.materials[ 'vertexColorMaterial' ];
  173. }
  174. }
  175. if ( materialDescription.flat ) {
  176. materialName = material.name + '_flat';
  177. var materialClone = this.materials[ materialName ];
  178. if ( ! Validator.isValid( materialClone ) ) {
  179. materialClone = material.clone();
  180. materialClone.name = materialName;
  181. materialClone.flatShading = true;
  182. this.materials[ materialName ] = materialClone;
  183. }
  184. material = materialClone;
  185. }
  186. if ( createMultiMaterial ) multiMaterials.push( material );
  187. }
  188. if ( createMultiMaterial ) {
  189. material = multiMaterials;
  190. var materialGroups = payload.materials.materialGroups;
  191. var materialGroup;
  192. for ( key in materialGroups ) {
  193. materialGroup = materialGroups[ key ];
  194. bufferGeometry.addGroup( materialGroup.start, materialGroup.count, materialGroup.index );
  195. }
  196. }
  197. var meshes = [];
  198. var mesh;
  199. var callbackOnMeshAlter = this.callbacks.onMeshAlter;
  200. var callbackOnMeshAlterResult;
  201. var useOrgMesh = true;
  202. if ( Validator.isValid( callbackOnMeshAlter ) ) {
  203. callbackOnMeshAlterResult = callbackOnMeshAlter( meshName, bufferGeometry, material );
  204. if ( Validator.isValid( callbackOnMeshAlterResult ) ) {
  205. if ( ! callbackOnMeshAlterResult.isDisregardMesh() && callbackOnMeshAlterResult.providesAlteredMeshes() ) {
  206. for ( var i in callbackOnMeshAlterResult.meshes ) {
  207. meshes.push( callbackOnMeshAlterResult.meshes[ i ] );
  208. }
  209. }
  210. useOrgMesh = false;
  211. }
  212. }
  213. if ( useOrgMesh ) {
  214. mesh = new THREE.Mesh( bufferGeometry, material );
  215. mesh.name = meshName;
  216. meshes.push( mesh );
  217. }
  218. var progressMessage;
  219. if ( Validator.isValid( meshes ) && meshes.length > 0 ) {
  220. var meshNames = [];
  221. for ( var i in meshes ) {
  222. mesh = meshes[ i ];
  223. meshNames[ i ] = mesh.name;
  224. }
  225. progressMessage = 'Adding mesh(es) (' + meshNames.length + ': ' + meshNames + ') from input mesh: ' + meshName;
  226. } else {
  227. progressMessage = 'Not adding mesh: ' + meshName;
  228. }
  229. var callbackOnProgress = this.callbacks.onProgress;
  230. if ( Validator.isValid( callbackOnProgress ) ) callbackOnProgress( progressMessage );
  231. return meshes;
  232. };
  233. return Builder;
  234. })();
  235. /**
  236. * Global callback definition
  237. * @class
  238. */
  239. THREE.LoaderSupport.Commons = (function () {
  240. var Validator = THREE.LoaderSupport.Validator;
  241. function Commons( manager ) {
  242. this.manager = Validator.verifyInput( manager, THREE.DefaultLoadingManager );
  243. this.modelName = '';
  244. this.instanceNo = 0;
  245. this.path = '';
  246. this.debug = false;
  247. this.useIndices = false;
  248. this.disregardNormals = false;
  249. this.loaderRootNode = new THREE.Group();
  250. this.builder = new THREE.LoaderSupport.Builder();
  251. this.callbacks = new THREE.LoaderSupport.Callbacks();
  252. };
  253. Commons.prototype._applyPrepData = function ( prepData ) {
  254. if ( Validator.isValid( prepData ) ) {
  255. this.setModelName( prepData.modelName );
  256. this.setStreamMeshesTo( prepData.streamMeshesTo );
  257. this.builder.setMaterials( prepData.materials );
  258. this.setUseIndices( prepData.useIndices );
  259. this.setDisregardNormals( prepData.disregardNormals );
  260. this._setCallbacks( prepData.getCallbacks().onProgress, prepData.getCallbacks().onMeshAlter, prepData.getCallbacks().onLoad );
  261. }
  262. };
  263. Commons.prototype._setCallbacks = function ( callbackOnProgress, callbackOnMeshAlter, callbackOnLoad ) {
  264. this.callbacks.setCallbackOnProgress( callbackOnProgress );
  265. this.callbacks.setCallbackOnMeshAlter( callbackOnMeshAlter );
  266. this.callbacks.setCallbackOnLoad( callbackOnLoad );
  267. this.builder._setCallbacks( callbackOnProgress, callbackOnMeshAlter, callbackOnLoad );
  268. };
  269. Commons.prototype.setModelName = function ( modelName ) {
  270. this.modelName = Validator.verifyInput( modelName, this.modelName );
  271. };
  272. /**
  273. * The URL of the base path
  274. * @param {string} path
  275. */
  276. Commons.prototype.setPath = function ( path ) {
  277. this.path = Validator.verifyInput( path, this.path );
  278. };
  279. /**
  280. * Allows to set debug mode.
  281. * @memberOf THREE.LoaderSupport.Commons
  282. *
  283. * @param {boolean} enabled
  284. */
  285. Commons.prototype.setDebug = function ( enabled ) {
  286. this.debug = enabled;
  287. };
  288. /**
  289. * Set the node where the loaded objects will be attached directly.
  290. * @memberOf THREE.LoaderSupport.Commons
  291. *
  292. * @param {THREE.Object3D} streamMeshesTo Attached scenegraph object where meshes will be attached live
  293. */
  294. Commons.prototype.setStreamMeshesTo = function ( streamMeshesTo ) {
  295. this.loaderRootNode = Validator.verifyInput( streamMeshesTo, this.loaderRootNode );
  296. };
  297. /**
  298. * Set materials loaded by MTLLoader or any other supplier of an Array of {@link THREE.Material}.
  299. * @memberOf THREE.LoaderSupport.Commons
  300. *
  301. * @param {THREE.Material[]} materials Array of {@link THREE.Material}
  302. */
  303. Commons.prototype.setMaterials = function ( materials ) {
  304. this.builder.setMaterials( materials );
  305. };
  306. /**
  307. * Tells whether indices should be used
  308. * @memberOf THREE.LoaderSupport.Commons
  309. *
  310. * @param {boolean} useIndices=false Default is false
  311. */
  312. Commons.prototype.setUseIndices = function ( useIndices ) {
  313. this.useIndices = useIndices === true;
  314. };
  315. /**
  316. * Tells whether normals should be completely disregarded
  317. * @memberOf THREE.LoaderSupport.Commons
  318. *
  319. * @param {boolean} disregardNormals=false Default is false
  320. */
  321. Commons.prototype.setDisregardNormals = function ( disregardNormals ) {
  322. this.disregardNormals = disregardNormals === true;
  323. };
  324. /**
  325. * Announce feedback which is give to the registered callbacks and logged if debug is enabled
  326. * @memberOf THREE.LoaderSupport.Commons
  327. *
  328. * @param baseText
  329. * @param text
  330. */
  331. Commons.prototype.onProgress = function ( baseText, text ) {
  332. var content = Validator.isValid( baseText ) ? baseText: '';
  333. content = Validator.isValid( text ) ? content + ' ' + text : content;
  334. if ( Validator.isValid( this.callbacks.onProgress ) ) this.callbacks.onProgress( content, this.modelName, this.instanceNo );
  335. if ( this.debug ) console.log( content );
  336. };
  337. return Commons;
  338. })();
  339. /**
  340. * Object to return by {@link THREE.LoaderSupport.Commons}.callbacks.meshLoaded.
  341. * Used to disregard a certain mesh or to return one to many created meshes.
  342. * @class
  343. *
  344. * @param {boolean} disregardMesh=false Tell implementation to completely disregard this mesh
  345. */
  346. THREE.LoaderSupport.LoadedMeshUserOverride = (function () {
  347. function LoadedMeshUserOverride( disregardMesh, alteredMesh ) {
  348. this.disregardMesh = disregardMesh === true;
  349. this.alteredMesh = alteredMesh === true;
  350. this.meshes = [];
  351. }
  352. /**
  353. * Add a mesh created within callback.
  354. *
  355. * @memberOf THREE.OBJLoader2.LoadedMeshUserOverride
  356. *
  357. * @param {THREE.Mesh} mesh
  358. */
  359. LoadedMeshUserOverride.prototype.addMesh = function ( mesh ) {
  360. this.meshes.push( mesh );
  361. };
  362. /**
  363. * Answers if mesh shall be disregarded completely.
  364. *
  365. * @returns {boolean}
  366. */
  367. LoadedMeshUserOverride.prototype.isDisregardMesh = function () {
  368. return this.disregardMesh;
  369. };
  370. /**
  371. * Answers if new mesh(es) were created.
  372. *
  373. * @returns {boolean}
  374. */
  375. LoadedMeshUserOverride.prototype.providesAlteredMeshes = function () {
  376. return this.alteredMesh;
  377. };
  378. return LoadedMeshUserOverride;
  379. })();
  380. /**
  381. * A resource description used by {@link THREE.LoaderSupport.PrepData} and others.
  382. * @class
  383. *
  384. * @param {string} url URL to the file
  385. * @param {string} extension The file extension (type)
  386. */
  387. THREE.LoaderSupport.ResourceDescriptor = (function () {
  388. var Validator = THREE.LoaderSupport.Validator;
  389. function ResourceDescriptor( url, extension ) {
  390. var urlParts = url.split( '/' );
  391. if ( urlParts.length < 2 ) {
  392. this.path = null;
  393. this.name = this.name = url;
  394. this.url = url;
  395. } else {
  396. this.path = Validator.verifyInput( urlParts.slice( 0, urlParts.length - 1).join( '/' ) + '/', null );
  397. this.name = Validator.verifyInput( urlParts[ urlParts.length - 1 ], null );
  398. this.url = url;
  399. }
  400. this.extension = Validator.verifyInput( extension, "default" );
  401. this.extension = this.extension.trim();
  402. this.content = null;
  403. }
  404. /**
  405. * Set the content of this resource (String)
  406. * @memberOf THREE.LoaderSupport.ResourceDescriptor
  407. *
  408. * @param {Object} content The file content as arraybuffer or text
  409. */
  410. ResourceDescriptor.prototype.setContent = function ( content ) {
  411. this.content = Validator.verifyInput( content, null );
  412. };
  413. return ResourceDescriptor;
  414. })();
  415. /**
  416. * Base class for configuration of prepareRun when using {@link THREE.LoaderSupport.WorkerSupport}.
  417. * @class
  418. */
  419. THREE.LoaderSupport.PrepData = (function () {
  420. var Validator = THREE.LoaderSupport.Validator;
  421. function PrepData( modelName ) {
  422. this.modelName = Validator.verifyInput( modelName, '' );
  423. this.resources = [];
  424. this.streamMeshesTo = null;
  425. this.materialPerSmoothingGroup = false;
  426. this.useIndices = false;
  427. this.disregardNormals = false;
  428. this.callbacks = new THREE.LoaderSupport.Callbacks();
  429. this.crossOrigin;
  430. this.useAsync = false;
  431. }
  432. /**
  433. * {@link THREE.Object3D} where meshes will be attached.
  434. * @memberOf THREE.LoaderSupport.PrepData
  435. *
  436. * @param {THREE.Object3D} streamMeshesTo Scene graph object
  437. */
  438. PrepData.prototype.setStreamMeshesTo = function ( streamMeshesTo ) {
  439. this.streamMeshesTo = Validator.verifyInput( streamMeshesTo, null );
  440. };
  441. /**
  442. * Tells whether a material shall be created per smoothing group
  443. * @memberOf THREE.LoaderSupport.PrepData
  444. *
  445. * @param {boolean} materialPerSmoothingGroup
  446. */
  447. PrepData.prototype.setMaterialPerSmoothingGroup = function ( materialPerSmoothingGroup ) {
  448. this.materialPerSmoothingGroup = materialPerSmoothingGroup;
  449. };
  450. /**
  451. * Tells whether indices should be used
  452. * @memberOf THREE.LoaderSupport.PrepData
  453. *
  454. * @param {boolean} useIndices=false Default is false
  455. */
  456. PrepData.prototype.setUseIndices = function ( useIndices ) {
  457. this.useIndices = useIndices === true;
  458. };
  459. /**
  460. * Tells whether normals should be completely disregarded
  461. * @memberOf THREE.LoaderSupport.PrepData
  462. *
  463. * @param {boolean} disregardNormals=false Default is false
  464. */
  465. PrepData.prototype.setDisregardNormals = function ( disregardNormals ) {
  466. this.disregardNormals = disregardNormals === true;
  467. };
  468. /**
  469. * Returns all callbacks as {@link THREE.LoaderSupport.Callbacks}
  470. * @memberOf THREE.LoaderSupport.PrepData
  471. *
  472. * @returns {THREE.LoaderSupport.Callbacks}
  473. */
  474. PrepData.prototype.getCallbacks = function () {
  475. return this.callbacks;
  476. };
  477. /**
  478. * Sets the CORS string to be used.
  479. * @memberOf THREE.LoaderSupport.PrepData
  480. *
  481. * @param {string} crossOrigin CORS value
  482. */
  483. PrepData.prototype.setCrossOrigin = function ( crossOrigin ) {
  484. this.crossOrigin = crossOrigin;
  485. };
  486. /**
  487. * Add a resource description
  488. * @memberOf THREE.LoaderSupport.PrepData
  489. *
  490. * @param {THREE.LoaderSupport.ResourceDescriptor} The resource description
  491. */
  492. PrepData.prototype.addResource = function ( resource ) {
  493. this.resources.push( resource );
  494. };
  495. /**
  496. *
  497. * @param {boolean} useAsync
  498. */
  499. PrepData.prototype.setUseAsync = function ( useAsync ) {
  500. this.useAsync = useAsync === true;
  501. };
  502. /**
  503. * Clones this object and returns it afterwards.
  504. *
  505. * @returns {@link THREE.LoaderSupport.PrepData}
  506. */
  507. PrepData.prototype.clone = function () {
  508. var clone = new THREE.LoaderSupport.PrepData( this.modelName );
  509. clone.resources = this.resources;
  510. clone.streamMeshesTo = this.streamMeshesTo;
  511. clone.materialPerSmoothingGroup = this.materialPerSmoothingGroup;
  512. clone.useIndices = this.useIndices;
  513. clone.disregardNormals = this.disregardNormals;
  514. clone.callbacks = this.callbacks;
  515. clone.crossOrigin = this.crossOrigin;
  516. clone.useAsync = this.useAsync;
  517. return clone;
  518. };
  519. return PrepData;
  520. })();
  521. THREE.LoaderSupport.WorkerRunnerRefImpl = (function () {
  522. function WorkerRunnerRefImpl() {
  523. var scope = this;
  524. var scopedRunner = function( event ) {
  525. scope.run( event.data );
  526. };
  527. self.addEventListener( 'message', scopedRunner, false );
  528. }
  529. WorkerRunnerRefImpl.prototype.applyProperties = function ( parser, params ) {
  530. var property, funcName, values;
  531. for ( property in params ) {
  532. funcName = 'set' + property.substring( 0, 1 ).toLocaleUpperCase() + property.substring( 1 );
  533. values = params[ property ];
  534. if ( parser.hasOwnProperty( property ) ) {
  535. if ( typeof parser[ funcName ] === 'function' ) {
  536. parser[ funcName ]( values );
  537. } else {
  538. parser[ property ] = values;
  539. }
  540. }
  541. }
  542. };
  543. WorkerRunnerRefImpl.prototype.run = function ( payload ) {
  544. if ( payload.cmd === 'run' ) {
  545. console.log( 'WorkerRunner: Starting Run...' );
  546. var callbacks = {
  547. callbackBuilder: function ( payload ) {
  548. self.postMessage( payload );
  549. },
  550. callbackProgress: function ( message ) {
  551. console.log( 'WorkerRunner: progress: ' + message );
  552. }
  553. };
  554. // Parser is expected to be named as such
  555. var parser = new Parser();
  556. this.applyProperties( parser, payload.params );
  557. this.applyProperties( parser, payload.materials );
  558. this.applyProperties( parser, callbacks );
  559. parser.parse( payload.buffers.input );
  560. console.log( 'WorkerRunner: Run complete!' );
  561. callbacks.callbackBuilder( {
  562. cmd: 'complete',
  563. msg: 'WorkerRunner completed run.'
  564. } );
  565. } else {
  566. console.error( 'WorkerRunner: Received unknown command: ' + payload.cmd );
  567. }
  568. };
  569. return WorkerRunnerRefImpl;
  570. })();
  571. THREE.LoaderSupport.WorkerSupport = (function () {
  572. var WORKER_SUPPORT_VERSION = '1.0.0-dev';
  573. var Validator = THREE.LoaderSupport.Validator;
  574. function WorkerSupport() {
  575. console.log( "Using THREE.LoaderSupport.WorkerSupport version: " + WORKER_SUPPORT_VERSION );
  576. // check worker support first
  577. if ( window.Worker === undefined ) throw "This browser does not support web workers!";
  578. if ( window.Blob === undefined ) throw "This browser does not support Blob!";
  579. if ( typeof window.URL.createObjectURL !== 'function' ) throw "This browser does not support Object creation from URL!";
  580. this.worker = null;
  581. this.workerCode = null;
  582. this.running = false;
  583. this.terminateRequested = false;
  584. this.callbacks = {
  585. builder: null,
  586. onLoad: null
  587. };
  588. }
  589. WorkerSupport.prototype.validate = function ( functionCodeBuilder, forceWorkerReload, runnerImpl ) {
  590. this.running = false;
  591. if ( forceWorkerReload ) {
  592. this.worker = null;
  593. this.workerCode = null;
  594. this.callbacks.builder = null;
  595. this.callbacks.onLoad = null;
  596. }
  597. if ( ! Validator.isValid( this.worker ) ) {
  598. console.log( 'WorkerSupport: Building worker code...' );
  599. console.time( 'buildWebWorkerCode' );
  600. var workerRunner;
  601. if ( Validator.isValid( runnerImpl ) ) {
  602. console.log( 'WorkerSupport: Using "' + runnerImpl.name + '" as Runncer class for worker.');
  603. workerRunner = runnerImpl;
  604. } else {
  605. console.log( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.WorkerRunnerRefImpl" as Runncer class for worker.');
  606. workerRunner = THREE.LoaderSupport.WorkerRunnerRefImpl;
  607. }
  608. this.workerCode = functionCodeBuilder( buildObject, buildSingelton );
  609. this.workerCode += buildSingelton( workerRunner.name, workerRunner.name, workerRunner );
  610. this.workerCode += 'new ' + workerRunner.name + '();\n\n';
  611. var blob = new Blob( [ this.workerCode ], { type: 'text/plain' } );
  612. this.worker = new Worker( window.URL.createObjectURL( blob ) );
  613. console.timeEnd( 'buildWebWorkerCode' );
  614. var scope = this;
  615. var receiveWorkerMessage = function ( e ) {
  616. var payload = e.data;
  617. switch ( payload.cmd ) {
  618. case 'meshData':
  619. scope.callbacks.builder( payload );
  620. break;
  621. case 'complete':
  622. scope.callbacks.onLoad( payload.msg );
  623. scope.running = false;
  624. if ( scope.terminateRequested ) {
  625. console.log( 'WorkerSupport: Run is complete. Terminating application on request!' );
  626. scope.terminateWorker();
  627. }
  628. break;
  629. default:
  630. console.error( 'WorkerSupport: Received unknown command: ' + payload.cmd );
  631. break;
  632. }
  633. };
  634. this.worker.addEventListener( 'message', receiveWorkerMessage, false );
  635. }
  636. };
  637. WorkerSupport.prototype.terminateWorker = function () {
  638. if ( Validator.isValid( this.worker ) ) {
  639. this.worker.terminate();
  640. }
  641. this.worker = null;
  642. this.workerCode = null;
  643. };
  644. WorkerSupport.prototype.setCallbacks = function ( builder, onLoad ) {
  645. this.callbacks = {
  646. builder: builder,
  647. onLoad: onLoad
  648. };
  649. };
  650. var buildObject = function ( fullName, object ) {
  651. var objectString = fullName + ' = {\n';
  652. var part;
  653. for ( var name in object ) {
  654. part = object[ name ];
  655. if ( typeof( part ) === 'string' || part instanceof String ) {
  656. part = part.replace( '\n', '\\n' );
  657. part = part.replace( '\r', '\\r' );
  658. objectString += '\t' + name + ': "' + part + '",\n';
  659. } else if ( part instanceof Array ) {
  660. objectString += '\t' + name + ': [' + part + '],\n';
  661. } else if ( Number.isInteger( part ) ) {
  662. objectString += '\t' + name + ': ' + part + ',\n';
  663. } else if ( typeof part === 'function' ) {
  664. objectString += '\t' + name + ': ' + part + ',\n';
  665. }
  666. }
  667. objectString += '}\n\n';
  668. return objectString;
  669. };
  670. var buildSingelton = function ( fullName, internalName, object ) {
  671. var objectString = fullName + ' = (function () {\n\n';
  672. objectString += '\t' + object.prototype.constructor.toString() + '\n\n';
  673. var funcString;
  674. var objectPart;
  675. for ( var name in object.prototype ) {
  676. objectPart = object.prototype[ name ];
  677. if ( typeof objectPart === 'function' ) {
  678. funcString = objectPart.toString();
  679. objectString += '\t' + internalName + '.prototype.' + name + ' = ' + funcString + ';\n\n';
  680. }
  681. }
  682. objectString += '\treturn ' + internalName + ';\n';
  683. objectString += '})();\n\n';
  684. return objectString;
  685. };
  686. WorkerSupport.prototype.setTerminateRequested = function ( terminateRequested ) {
  687. this.terminateRequested = terminateRequested === true;
  688. };
  689. WorkerSupport.prototype.run = function ( messageObject ) {
  690. if ( ! Validator.isValid( this.callbacks.builder ) ) throw 'Unable to run as no "builder" callback is set.';
  691. if ( ! Validator.isValid( this.callbacks.onLoad ) ) throw 'Unable to run as no "onLoad" callback is set.';
  692. if ( Validator.isValid( this.worker ) ) {
  693. this.running = true;
  694. this.worker.postMessage( messageObject );
  695. }
  696. };
  697. return WorkerSupport;
  698. })();
  699. /**
  700. * Orchestrate loading of multiple OBJ files/data from an instruction queue with a configurable amount of workers (1-16).
  701. * Workflow:
  702. * prepareWorkers
  703. * enqueueForRun
  704. * processQueue
  705. * deregister
  706. *
  707. * @class
  708. */
  709. THREE.LoaderSupport.WorkerDirector = (function () {
  710. var LOADER_WORKER_DIRECTOR_VERSION = '1.0.0-dev';
  711. var Validator = THREE.LoaderSupport.Validator;
  712. var MAX_WEB_WORKER = 16;
  713. var MAX_QUEUE_SIZE = 8192;
  714. function WorkerDirector( classDef ) {
  715. console.log( "Using THREE.LoaderSupport.WorkerDirector version: " + LOADER_WORKER_DIRECTOR_VERSION );
  716. this.maxQueueSize = MAX_QUEUE_SIZE ;
  717. this.maxWebWorkers = MAX_WEB_WORKER;
  718. this.crossOrigin = null;
  719. if ( ! Validator.isValid( classDef ) ) throw 'Provided invalid classDef: ' + classDef;
  720. this.workerDescription = {
  721. classDef: classDef,
  722. globalCallbacks: {},
  723. workerSupports: []
  724. };
  725. this.objectsCompleted = 0;
  726. this.instructionQueue = [];
  727. }
  728. /**
  729. * Returns the maximum length of the instruction queue.
  730. * @memberOf THREE.LoaderSupport.WorkerDirector
  731. *
  732. * @returns {number}
  733. */
  734. WorkerDirector.prototype.getMaxQueueSize = function () {
  735. return this.maxQueueSize;
  736. };
  737. /**
  738. * Returns the maximum number of workers.
  739. * @memberOf THREE.LoaderSupport.WorkerDirector
  740. *
  741. * @returns {number}
  742. */
  743. WorkerDirector.prototype.getMaxWebWorkers = function () {
  744. return this.maxWebWorkers;
  745. };
  746. /**
  747. * Sets the CORS string to be used.
  748. * @memberOf THREE.LoaderSupport.WorkerDirector
  749. *
  750. * @param {string} crossOrigin CORS value
  751. */
  752. WorkerDirector.prototype.setCrossOrigin = function ( crossOrigin ) {
  753. this.crossOrigin = crossOrigin;
  754. };
  755. /**
  756. * Create or destroy workers according limits. Set the name and register callbacks for dynamically created web workers.
  757. * @memberOf THREE.LoaderSupport.WorkerDirector
  758. *
  759. * @param {THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks} globalCallbacks Register global callbacks used by all web workers
  760. * @param {number} maxQueueSize Set the maximum size of the instruction queue (1-1024)
  761. * @param {number} maxWebWorkers Set the maximum amount of workers (1-16)
  762. */
  763. WorkerDirector.prototype.prepareWorkers = function ( globalCallbacks, maxQueueSize, maxWebWorkers ) {
  764. if ( Validator.isValid( globalCallbacks ) ) this.workerDescription.globalCallbacks = globalCallbacks;
  765. this.maxQueueSize = Math.min( maxQueueSize, MAX_QUEUE_SIZE );
  766. this.maxWebWorkers = Math.min( maxWebWorkers, MAX_WEB_WORKER );
  767. this.objectsCompleted = 0;
  768. this.instructionQueue = [];
  769. var start = this.workerDescription.workerSupports.length;
  770. var i;
  771. if ( start < this.maxWebWorkers ) {
  772. for ( i = start; i < this.maxWebWorkers; i++ ) {
  773. this.workerDescription.workerSupports[ i ] = {
  774. workerSupport: new THREE.LoaderSupport.WorkerSupport(),
  775. loader: null
  776. };
  777. }
  778. } else {
  779. for ( i = start - 1; i >= this.maxWebWorkers; i-- ) {
  780. this.workerDescription.workerSupports[ i ].workerSupport.setRequestTerminate( true );
  781. this.workerDescription.workerSupports.pop();
  782. }
  783. }
  784. };
  785. /**
  786. * Store run instructions in internal instructionQueue.
  787. * @memberOf THREE.LoaderSupport.WorkerDirector
  788. *
  789. * @param {Object} prepData Either {@link THREE.LoaderSupport.PrepData}
  790. */
  791. WorkerDirector.prototype.enqueueForRun = function ( prepData ) {
  792. if ( this.instructionQueue.length < this.maxQueueSize ) {
  793. this.instructionQueue.push( prepData );
  794. }
  795. };
  796. /**
  797. * Process the instructionQueue until it is depleted.
  798. * @memberOf THREE.LoaderSupport.WorkerDirector
  799. */
  800. WorkerDirector.prototype.processQueue = function () {
  801. if ( this.instructionQueue.length === 0 ) return;
  802. var length = Math.min( this.maxWebWorkers, this.instructionQueue.length );
  803. for ( var i = 0; i < length; i++ ) {
  804. this._kickWorkerRun( this.instructionQueue[ 0 ], i );
  805. this.instructionQueue.shift();
  806. }
  807. };
  808. WorkerDirector.prototype._kickWorkerRun = function( prepData, workerInstanceNo ) {
  809. var scope = this;
  810. var directorOnLoad = function ( sceneGraphBaseNode, modelName, instanceNo ) {
  811. scope.objectsCompleted++;
  812. var nextPrepData = scope.instructionQueue[ 0 ];
  813. if ( Validator.isValid( nextPrepData ) ) {
  814. scope.instructionQueue.shift();
  815. console.log( '\nAssigning next item from queue to worker (queue length: ' + scope.instructionQueue.length + ')\n\n' );
  816. scope._kickWorkerRun( nextPrepData, instanceNo );
  817. } else if ( scope.instructionQueue.length === 0 ) {
  818. scope.deregister();
  819. }
  820. };
  821. var prepDataCallbacks = prepData.getCallbacks();
  822. var globalCallbacks = this.workerDescription.globalCallbacks;
  823. var wrapperOnLoad = function ( sceneGraphBaseNode, modelName, instanceNo ) {
  824. if ( Validator.isValid( globalCallbacks.onLoad ) ) {
  825. globalCallbacks.onLoad( sceneGraphBaseNode, modelName, instanceNo );
  826. }
  827. if ( Validator.isValid( prepDataCallbacks.onLoad ) ) {
  828. prepDataCallbacks.onLoad( sceneGraphBaseNode, modelName, instanceNo );
  829. }
  830. directorOnLoad( sceneGraphBaseNode, modelName, instanceNo );
  831. };
  832. var wrapperOnProgress = function ( content, modelName, instanceNo ) {
  833. if ( Validator.isValid( globalCallbacks.onProgress ) ) {
  834. globalCallbacks.onProgress( content, modelName, instanceNo );
  835. }
  836. if ( Validator.isValid( prepDataCallbacks.onProgress ) ) {
  837. prepDataCallbacks.onProgress( content, modelName, instanceNo );
  838. }
  839. };
  840. var wrapperOnMeshAlter = function ( meshName, bufferGeometry, material ) {
  841. if ( Validator.isValid( globalCallbacks.onMeshAlter ) ) {
  842. globalCallbacks.onMeshAlter( meshName, bufferGeometry, material );
  843. }
  844. if ( Validator.isValid( prepDataCallbacks.onMeshAlter ) ) {
  845. prepDataCallbacks.onMeshAlter( meshName, bufferGeometry, material );
  846. }
  847. };
  848. var supportTuple = this.workerDescription.workerSupports[ workerInstanceNo ];
  849. supportTuple.loader = this._buildLoader( workerInstanceNo );
  850. var updatedCallbacks = new THREE.LoaderSupport.Callbacks();
  851. updatedCallbacks.setCallbackOnLoad( wrapperOnLoad );
  852. updatedCallbacks.setCallbackOnProgress( wrapperOnProgress );
  853. updatedCallbacks.setCallbackOnMeshAlter( wrapperOnMeshAlter );
  854. prepData.callbacks = updatedCallbacks;
  855. supportTuple.loader.run( prepData, supportTuple.workerSupport );
  856. };
  857. WorkerDirector.prototype._buildLoader = function ( instanceNo ) {
  858. var classDef = this.workerDescription.classDef;
  859. var loader = Object.create( classDef.prototype );
  860. this.workerDescription.classDef.call( loader );
  861. // verify that all required functions are implemented
  862. if ( ! loader.hasOwnProperty( 'instanceNo' ) ) throw classDef.name + ' has no property "instanceNo".';
  863. loader.instanceNo = instanceNo;
  864. if ( ! loader.hasOwnProperty( 'workerSupport' ) ) {
  865. throw classDef.name + ' has no property "workerSupport".';
  866. } else if ( ! classDef.workerSupport instanceof THREE.LoaderSupport.WorkerSupport ) {
  867. throw classDef.name + '.workerSupport is not of type "THREE.LoaderSupport.WorkerSupport".';
  868. }
  869. if ( typeof loader.run !== 'function' ) throw classDef.name + ' has no function "run".';
  870. return loader;
  871. };
  872. /**
  873. * Terminate all workers.
  874. * @memberOf THREE.LoaderSupport.WorkerDirector
  875. */
  876. WorkerDirector.prototype.deregister = function () {
  877. console.log( 'WorkerDirector received the deregister call. Terminating all workers!' );
  878. for ( var i = 0, length = this.workerDescription.workerSupports.length; i < length; i++ ) {
  879. var supportTuple = this.workerDescription.workerSupports[ i ];
  880. supportTuple.workerSupport.setTerminateRequested( true );
  881. console.log( 'Requested termination of worker.' );
  882. var loaderCallbacks = supportTuple.loader.callbacks;
  883. if ( Validator.isValid( loaderCallbacks.onProgress ) ) loaderCallbacks.onProgress( '' );
  884. }
  885. this.workerDescription.workerSupports = [];
  886. this.instructionQueue = [];
  887. };
  888. return WorkerDirector;
  889. })();