LoaderSupport.js 43 KB

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