LoaderSupport.js 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509
  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 Can be 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 Can be anything
  25. * @param defaultValue Can be anything
  26. * @returns {*}
  27. */
  28. verifyInput: function( input, defaultValue ) {
  29. return ( input === null || input === undefined ) ? defaultValue : input;
  30. }
  31. };
  32. /**
  33. * Callbacks utilized by loaders and builders.
  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. this.onLoadMaterials = null;
  43. }
  44. /**
  45. * Register callback function that is invoked by internal function "announceProgress" to print feedback.
  46. * @memberOf THREE.LoaderSupport.Callbacks
  47. *
  48. * @param {callback} callbackOnProgress Callback function for described functionality
  49. */
  50. Callbacks.prototype.setCallbackOnProgress = function ( callbackOnProgress ) {
  51. this.onProgress = Validator.verifyInput( callbackOnProgress, this.onProgress );
  52. };
  53. /**
  54. * Register callback function that is called every time a mesh was loaded.
  55. * Use {@link THREE.LoaderSupport.LoadedMeshUserOverride} for alteration instructions (geometry, material or disregard mesh).
  56. * @memberOf THREE.LoaderSupport.Callbacks
  57. *
  58. * @param {callback} callbackOnMeshAlter Callback function for described functionality
  59. */
  60. Callbacks.prototype.setCallbackOnMeshAlter = function ( callbackOnMeshAlter ) {
  61. this.onMeshAlter = Validator.verifyInput( callbackOnMeshAlter, this.onMeshAlter );
  62. };
  63. /**
  64. * Register callback function that is called once loading of the complete OBJ file is completed.
  65. * @memberOf THREE.LoaderSupport.Callbacks
  66. *
  67. * @param {callback} callbackOnLoad Callback function for described functionality
  68. */
  69. Callbacks.prototype.setCallbackOnLoad = function ( callbackOnLoad ) {
  70. this.onLoad = Validator.verifyInput( callbackOnLoad, this.onLoad );
  71. };
  72. /**
  73. * Register callback function that is called when materials have been loaded.
  74. * @memberOf THREE.LoaderSupport.Callbacks
  75. *
  76. * @param {callback} callbackOnLoadMaterials Callback function for described functionality
  77. */
  78. Callbacks.prototype.setCallbackOnLoadMaterials = function ( callbackOnLoadMaterials ) {
  79. this.onLoadMaterials = Validator.verifyInput( callbackOnLoadMaterials, this.onLoadMaterials );
  80. };
  81. return Callbacks;
  82. })();
  83. /**
  84. * Object to return by callback onMeshAlter. Used to disregard a certain mesh or to return one to many meshes.
  85. * @class
  86. *
  87. * @param {boolean} disregardMesh=false Tell implementation to completely disregard this mesh
  88. * @param {boolean} disregardMesh=false Tell implementation that mesh(es) have been altered or added
  89. */
  90. THREE.LoaderSupport.LoadedMeshUserOverride = (function () {
  91. function LoadedMeshUserOverride( disregardMesh, alteredMesh ) {
  92. this.disregardMesh = disregardMesh === true;
  93. this.alteredMesh = alteredMesh === true;
  94. this.meshes = [];
  95. }
  96. /**
  97. * Add a mesh created within callback.
  98. *
  99. * @memberOf THREE.OBJLoader2.LoadedMeshUserOverride
  100. *
  101. * @param {THREE.Mesh} mesh
  102. */
  103. LoadedMeshUserOverride.prototype.addMesh = function ( mesh ) {
  104. this.meshes.push( mesh );
  105. this.alteredMesh = true;
  106. };
  107. /**
  108. * Answers if mesh shall be disregarded completely.
  109. *
  110. * @returns {boolean}
  111. */
  112. LoadedMeshUserOverride.prototype.isDisregardMesh = function () {
  113. return this.disregardMesh;
  114. };
  115. /**
  116. * Answers if new mesh(es) were created.
  117. *
  118. * @returns {boolean}
  119. */
  120. LoadedMeshUserOverride.prototype.providesAlteredMeshes = function () {
  121. return this.alteredMesh;
  122. };
  123. return LoadedMeshUserOverride;
  124. })();
  125. /**
  126. * A resource description used by {@link THREE.LoaderSupport.PrepData} and others.
  127. * @class
  128. *
  129. * @param {string} url URL to the file
  130. * @param {string} extension The file extension (type)
  131. */
  132. THREE.LoaderSupport.ResourceDescriptor = (function () {
  133. var Validator = THREE.LoaderSupport.Validator;
  134. function ResourceDescriptor( url, extension ) {
  135. var urlParts = url.split( '/' );
  136. if ( urlParts.length < 2 ) {
  137. this.path = null;
  138. this.name = url;
  139. this.url = url;
  140. } else {
  141. this.path = Validator.verifyInput( urlParts.slice( 0, urlParts.length - 1).join( '/' ) + '/', null );
  142. this.name = urlParts[ urlParts.length - 1 ];
  143. this.url = url;
  144. }
  145. this.name = Validator.verifyInput( this.name, 'Unnamed_Resource' );
  146. this.extension = Validator.verifyInput( extension, 'default' );
  147. this.extension = this.extension.trim();
  148. this.content = null;
  149. }
  150. /**
  151. * Set the content of this resource
  152. * @memberOf THREE.LoaderSupport.ResourceDescriptor
  153. *
  154. * @param {Object} content The file content as arraybuffer or text
  155. */
  156. ResourceDescriptor.prototype.setContent = function ( content ) {
  157. this.content = Validator.verifyInput( content, null );
  158. };
  159. return ResourceDescriptor;
  160. })();
  161. /**
  162. * Configuration instructions to be used by run method.
  163. * @class
  164. */
  165. THREE.LoaderSupport.PrepData = (function () {
  166. var Validator = THREE.LoaderSupport.Validator;
  167. function PrepData( modelName ) {
  168. this.logging = {
  169. enabled: true,
  170. debug: false
  171. };
  172. this.modelName = Validator.verifyInput( modelName, '' );
  173. this.resources = [];
  174. this.callbacks = new THREE.LoaderSupport.Callbacks();
  175. }
  176. /**
  177. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  178. * @memberOf THREE.LoaderSupport.PrepData
  179. *
  180. * @param {boolean} enabled True or false.
  181. * @param {boolean} debug True or false.
  182. */
  183. PrepData.prototype.setLogging = function ( enabled, debug ) {
  184. this.logging.enabled = enabled === true;
  185. this.logging.debug = debug === true;
  186. };
  187. /**
  188. * Returns all callbacks as {@link THREE.LoaderSupport.Callbacks}
  189. * @memberOf THREE.LoaderSupport.PrepData
  190. *
  191. * @returns {THREE.LoaderSupport.Callbacks}
  192. */
  193. PrepData.prototype.getCallbacks = function () {
  194. return this.callbacks;
  195. };
  196. /**
  197. * Add a resource description.
  198. * @memberOf THREE.LoaderSupport.PrepData
  199. *
  200. * @param {THREE.LoaderSupport.ResourceDescriptor} Adds a {@link THREE.LoaderSupport.ResourceDescriptor}
  201. */
  202. PrepData.prototype.addResource = function ( resource ) {
  203. this.resources.push( resource );
  204. };
  205. /**
  206. * Clones this object and returns it afterwards. Callbacks and resources are not cloned deep (references!).
  207. * @memberOf THREE.LoaderSupport.PrepData
  208. *
  209. * @returns {@link THREE.LoaderSupport.PrepData}
  210. */
  211. PrepData.prototype.clone = function () {
  212. var clone = new THREE.LoaderSupport.PrepData( this.modelName );
  213. clone.logging.enabled = this.logging.enabled;
  214. clone.logging.debug = this.logging.debug;
  215. clone.resources = this.resources;
  216. clone.callbacks = this.callbacks;
  217. var property, value;
  218. for ( property in this ) {
  219. value = this[ property ];
  220. if ( ! clone.hasOwnProperty( property ) && typeof this[ property ] !== 'function' ) {
  221. clone[ property ] = value;
  222. }
  223. }
  224. return clone;
  225. };
  226. /**
  227. * Identify files or content of interest from an Array of {@link THREE.LoaderSupport.ResourceDescriptor}.
  228. * @memberOf THREE.LoaderSupport.PrepData
  229. *
  230. * @param {THREE.LoaderSupport.ResourceDescriptor[]} resources Array of {@link THREE.LoaderSupport.ResourceDescriptor}
  231. * @param Object fileDesc Object describing which resources are of interest (ext, type (string or UInt8Array) and ignore (boolean))
  232. * @returns {{}} Object with each "ext" and the corresponding {@link THREE.LoaderSupport.ResourceDescriptor}
  233. */
  234. PrepData.prototype.checkResourceDescriptorFiles = function ( resources, fileDesc ) {
  235. var resource, triple, i, found;
  236. var result = {};
  237. for ( var index in resources ) {
  238. resource = resources[ index ];
  239. found = false;
  240. if ( ! Validator.isValid( resource.name ) ) continue;
  241. if ( Validator.isValid( resource.content ) ) {
  242. for ( i = 0; i < fileDesc.length && !found; i++ ) {
  243. triple = fileDesc[ i ];
  244. if ( resource.extension.toLowerCase() === triple.ext.toLowerCase() ) {
  245. if ( triple.ignore ) {
  246. found = true;
  247. } else if ( triple.type === "ArrayBuffer" ) {
  248. // fast-fail on bad type
  249. if ( ! ( resource.content instanceof ArrayBuffer || resource.content instanceof Uint8Array ) ) throw 'Provided content is not of type ArrayBuffer! Aborting...';
  250. result[ triple.ext ] = resource;
  251. found = true;
  252. } else if ( triple.type === "String" ) {
  253. if ( ! ( typeof( resource.content ) === 'string' || resource.content instanceof String) ) throw 'Provided content is not of type String! Aborting...';
  254. result[ triple.ext ] = resource;
  255. found = true;
  256. }
  257. }
  258. }
  259. if ( !found ) throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  260. } else {
  261. // fast-fail on bad type
  262. if ( ! ( typeof( resource.name ) === 'string' || resource.name instanceof String ) ) throw 'Provided file is not properly defined! Aborting...';
  263. for ( i = 0; i < fileDesc.length && !found; i++ ) {
  264. triple = fileDesc[ i ];
  265. if ( resource.extension.toLowerCase() === triple.ext.toLowerCase() ) {
  266. if ( ! triple.ignore ) result[ triple.ext ] = resource;
  267. found = true;
  268. }
  269. }
  270. if ( !found ) throw 'Unidentified resource "' + resource.name + '": ' + resource.url;
  271. }
  272. }
  273. return result;
  274. };
  275. return PrepData;
  276. })();
  277. /**
  278. * Builds one or many THREE.Mesh from one raw set of Arraybuffers, materialGroup descriptions and further parameters.
  279. * Supports vertex, vertexColor, normal, uv and index buffers.
  280. * @class
  281. */
  282. THREE.LoaderSupport.MeshBuilder = (function () {
  283. var LOADER_MESH_BUILDER_VERSION = '1.2.1';
  284. var Validator = THREE.LoaderSupport.Validator;
  285. function MeshBuilder() {
  286. console.info( 'Using THREE.LoaderSupport.MeshBuilder version: ' + LOADER_MESH_BUILDER_VERSION );
  287. this.logging = {
  288. enabled: true,
  289. debug: false
  290. };
  291. this.callbacks = new THREE.LoaderSupport.Callbacks();
  292. this.materials = [];
  293. }
  294. /**
  295. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  296. * @memberOf THREE.LoaderSupport.MeshBuilder
  297. *
  298. * @param {boolean} enabled True or false.
  299. * @param {boolean} debug True or false.
  300. */
  301. MeshBuilder.prototype.setLogging = function ( enabled, debug ) {
  302. this.logging.enabled = enabled === true;
  303. this.logging.debug = debug === true;
  304. };
  305. /**
  306. * Initializes the MeshBuilder (currently only default material initialisation).
  307. * @memberOf THREE.LoaderSupport.MeshBuilder
  308. *
  309. */
  310. MeshBuilder.prototype.init = function () {
  311. var defaultMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  312. defaultMaterial.name = 'defaultMaterial';
  313. var defaultVertexColorMaterial = new THREE.MeshStandardMaterial( { color: 0xDCF1FF } );
  314. defaultVertexColorMaterial.name = 'defaultVertexColorMaterial';
  315. defaultVertexColorMaterial.vertexColors = THREE.VertexColors;
  316. var defaultLineMaterial = new THREE.LineBasicMaterial();
  317. defaultLineMaterial.name = 'defaultLineMaterial';
  318. var defaultPointMaterial = new THREE.PointsMaterial( { size: 1 } );
  319. defaultPointMaterial.name = 'defaultPointMaterial';
  320. var runtimeMaterials = {};
  321. runtimeMaterials[ defaultMaterial.name ] = defaultMaterial;
  322. runtimeMaterials[ defaultVertexColorMaterial.name ] = defaultVertexColorMaterial;
  323. runtimeMaterials[ defaultLineMaterial.name ] = defaultLineMaterial;
  324. runtimeMaterials[ defaultPointMaterial.name ] = defaultPointMaterial;
  325. this.updateMaterials(
  326. {
  327. cmd: 'materialData',
  328. materials: {
  329. materialCloneInstructions: null,
  330. serializedMaterials: null,
  331. runtimeMaterials: runtimeMaterials
  332. }
  333. }
  334. );
  335. };
  336. /**
  337. * Set materials loaded by any supplier of an Array of {@link THREE.Material}.
  338. * @memberOf THREE.LoaderSupport.MeshBuilder
  339. *
  340. * @param {THREE.Material[]} materials Array of {@link THREE.Material}
  341. */
  342. MeshBuilder.prototype.setMaterials = function ( materials ) {
  343. var payload = {
  344. cmd: 'materialData',
  345. materials: {
  346. materialCloneInstructions: null,
  347. serializedMaterials: null,
  348. runtimeMaterials: Validator.isValid( this.callbacks.onLoadMaterials ) ? this.callbacks.onLoadMaterials( materials ) : materials
  349. }
  350. };
  351. this.updateMaterials( payload );
  352. };
  353. MeshBuilder.prototype._setCallbacks = function ( callbacks ) {
  354. if ( Validator.isValid( callbacks.onProgress ) ) this.callbacks.setCallbackOnProgress( callbacks.onProgress );
  355. if ( Validator.isValid( callbacks.onMeshAlter ) ) this.callbacks.setCallbackOnMeshAlter( callbacks.onMeshAlter );
  356. if ( Validator.isValid( callbacks.onLoad ) ) this.callbacks.setCallbackOnLoad( callbacks.onLoad );
  357. if ( Validator.isValid( callbacks.onLoadMaterials ) ) this.callbacks.setCallbackOnLoadMaterials( callbacks.onLoadMaterials );
  358. };
  359. /**
  360. * Delegates processing of the payload (mesh building or material update) to the corresponding functions (BW-compatibility).
  361. * @memberOf THREE.LoaderSupport.MeshBuilder
  362. *
  363. * @param {Object} payload Raw Mesh or Material descriptions.
  364. * @returns {THREE.Mesh[]} mesh Array of {@link THREE.Mesh} or null in case of material update
  365. */
  366. MeshBuilder.prototype.processPayload = function ( payload ) {
  367. if ( payload.cmd === 'meshData' ) {
  368. return this.buildMeshes( payload );
  369. } else if ( payload.cmd === 'materialData' ) {
  370. this.updateMaterials( payload );
  371. return null;
  372. }
  373. };
  374. /**
  375. * Builds one or multiple meshes from the data described in the payload (buffers, params, material info).
  376. * @memberOf THREE.LoaderSupport.MeshBuilder
  377. *
  378. * @param {Object} meshPayload Raw mesh description (buffers, params, materials) used to build one to many meshes.
  379. * @returns {THREE.Mesh[]} mesh Array of {@link THREE.Mesh}
  380. */
  381. MeshBuilder.prototype.buildMeshes = function ( meshPayload ) {
  382. var meshName = meshPayload.params.meshName;
  383. var bufferGeometry = new THREE.BufferGeometry();
  384. bufferGeometry.addAttribute( 'position', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.vertices ), 3 ) );
  385. if ( Validator.isValid( meshPayload.buffers.indices ) ) {
  386. bufferGeometry.setIndex( new THREE.BufferAttribute( new Uint32Array( meshPayload.buffers.indices ), 1 ));
  387. }
  388. var haveVertexColors = Validator.isValid( meshPayload.buffers.colors );
  389. if ( haveVertexColors ) {
  390. bufferGeometry.addAttribute( 'color', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.colors ), 3 ) );
  391. }
  392. if ( Validator.isValid( meshPayload.buffers.normals ) ) {
  393. bufferGeometry.addAttribute( 'normal', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.normals ), 3 ) );
  394. } else {
  395. bufferGeometry.computeVertexNormals();
  396. }
  397. if ( Validator.isValid( meshPayload.buffers.uvs ) ) {
  398. bufferGeometry.addAttribute( 'uv', new THREE.BufferAttribute( new Float32Array( meshPayload.buffers.uvs ), 2 ) );
  399. }
  400. var material, materialName, key;
  401. var materialNames = meshPayload.materials.materialNames;
  402. var createMultiMaterial = meshPayload.materials.multiMaterial;
  403. var multiMaterials = [];
  404. for ( key in materialNames ) {
  405. materialName = materialNames[ key ];
  406. material = this.materials[ materialName ];
  407. if ( createMultiMaterial ) multiMaterials.push( material );
  408. }
  409. if ( createMultiMaterial ) {
  410. material = multiMaterials;
  411. var materialGroups = meshPayload.materials.materialGroups;
  412. var materialGroup;
  413. for ( key in materialGroups ) {
  414. materialGroup = materialGroups[ key ];
  415. bufferGeometry.addGroup( materialGroup.start, materialGroup.count, materialGroup.index );
  416. }
  417. }
  418. var meshes = [];
  419. var mesh;
  420. var callbackOnMeshAlter = this.callbacks.onMeshAlter;
  421. var callbackOnMeshAlterResult;
  422. var useOrgMesh = true;
  423. var geometryType = Validator.verifyInput( meshPayload.geometryType, 0 );
  424. if ( Validator.isValid( callbackOnMeshAlter ) ) {
  425. callbackOnMeshAlterResult = callbackOnMeshAlter(
  426. {
  427. detail: {
  428. meshName: meshName,
  429. bufferGeometry: bufferGeometry,
  430. material: material,
  431. geometryType: geometryType
  432. }
  433. }
  434. );
  435. if ( Validator.isValid( callbackOnMeshAlterResult ) ) {
  436. if ( callbackOnMeshAlterResult.isDisregardMesh() ) {
  437. useOrgMesh = false;
  438. } else if ( callbackOnMeshAlterResult.providesAlteredMeshes() ) {
  439. for ( var i in callbackOnMeshAlterResult.meshes ) {
  440. meshes.push( callbackOnMeshAlterResult.meshes[ i ] );
  441. }
  442. useOrgMesh = false;
  443. }
  444. }
  445. }
  446. if ( useOrgMesh ) {
  447. if ( meshPayload.computeBoundingSphere ) bufferGeometry.computeBoundingSphere();
  448. if ( geometryType === 0 ) {
  449. mesh = new THREE.Mesh( bufferGeometry, material );
  450. } else if ( geometryType === 1) {
  451. mesh = new THREE.LineSegments( bufferGeometry, material );
  452. } else {
  453. mesh = new THREE.Points( bufferGeometry, material );
  454. }
  455. mesh.name = meshName;
  456. meshes.push( mesh );
  457. }
  458. var progressMessage;
  459. if ( Validator.isValid( meshes ) && meshes.length > 0 ) {
  460. var meshNames = [];
  461. for ( var i in meshes ) {
  462. mesh = meshes[ i ];
  463. meshNames[ i ] = mesh.name;
  464. }
  465. progressMessage = 'Adding mesh(es) (' + meshNames.length + ': ' + meshNames + ') from input mesh: ' + meshName;
  466. progressMessage += ' (' + ( meshPayload.progress.numericalValue * 100 ).toFixed( 2 ) + '%)';
  467. } else {
  468. progressMessage = 'Not adding mesh: ' + meshName;
  469. progressMessage += ' (' + ( meshPayload.progress.numericalValue * 100 ).toFixed( 2 ) + '%)';
  470. }
  471. var callbackOnProgress = this.callbacks.onProgress;
  472. if ( Validator.isValid( callbackOnProgress ) ) {
  473. var event = new CustomEvent( 'MeshBuilderEvent', {
  474. detail: {
  475. type: 'progress',
  476. modelName: meshPayload.params.meshName,
  477. text: progressMessage,
  478. numericalValue: meshPayload.progress.numericalValue
  479. }
  480. } );
  481. callbackOnProgress( event );
  482. }
  483. return meshes;
  484. };
  485. /**
  486. * Updates the materials with contained material objects (sync) or from alteration instructions (async).
  487. * @memberOf THREE.LoaderSupport.MeshBuilder
  488. *
  489. * @param {Object} materialPayload Material update instructions
  490. */
  491. MeshBuilder.prototype.updateMaterials = function ( materialPayload ) {
  492. var material, materialName;
  493. var materialCloneInstructions = materialPayload.materials.materialCloneInstructions;
  494. if ( Validator.isValid( materialCloneInstructions ) ) {
  495. var materialNameOrg = materialCloneInstructions.materialNameOrg;
  496. var materialOrg = this.materials[ materialNameOrg ];
  497. if ( Validator.isValid( materialNameOrg ) ) {
  498. material = materialOrg.clone();
  499. materialName = materialCloneInstructions.materialName;
  500. material.name = materialName;
  501. var materialProperties = materialCloneInstructions.materialProperties;
  502. for ( var key in materialProperties ) {
  503. if ( material.hasOwnProperty( key ) && materialProperties.hasOwnProperty( key ) ) material[ key ] = materialProperties[ key ];
  504. }
  505. this.materials[ materialName ] = material;
  506. } else {
  507. console.warn( 'Requested material "' + materialNameOrg + '" is not available!' );
  508. }
  509. }
  510. var materials = materialPayload.materials.serializedMaterials;
  511. if ( Validator.isValid( materials ) && Object.keys( materials ).length > 0 ) {
  512. var loader = new THREE.MaterialLoader();
  513. var materialJson;
  514. for ( materialName in materials ) {
  515. materialJson = materials[ materialName ];
  516. if ( Validator.isValid( materialJson ) ) {
  517. material = loader.parse( materialJson );
  518. if ( this.logging.enabled ) console.info( 'De-serialized material with name "' + materialName + '" will be added.' );
  519. this.materials[ materialName ] = material;
  520. }
  521. }
  522. }
  523. materials = materialPayload.materials.runtimeMaterials;
  524. if ( Validator.isValid( materials ) && Object.keys( materials ).length > 0 ) {
  525. for ( materialName in materials ) {
  526. material = materials[ materialName ];
  527. if ( this.logging.enabled ) console.info( 'Material with name "' + materialName + '" will be added.' );
  528. this.materials[ materialName ] = material;
  529. }
  530. }
  531. };
  532. /**
  533. * Returns the mapping object of material name and corresponding jsonified material.
  534. *
  535. * @returns {Object} Map of Materials in JSON representation
  536. */
  537. MeshBuilder.prototype.getMaterialsJSON = function () {
  538. var materialsJSON = {};
  539. var material;
  540. for ( var materialName in this.materials ) {
  541. material = this.materials[ materialName ];
  542. materialsJSON[ materialName ] = material.toJSON();
  543. }
  544. return materialsJSON;
  545. };
  546. /**
  547. * Returns the mapping object of material name and corresponding material.
  548. *
  549. * @returns {Object} Map of {@link THREE.Material}
  550. */
  551. MeshBuilder.prototype.getMaterials = function () {
  552. return this.materials;
  553. };
  554. return MeshBuilder;
  555. })();
  556. /**
  557. * Default implementation of the WorkerRunner responsible for creation and configuration of the parser within the worker.
  558. *
  559. * @class
  560. */
  561. THREE.LoaderSupport.WorkerRunnerRefImpl = (function () {
  562. function WorkerRunnerRefImpl() {
  563. var scope = this;
  564. var scopedRunner = function( event ) {
  565. scope.processMessage( event.data );
  566. };
  567. self.addEventListener( 'message', scopedRunner, false );
  568. }
  569. /**
  570. * Applies values from parameter object via set functions or via direct assignment.
  571. * @memberOf THREE.LoaderSupport.WorkerRunnerRefImpl
  572. *
  573. * @param {Object} parser The parser instance
  574. * @param {Object} params The parameter object
  575. */
  576. WorkerRunnerRefImpl.prototype.applyProperties = function ( parser, params ) {
  577. var property, funcName, values;
  578. for ( property in params ) {
  579. funcName = 'set' + property.substring( 0, 1 ).toLocaleUpperCase() + property.substring( 1 );
  580. values = params[ property ];
  581. if ( typeof parser[ funcName ] === 'function' ) {
  582. parser[ funcName ]( values );
  583. } else if ( parser.hasOwnProperty( property ) ) {
  584. parser[ property ] = values;
  585. }
  586. }
  587. };
  588. /**
  589. * Configures the Parser implementation according the supplied configuration object.
  590. * @memberOf THREE.LoaderSupport.WorkerRunnerRefImpl
  591. *
  592. * @param {Object} payload Raw mesh description (buffers, params, materials) used to build one to many meshes.
  593. */
  594. WorkerRunnerRefImpl.prototype.processMessage = function ( payload ) {
  595. if ( payload.cmd === 'run' ) {
  596. var callbacks = {
  597. callbackMeshBuilder: function ( payload ) {
  598. self.postMessage( payload );
  599. },
  600. callbackProgress: function ( text ) {
  601. if ( payload.logging.enabled && payload.logging.debug ) console.debug( 'WorkerRunner: progress: ' + text );
  602. }
  603. };
  604. // Parser is expected to be named as such
  605. var parser = new Parser();
  606. if ( typeof parser[ 'setLogging' ] === 'function' ) parser.setLogging( payload.logging.enabled, payload.logging.debug );
  607. this.applyProperties( parser, payload.params );
  608. this.applyProperties( parser, payload.materials );
  609. this.applyProperties( parser, callbacks );
  610. parser.workerScope = self;
  611. parser.parse( payload.data.input, payload.data.options );
  612. if ( payload.logging.enabled ) console.log( 'WorkerRunner: Run complete!' );
  613. callbacks.callbackMeshBuilder( {
  614. cmd: 'complete',
  615. msg: 'WorkerRunner completed run.'
  616. } );
  617. } else {
  618. console.error( 'WorkerRunner: Received unknown command: ' + payload.cmd );
  619. }
  620. };
  621. return WorkerRunnerRefImpl;
  622. })();
  623. /**
  624. * This class provides means to transform existing parser code into a web worker. It defines a simple communication protocol
  625. * which allows to configure the worker and receive raw mesh data during execution.
  626. * @class
  627. */
  628. THREE.LoaderSupport.WorkerSupport = (function () {
  629. var WORKER_SUPPORT_VERSION = '2.2.0';
  630. var Validator = THREE.LoaderSupport.Validator;
  631. var LoaderWorker = (function () {
  632. function LoaderWorker() {
  633. this._reset();
  634. }
  635. LoaderWorker.prototype._reset = function () {
  636. this.logging = {
  637. enabled: true,
  638. debug: false
  639. };
  640. this.worker = null;
  641. this.runnerImplName = null;
  642. this.callbacks = {
  643. meshBuilder: null,
  644. onLoad: null
  645. };
  646. this.terminateRequested = false;
  647. this.queuedMessage = null;
  648. this.started = false;
  649. this.forceCopy = false;
  650. };
  651. LoaderWorker.prototype.setLogging = function ( enabled, debug ) {
  652. this.logging.enabled = enabled === true;
  653. this.logging.debug = debug === true;
  654. };
  655. LoaderWorker.prototype.setForceCopy = function ( forceCopy ) {
  656. this.forceCopy = forceCopy === true;
  657. };
  658. LoaderWorker.prototype.initWorker = function ( code, runnerImplName ) {
  659. this.runnerImplName = runnerImplName;
  660. var blob = new Blob( [ code ], { type: 'application/javascript' } );
  661. this.worker = new Worker( window.URL.createObjectURL( blob ) );
  662. this.worker.onmessage = this._receiveWorkerMessage;
  663. // set referemce to this, then processing in worker scope within "_receiveWorkerMessage" can access members
  664. this.worker.runtimeRef = this;
  665. // process stored queuedMessage
  666. this._postMessage();
  667. };
  668. /**
  669. * Executed in worker scope
  670. */
  671. LoaderWorker.prototype._receiveWorkerMessage = function ( e ) {
  672. var payload = e.data;
  673. switch ( payload.cmd ) {
  674. case 'meshData':
  675. case 'materialData':
  676. case 'imageData':
  677. this.runtimeRef.callbacks.meshBuilder( payload );
  678. break;
  679. case 'complete':
  680. this.runtimeRef.queuedMessage = null;
  681. this.started = false;
  682. this.runtimeRef.callbacks.onLoad( payload.msg );
  683. if ( this.runtimeRef.terminateRequested ) {
  684. if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run is complete. Terminating application on request!' );
  685. this.runtimeRef._terminate();
  686. }
  687. break;
  688. case 'error':
  689. console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Reported error: ' + payload.msg );
  690. this.runtimeRef.queuedMessage = null;
  691. this.started = false;
  692. this.runtimeRef.callbacks.onLoad( payload.msg );
  693. if ( this.runtimeRef.terminateRequested ) {
  694. if ( this.runtimeRef.logging.enabled ) console.info( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Run reported error. Terminating application on request!' );
  695. this.runtimeRef._terminate();
  696. }
  697. break;
  698. default:
  699. console.error( 'WorkerSupport [' + this.runtimeRef.runnerImplName + ']: Received unknown command: ' + payload.cmd );
  700. break;
  701. }
  702. };
  703. LoaderWorker.prototype.setCallbacks = function ( meshBuilder, onLoad ) {
  704. this.callbacks.meshBuilder = Validator.verifyInput( meshBuilder, this.callbacks.meshBuilder );
  705. this.callbacks.onLoad = Validator.verifyInput( onLoad, this.callbacks.onLoad );
  706. };
  707. LoaderWorker.prototype.run = function( payload ) {
  708. if ( Validator.isValid( this.queuedMessage ) ) {
  709. console.warn( 'Already processing message. Rejecting new run instruction' );
  710. return;
  711. } else {
  712. this.queuedMessage = payload;
  713. this.started = true;
  714. }
  715. if ( ! Validator.isValid( this.callbacks.meshBuilder ) ) throw 'Unable to run as no "MeshBuilder" callback is set.';
  716. if ( ! Validator.isValid( this.callbacks.onLoad ) ) throw 'Unable to run as no "onLoad" callback is set.';
  717. if ( payload.cmd !== 'run' ) payload.cmd = 'run';
  718. if ( Validator.isValid( payload.logging ) ) {
  719. payload.logging.enabled = payload.logging.enabled === true;
  720. payload.logging.debug = payload.logging.debug === true;
  721. } else {
  722. payload.logging = {
  723. enabled: true,
  724. debug: false
  725. }
  726. }
  727. this._postMessage();
  728. };
  729. LoaderWorker.prototype._postMessage = function () {
  730. if ( Validator.isValid( this.queuedMessage ) && Validator.isValid( this.worker ) ) {
  731. if ( this.queuedMessage.data.input instanceof ArrayBuffer ) {
  732. var content;
  733. if ( this.forceCopy ) {
  734. content = this.queuedMessage.data.input.slice( 0 );
  735. } else {
  736. content = this.queuedMessage.data.input;
  737. }
  738. this.worker.postMessage( this.queuedMessage, [ content ] );
  739. } else {
  740. this.worker.postMessage( this.queuedMessage );
  741. }
  742. }
  743. };
  744. LoaderWorker.prototype.setTerminateRequested = function ( terminateRequested ) {
  745. this.terminateRequested = terminateRequested === true;
  746. if ( this.terminateRequested && Validator.isValid( this.worker ) && ! Validator.isValid( this.queuedMessage ) && this.started ) {
  747. if ( this.logging.enabled ) console.info( 'Worker is terminated immediately as it is not running!' );
  748. this._terminate();
  749. }
  750. };
  751. LoaderWorker.prototype._terminate = function () {
  752. this.worker.terminate();
  753. this._reset();
  754. };
  755. return LoaderWorker;
  756. })();
  757. function WorkerSupport() {
  758. console.info( 'Using THREE.LoaderSupport.WorkerSupport version: ' + WORKER_SUPPORT_VERSION );
  759. this.logging = {
  760. enabled: true,
  761. debug: false
  762. };
  763. // check worker support first
  764. if ( window.Worker === undefined ) throw "This browser does not support web workers!";
  765. if ( window.Blob === undefined ) throw "This browser does not support Blob!";
  766. if ( typeof window.URL.createObjectURL !== 'function' ) throw "This browser does not support Object creation from URL!";
  767. this.loaderWorker = new LoaderWorker();
  768. }
  769. /**
  770. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  771. * @memberOf THREE.LoaderSupport.WorkerSupport
  772. *
  773. * @param {boolean} enabled True or false.
  774. * @param {boolean} debug True or false.
  775. */
  776. WorkerSupport.prototype.setLogging = function ( enabled, debug ) {
  777. this.logging.enabled = enabled === true;
  778. this.logging.debug = debug === true;
  779. this.loaderWorker.setLogging( this.logging.enabled, this.logging.debug );
  780. };
  781. /**
  782. * Forces all ArrayBuffers to be transferred to worker to be copied.
  783. * @memberOf THREE.LoaderSupport.WorkerSupport
  784. *
  785. * @param {boolean} forceWorkerDataCopy True or false.
  786. */
  787. WorkerSupport.prototype.setForceWorkerDataCopy = function ( forceWorkerDataCopy ) {
  788. this.loaderWorker.setForceCopy( forceWorkerDataCopy );
  789. };
  790. /**
  791. * Validate the status of worker code and the derived worker.
  792. * @memberOf THREE.LoaderSupport.WorkerSupport
  793. *
  794. * @param {Function} functionCodeBuilder Function that is invoked with funcBuildObject and funcBuildSingleton that allows stringification of objects and singletons.
  795. * @param {String} parserName Name of the Parser object
  796. * @param {String[]} libLocations URL of libraries that shall be added to worker code relative to libPath
  797. * @param {String} libPath Base path used for loading libraries
  798. * @param {THREE.LoaderSupport.WorkerRunnerRefImpl} runnerImpl The default worker parser wrapper implementation (communication and execution). An extended class could be passed here.
  799. */
  800. WorkerSupport.prototype.validate = function ( functionCodeBuilder, parserName, libLocations, libPath, runnerImpl ) {
  801. if ( Validator.isValid( this.loaderWorker.worker ) ) return;
  802. if ( this.logging.enabled ) {
  803. console.info( 'WorkerSupport: Building worker code...' );
  804. console.time( 'buildWebWorkerCode' );
  805. }
  806. if ( Validator.isValid( runnerImpl ) ) {
  807. if ( this.logging.enabled ) console.info( 'WorkerSupport: Using "' + runnerImpl.name + '" as Runner class for worker.' );
  808. } else {
  809. runnerImpl = THREE.LoaderSupport.WorkerRunnerRefImpl;
  810. if ( this.logging.enabled ) console.info( 'WorkerSupport: Using DEFAULT "THREE.LoaderSupport.WorkerRunnerRefImpl" as Runner class for worker.' );
  811. }
  812. var userWorkerCode = functionCodeBuilder( buildObject, buildSingleton );
  813. userWorkerCode += 'var Parser = '+ parserName + ';\n\n';
  814. userWorkerCode += buildSingleton( runnerImpl.name, runnerImpl );
  815. userWorkerCode += 'new ' + runnerImpl.name + '();\n\n';
  816. var scope = this;
  817. if ( Validator.isValid( libLocations ) && libLocations.length > 0 ) {
  818. var libsContent = '';
  819. var loadAllLibraries = function ( path, locations ) {
  820. if ( locations.length === 0 ) {
  821. scope.loaderWorker.initWorker( libsContent + userWorkerCode, runnerImpl.name );
  822. if ( scope.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' );
  823. } else {
  824. var loadedLib = function ( contentAsString ) {
  825. libsContent += contentAsString;
  826. loadAllLibraries( path, locations );
  827. };
  828. var fileLoader = new THREE.FileLoader();
  829. fileLoader.setPath( path );
  830. fileLoader.setResponseType( 'text' );
  831. fileLoader.load( locations[ 0 ], loadedLib );
  832. locations.shift();
  833. }
  834. };
  835. loadAllLibraries( libPath, libLocations );
  836. } else {
  837. this.loaderWorker.initWorker( userWorkerCode, runnerImpl.name );
  838. if ( this.logging.enabled ) console.timeEnd( 'buildWebWorkerCode' );
  839. }
  840. };
  841. /**
  842. * Specify functions that should be build when new raw mesh data becomes available and when the parser is finished.
  843. * @memberOf THREE.LoaderSupport.WorkerSupport
  844. *
  845. * @param {Function} meshBuilder The mesh builder function. Default is {@link THREE.LoaderSupport.MeshBuilder}.
  846. * @param {Function} onLoad The function that is called when parsing is complete.
  847. */
  848. WorkerSupport.prototype.setCallbacks = function ( meshBuilder, onLoad ) {
  849. this.loaderWorker.setCallbacks( meshBuilder, onLoad );
  850. };
  851. /**
  852. * Runs the parser with the provided configuration.
  853. * @memberOf THREE.LoaderSupport.WorkerSupport
  854. *
  855. * @param {Object} payload Raw mesh description (buffers, params, materials) used to build one to many meshes.
  856. */
  857. WorkerSupport.prototype.run = function ( payload ) {
  858. this.loaderWorker.run( payload );
  859. };
  860. /**
  861. * Request termination of worker once parser is finished.
  862. * @memberOf THREE.LoaderSupport.WorkerSupport
  863. *
  864. * @param {boolean} terminateRequested True or false.
  865. */
  866. WorkerSupport.prototype.setTerminateRequested = function ( terminateRequested ) {
  867. this.loaderWorker.setTerminateRequested( terminateRequested );
  868. };
  869. var buildObject = function ( fullName, object ) {
  870. var objectString = fullName + ' = {\n';
  871. var part;
  872. for ( var name in object ) {
  873. part = object[ name ];
  874. if ( typeof( part ) === 'string' || part instanceof String ) {
  875. part = part.replace( '\n', '\\n' );
  876. part = part.replace( '\r', '\\r' );
  877. objectString += '\t' + name + ': "' + part + '",\n';
  878. } else if ( part instanceof Array ) {
  879. objectString += '\t' + name + ': [' + part + '],\n';
  880. } else if ( Number.isInteger( part ) ) {
  881. objectString += '\t' + name + ': ' + part + ',\n';
  882. } else if ( typeof part === 'function' ) {
  883. objectString += '\t' + name + ': ' + part + ',\n';
  884. }
  885. }
  886. objectString += '}\n\n';
  887. return objectString;
  888. };
  889. var buildSingleton = function ( fullName, object, internalName, basePrototypeName, ignoreFunctions ) {
  890. var objectString = '';
  891. var objectName = ( Validator.isValid( internalName ) ) ? internalName : object.name;
  892. var funcString, objectPart, constructorString;
  893. ignoreFunctions = Validator.verifyInput( ignoreFunctions, [] );
  894. for ( var name in object.prototype ) {
  895. objectPart = object.prototype[ name ];
  896. if ( name === 'constructor' ) {
  897. funcString = objectPart.toString();
  898. funcString = funcString.replace( 'function', '' );
  899. constructorString = '\tfunction ' + objectName + funcString + ';\n\n';
  900. } else if ( typeof objectPart === 'function' ) {
  901. if ( ignoreFunctions.indexOf( name ) < 0 ) {
  902. funcString = objectPart.toString();
  903. objectString += '\t' + objectName + '.prototype.' + name + ' = ' + funcString + ';\n\n';
  904. }
  905. }
  906. }
  907. objectString += '\treturn ' + objectName + ';\n';
  908. objectString += '})();\n\n';
  909. var inheritanceBlock = '';
  910. if ( Validator.isValid( basePrototypeName ) ) {
  911. inheritanceBlock += '\n';
  912. inheritanceBlock += objectName + '.prototype = Object.create( ' + basePrototypeName + '.prototype );\n';
  913. inheritanceBlock += objectName + '.constructor = ' + objectName + ';\n';
  914. inheritanceBlock += '\n';
  915. }
  916. if ( ! Validator.isValid( constructorString ) ) {
  917. constructorString = fullName + ' = (function () {\n\n';
  918. constructorString += inheritanceBlock + '\t' + object.prototype.constructor.toString() + '\n\n';
  919. objectString = constructorString + objectString;
  920. } else {
  921. objectString = fullName + ' = (function () {\n\n' + inheritanceBlock + constructorString + objectString;
  922. }
  923. return objectString;
  924. };
  925. return WorkerSupport;
  926. })();
  927. /**
  928. * Orchestrate loading of multiple OBJ files/data from an instruction queue with a configurable amount of workers (1-16).
  929. * Workflow:
  930. * prepareWorkers
  931. * enqueueForRun
  932. * processQueue
  933. * tearDown (to force stop)
  934. *
  935. * @class
  936. *
  937. * @param {string} classDef Class definition to be used for construction
  938. */
  939. THREE.LoaderSupport.WorkerDirector = (function () {
  940. var LOADER_WORKER_DIRECTOR_VERSION = '2.2.1';
  941. var Validator = THREE.LoaderSupport.Validator;
  942. var MAX_WEB_WORKER = 16;
  943. var MAX_QUEUE_SIZE = 8192;
  944. function WorkerDirector( classDef ) {
  945. console.info( 'Using THREE.LoaderSupport.WorkerDirector version: ' + LOADER_WORKER_DIRECTOR_VERSION );
  946. this.logging = {
  947. enabled: true,
  948. debug: false
  949. };
  950. this.maxQueueSize = MAX_QUEUE_SIZE ;
  951. this.maxWebWorkers = MAX_WEB_WORKER;
  952. this.crossOrigin = 'anonymous';
  953. if ( ! Validator.isValid( classDef ) ) throw 'Provided invalid classDef: ' + classDef;
  954. this.workerDescription = {
  955. classDef: classDef,
  956. globalCallbacks: {},
  957. workerSupports: {},
  958. forceWorkerDataCopy: true
  959. };
  960. this.objectsCompleted = 0;
  961. this.instructionQueue = [];
  962. this.instructionQueuePointer = 0;
  963. this.callbackOnFinishedProcessing = null;
  964. }
  965. /**
  966. * Enable or disable logging in general (except warn and error), plus enable or disable debug logging.
  967. * @memberOf THREE.LoaderSupport.WorkerDirector
  968. *
  969. * @param {boolean} enabled True or false.
  970. * @param {boolean} debug True or false.
  971. */
  972. WorkerDirector.prototype.setLogging = function ( enabled, debug ) {
  973. this.logging.enabled = enabled === true;
  974. this.logging.debug = debug === true;
  975. };
  976. /**
  977. * Returns the maximum length of the instruction queue.
  978. * @memberOf THREE.LoaderSupport.WorkerDirector
  979. *
  980. * @returns {number}
  981. */
  982. WorkerDirector.prototype.getMaxQueueSize = function () {
  983. return this.maxQueueSize;
  984. };
  985. /**
  986. * Returns the maximum number of workers.
  987. * @memberOf THREE.LoaderSupport.WorkerDirector
  988. *
  989. * @returns {number}
  990. */
  991. WorkerDirector.prototype.getMaxWebWorkers = function () {
  992. return this.maxWebWorkers;
  993. };
  994. /**
  995. * Sets the CORS string to be used.
  996. * @memberOf THREE.LoaderSupport.WorkerDirector
  997. *
  998. * @param {string} crossOrigin CORS value
  999. */
  1000. WorkerDirector.prototype.setCrossOrigin = function ( crossOrigin ) {
  1001. this.crossOrigin = crossOrigin;
  1002. };
  1003. /**
  1004. * Forces all ArrayBuffers to be transferred to worker to be copied.
  1005. * @memberOf THREE.LoaderSupport.WorkerDirector
  1006. *
  1007. * @param {boolean} forceWorkerDataCopy True or false.
  1008. */
  1009. WorkerDirector.prototype.setForceWorkerDataCopy = function ( forceWorkerDataCopy ) {
  1010. this.workerDescription.forceWorkerDataCopy = forceWorkerDataCopy === true;
  1011. };
  1012. /**
  1013. * Create or destroy workers according limits. Set the name and register callbacks for dynamically created web workers.
  1014. * @memberOf THREE.LoaderSupport.WorkerDirector
  1015. *
  1016. * @param {THREE.OBJLoader2.WWOBJLoader2.PrepDataCallbacks} globalCallbacks Register global callbacks used by all web workers
  1017. * @param {number} maxQueueSize Set the maximum size of the instruction queue (1-1024)
  1018. * @param {number} maxWebWorkers Set the maximum amount of workers (1-16)
  1019. */
  1020. WorkerDirector.prototype.prepareWorkers = function ( globalCallbacks, maxQueueSize, maxWebWorkers ) {
  1021. if ( Validator.isValid( globalCallbacks ) ) this.workerDescription.globalCallbacks = globalCallbacks;
  1022. this.maxQueueSize = Math.min( maxQueueSize, MAX_QUEUE_SIZE );
  1023. this.maxWebWorkers = Math.min( maxWebWorkers, MAX_WEB_WORKER );
  1024. this.maxWebWorkers = Math.min( this.maxWebWorkers, this.maxQueueSize );
  1025. this.objectsCompleted = 0;
  1026. this.instructionQueue = [];
  1027. this.instructionQueuePointer = 0;
  1028. for ( var instanceNo = 0; instanceNo < this.maxWebWorkers; instanceNo++ ) {
  1029. var workerSupport = new THREE.LoaderSupport.WorkerSupport();
  1030. workerSupport.setLogging( this.logging.enabled, this.logging.debug );
  1031. workerSupport.setForceWorkerDataCopy( this.workerDescription.forceWorkerDataCopy );
  1032. this.workerDescription.workerSupports[ instanceNo ] = {
  1033. instanceNo: instanceNo,
  1034. inUse: false,
  1035. terminateRequested: false,
  1036. workerSupport: workerSupport,
  1037. loader: null
  1038. };
  1039. }
  1040. };
  1041. /**
  1042. * Store run instructions in internal instructionQueue.
  1043. * @memberOf THREE.LoaderSupport.WorkerDirector
  1044. *
  1045. * @param {THREE.LoaderSupport.PrepData} prepData
  1046. */
  1047. WorkerDirector.prototype.enqueueForRun = function ( prepData ) {
  1048. if ( this.instructionQueue.length < this.maxQueueSize ) {
  1049. this.instructionQueue.push( prepData );
  1050. }
  1051. };
  1052. /**
  1053. * Returns if any workers are running.
  1054. *
  1055. * @memberOf THREE.LoaderSupport.WorkerDirector
  1056. * @returns {boolean}
  1057. */
  1058. WorkerDirector.prototype.isRunning = function () {
  1059. var wsKeys = Object.keys( this.workerDescription.workerSupports );
  1060. return ( ( this.instructionQueue.length > 0 && this.instructionQueuePointer < this.instructionQueue.length ) || wsKeys.length > 0 );
  1061. };
  1062. /**
  1063. * Process the instructionQueue until it is depleted.
  1064. * @memberOf THREE.LoaderSupport.WorkerDirector
  1065. */
  1066. WorkerDirector.prototype.processQueue = function () {
  1067. var prepData, supportDesc;
  1068. for ( var instanceNo in this.workerDescription.workerSupports ) {
  1069. supportDesc = this.workerDescription.workerSupports[ instanceNo ];
  1070. if ( ! supportDesc.inUse ) {
  1071. if ( this.instructionQueuePointer < this.instructionQueue.length ) {
  1072. prepData = this.instructionQueue[ this.instructionQueuePointer ];
  1073. this._kickWorkerRun( prepData, supportDesc );
  1074. this.instructionQueuePointer++;
  1075. } else {
  1076. this._deregister( supportDesc );
  1077. }
  1078. }
  1079. }
  1080. if ( ! this.isRunning() && this.callbackOnFinishedProcessing !== null ) {
  1081. this.callbackOnFinishedProcessing();
  1082. this.callbackOnFinishedProcessing = null;
  1083. }
  1084. };
  1085. WorkerDirector.prototype._kickWorkerRun = function( prepData, supportDesc ) {
  1086. supportDesc.inUse = true;
  1087. supportDesc.workerSupport.setTerminateRequested( supportDesc.terminateRequested );
  1088. if ( this.logging.enabled ) console.info( '\nAssigning next item from queue to worker (queue length: ' + this.instructionQueue.length + ')\n\n' );
  1089. var scope = this;
  1090. var prepDataCallbacks = prepData.getCallbacks();
  1091. var globalCallbacks = this.workerDescription.globalCallbacks;
  1092. var wrapperOnLoad = function ( event ) {
  1093. if ( Validator.isValid( globalCallbacks.onLoad ) ) globalCallbacks.onLoad( event );
  1094. if ( Validator.isValid( prepDataCallbacks.onLoad ) ) prepDataCallbacks.onLoad( event );
  1095. scope.objectsCompleted++;
  1096. supportDesc.inUse = false;
  1097. scope.processQueue();
  1098. };
  1099. var wrapperOnProgress = function ( event ) {
  1100. if ( Validator.isValid( globalCallbacks.onProgress ) ) globalCallbacks.onProgress( event );
  1101. if ( Validator.isValid( prepDataCallbacks.onProgress ) ) prepDataCallbacks.onProgress( event );
  1102. };
  1103. var wrapperOnMeshAlter = function ( event, override ) {
  1104. if ( Validator.isValid( globalCallbacks.onMeshAlter ) ) override = globalCallbacks.onMeshAlter( event, override );
  1105. if ( Validator.isValid( prepDataCallbacks.onMeshAlter ) ) override = globalCallbacks.onMeshAlter( event, override );
  1106. return override;
  1107. };
  1108. var wrapperOnLoadMaterials = function ( materials ) {
  1109. if ( Validator.isValid( globalCallbacks.onLoadMaterials ) ) materials = globalCallbacks.onLoadMaterials( materials );
  1110. if ( Validator.isValid( prepDataCallbacks.onLoadMaterials ) ) materials = prepDataCallbacks.onLoadMaterials( materials );
  1111. return materials;
  1112. };
  1113. supportDesc.loader = this._buildLoader( supportDesc.instanceNo );
  1114. var updatedCallbacks = new THREE.LoaderSupport.Callbacks();
  1115. updatedCallbacks.setCallbackOnLoad( wrapperOnLoad );
  1116. updatedCallbacks.setCallbackOnProgress( wrapperOnProgress );
  1117. updatedCallbacks.setCallbackOnMeshAlter( wrapperOnMeshAlter );
  1118. updatedCallbacks.setCallbackOnLoadMaterials( wrapperOnLoadMaterials );
  1119. prepData.callbacks = updatedCallbacks;
  1120. supportDesc.loader.run( prepData, supportDesc.workerSupport );
  1121. };
  1122. WorkerDirector.prototype._buildLoader = function ( instanceNo ) {
  1123. var classDef = this.workerDescription.classDef;
  1124. var loader = Object.create( classDef.prototype );
  1125. classDef.call( loader, THREE.DefaultLoadingManager );
  1126. // verify that all required functions are implemented
  1127. if ( ! loader.hasOwnProperty( 'instanceNo' ) ) throw classDef.name + ' has no property "instanceNo".';
  1128. loader.instanceNo = instanceNo;
  1129. if ( ! loader.hasOwnProperty( 'workerSupport' ) ) {
  1130. throw classDef.name + ' has no property "workerSupport".';
  1131. }
  1132. if ( typeof loader.run !== 'function' ) throw classDef.name + ' has no function "run".';
  1133. if ( ! loader.hasOwnProperty( 'callbacks' ) || ! Validator.isValid( loader.callbacks ) ) {
  1134. console.warn( classDef.name + ' has an invalid property "callbacks". Will change to "THREE.LoaderSupport.Callbacks"' );
  1135. loader.callbacks = new THREE.LoaderSupport.Callbacks();
  1136. }
  1137. return loader;
  1138. };
  1139. WorkerDirector.prototype._deregister = function ( supportDesc ) {
  1140. if ( Validator.isValid( supportDesc ) ) {
  1141. supportDesc.workerSupport.setTerminateRequested( true );
  1142. if ( this.logging.enabled ) console.info( 'Requested termination of worker #' + supportDesc.instanceNo + '.' );
  1143. var loaderCallbacks = supportDesc.loader.callbacks;
  1144. if ( Validator.isValid( loaderCallbacks.onProgress ) ) loaderCallbacks.onProgress( { detail: { text: '' } } );
  1145. delete this.workerDescription.workerSupports[ supportDesc.instanceNo ];
  1146. }
  1147. };
  1148. /**
  1149. * Terminate all workers.
  1150. * @memberOf THREE.LoaderSupport.WorkerDirector
  1151. *
  1152. * @param {callback} callbackOnFinishedProcessing Function called once all workers finished processing.
  1153. */
  1154. WorkerDirector.prototype.tearDown = function ( callbackOnFinishedProcessing ) {
  1155. if ( this.logging.enabled ) console.info( 'WorkerDirector received the deregister call. Terminating all workers!' );
  1156. this.instructionQueuePointer = this.instructionQueue.length;
  1157. this.callbackOnFinishedProcessing = Validator.verifyInput( callbackOnFinishedProcessing, null );
  1158. for ( var name in this.workerDescription.workerSupports ) {
  1159. this.workerDescription.workerSupports[ name ].terminateRequested = true;
  1160. }
  1161. };
  1162. return WorkerDirector;
  1163. })();