2
0

LoaderSupport.js 44 KB

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