2
0

LoaderSupport.js 45 KB

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