LoaderSupport.js 47 KB

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