LoaderSupport.js 36 KB

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