OBJLoader2.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. import {
  6. FileLoader,
  7. Object3D,
  8. Loader
  9. } from "../../../build/three.module.js";
  10. import { OBJLoader2Parser } from "./obj2/worker/parallel/OBJLoader2Parser.js";
  11. import { MeshReceiver } from "./obj2/shared/MeshReceiver.js";
  12. import { MaterialHandler } from "./obj2/shared/MaterialHandler.js";
  13. /**
  14. * Creates a new OBJLoader2. Use it to load OBJ data from files or to parse OBJ data from arraybuffer or text.
  15. *
  16. * @param {LoadingManager} [manager] The loadingManager for the loader to use. Default is {@link LoadingManager}
  17. * @constructor
  18. */
  19. const OBJLoader2 = function ( manager ) {
  20. Loader.call( this, manager );
  21. this.parser = new OBJLoader2Parser();
  22. this.modelName = '';
  23. this.instanceNo = 0;
  24. this.baseObject3d = new Object3D();
  25. this.materialHandler = new MaterialHandler();
  26. this.meshReceiver = new MeshReceiver( this.materialHandler );
  27. // as OBJLoader2 is no longer derived from OBJLoader2Parser, we need to override the default onAssetAvailable callback
  28. let scope = this;
  29. let defaultOnAssetAvailable = function ( payload ) {
  30. scope._onAssetAvailable( payload );
  31. };
  32. this.parser.setCallbackOnAssetAvailable( defaultOnAssetAvailable );
  33. };
  34. OBJLoader2.OBJLOADER2_VERSION = '3.1.0';
  35. console.info( 'Using OBJLoader2 version: ' + OBJLoader2.OBJLOADER2_VERSION );
  36. OBJLoader2.prototype = Object.assign( Object.create( Loader.prototype ), {
  37. constructor: OBJLoader2,
  38. /**
  39. * See {@link OBJLoader2Parser.setLogging}
  40. * @return {OBJLoader2}
  41. */
  42. setLogging: function ( enabled, debug ) {
  43. this.parser.setLogging( enabled, debug );
  44. return this;
  45. },
  46. /**
  47. * See {@link OBJLoader2Parser.setMaterialPerSmoothingGroup}
  48. * @return {OBJLoader2}
  49. */
  50. setMaterialPerSmoothingGroup: function ( materialPerSmoothingGroup ) {
  51. this.parser.setMaterialPerSmoothingGroup( materialPerSmoothingGroup );
  52. return this;
  53. },
  54. /**
  55. * See {@link OBJLoader2Parser.setUseOAsMesh}
  56. * @return {OBJLoader2}
  57. */
  58. setUseOAsMesh: function ( useOAsMesh ) {
  59. this.parser.setUseOAsMesh( useOAsMesh );
  60. return this;
  61. },
  62. /**
  63. * See {@link OBJLoader2Parser.setUseIndices}
  64. * @return {OBJLoader2}
  65. */
  66. setUseIndices: function ( useIndices ) {
  67. this.parser.setUseIndices( useIndices );
  68. return this;
  69. },
  70. /**
  71. * See {@link OBJLoader2Parser.setDisregardNormals}
  72. * @return {OBJLoader2}
  73. */
  74. setDisregardNormals: function ( disregardNormals ) {
  75. this.parser.setDisregardNormals( disregardNormals );
  76. return this;
  77. },
  78. /**
  79. * Set the name of the model.
  80. *
  81. * @param {string} modelName
  82. * @return {OBJLoader2}
  83. */
  84. setModelName: function ( modelName ) {
  85. this.modelName = modelName ? modelName : this.modelName;
  86. return this;
  87. },
  88. /**
  89. * Set the node where the loaded objects will be attached directly.
  90. *
  91. * @param {Object3D} baseObject3d Object already attached to scenegraph where new meshes will be attached to
  92. * @return {OBJLoader2}
  93. */
  94. setBaseObject3d: function ( baseObject3d ) {
  95. this.baseObject3d = ( baseObject3d === undefined || baseObject3d === null ) ? this.baseObject3d : baseObject3d;
  96. return this;
  97. },
  98. /**
  99. * Add materials as associated array.
  100. *
  101. * @param {Object} materials Object with named {@link Material}
  102. * @return {OBJLoader2}
  103. */
  104. addMaterials: function ( materials ) {
  105. this.materialHandler.addMaterials( materials );
  106. return this;
  107. },
  108. /**
  109. * See {@link OBJLoader2Parser.setCallbackOnAssetAvailable}
  110. * @return {OBJLoader2}
  111. */
  112. setCallbackOnAssetAvailable: function ( onAssetAvailable ) {
  113. this.parser.setCallbackOnAssetAvailable( onAssetAvailable );
  114. return this;
  115. },
  116. /**
  117. * See {@link OBJLoader2Parser.setCallbackOnProgress}
  118. * @return {OBJLoader2}
  119. */
  120. setCallbackOnProgress: function ( onProgress ) {
  121. this.parser.setCallbackOnProgress( onProgress );
  122. return this;
  123. },
  124. /**
  125. * See {@link OBJLoader2Parser.setCallbackOnError}
  126. * @return {OBJLoader2}
  127. */
  128. setCallbackOnError: function ( onError ) {
  129. this.parser.setCallbackOnError( onError );
  130. return this;
  131. },
  132. /**
  133. * See {@link OBJLoader2Parser.setCallbackOnLoad}
  134. * @return {OBJLoader2}
  135. */
  136. setCallbackOnLoad: function ( onLoad ) {
  137. this.parser.setCallbackOnLoad( onLoad );
  138. return this;
  139. },
  140. /**
  141. * Register a function that is called once a single mesh is available and it could be altered by the supplied function.
  142. *
  143. * @param {Function} [onMeshAlter]
  144. * @return {OBJLoader2}
  145. */
  146. setCallbackOnMeshAlter: function ( onMeshAlter ) {
  147. this.meshReceiver._setCallbacks( this.parser.callbacks.onProgress, onMeshAlter );
  148. return this;
  149. },
  150. /**
  151. * Register a function that is called once all materials have been loaded and they could be altered by the supplied function.
  152. *
  153. * @param {Function} [onLoadMaterials]
  154. * @return {OBJLoader2}
  155. */
  156. setCallbackOnLoadMaterials: function ( onLoadMaterials ) {
  157. this.materialHandler._setCallbacks( onLoadMaterials );
  158. return this;
  159. },
  160. /**
  161. * Use this convenient method to load a file at the given URL. By default the fileLoader uses an ArrayBuffer.
  162. *
  163. * @param {string} url A string containing the path/URL of the file to be loaded.
  164. * @param {function} onLoad A function to be called after loading is successfully completed. The function receives loaded Object3D as an argument.
  165. * @param {function} [onFileLoadProgress] A function to be called while the loading is in progress. The argument will be the XMLHttpRequest instance, which contains total and Integer bytes.
  166. * @param {function} [onError] A function to be called if an error occurs during loading. The function receives the error as an argument.
  167. * @param {function} [onMeshAlter] Called after every single mesh is made available by the parser
  168. */
  169. load: function ( url, onLoad, onFileLoadProgress, onError, onMeshAlter ) {
  170. let scope = this;
  171. if ( onLoad === null || onLoad === undefined || ! ( onLoad instanceof Function ) ) {
  172. let errorMessage = 'onLoad is not a function! Aborting...';
  173. scope.parser.callbacks.onError( errorMessage );
  174. throw errorMessage;
  175. } else {
  176. this.parser.setCallbackOnLoad( onLoad );
  177. }
  178. if ( onError === null || onError === undefined || ! ( onError instanceof Function ) ) {
  179. onError = function ( event ) {
  180. let errorMessage = event;
  181. if ( event.currentTarget && event.currentTarget.statusText !== null ) {
  182. errorMessage = 'Error occurred while downloading!\nurl: ' + event.currentTarget.responseURL + '\nstatus: ' + event.currentTarget.statusText;
  183. }
  184. scope.parser.callbacks.onError( errorMessage );
  185. };
  186. }
  187. if ( ! url ) {
  188. onError( 'An invalid url was provided. Unable to continue!' );
  189. }
  190. let urlFull = new URL( url, window.location.href ).href;
  191. let filename = urlFull;
  192. let urlParts = urlFull.split( '/' );
  193. if ( urlParts.length > 2 ) {
  194. filename = urlParts[ urlParts.length - 1 ];
  195. let urlPartsPath = urlParts.slice( 0, urlParts.length - 1 ).join( '/' ) + '/';
  196. if ( urlPartsPath !== undefined && urlPartsPath !== null ) this.path = urlPartsPath;
  197. }
  198. if ( onFileLoadProgress === null || onFileLoadProgress === undefined || ! ( onFileLoadProgress instanceof Function ) ) {
  199. let numericalValueRef = 0;
  200. let numericalValue = 0;
  201. onFileLoadProgress = function ( event ) {
  202. if ( ! event.lengthComputable ) return;
  203. numericalValue = event.loaded / event.total;
  204. if ( numericalValue > numericalValueRef ) {
  205. numericalValueRef = numericalValue;
  206. let output = 'Download of "' + url + '": ' + ( numericalValue * 100 ).toFixed( 2 ) + '%';
  207. scope.parser.callbacks.onProgress( 'progressLoad', output, numericalValue );
  208. }
  209. };
  210. }
  211. this.setCallbackOnMeshAlter( onMeshAlter );
  212. let fileLoaderOnLoad = function ( content ) {
  213. scope.parser.callbacks.onLoad( scope.parse( content ), "OBJLoader2#load: Parsing completed" );
  214. };
  215. let fileLoader = new FileLoader( this.manager );
  216. fileLoader.setPath( this.path || this.resourcePath );
  217. fileLoader.setResponseType( 'arraybuffer' );
  218. fileLoader.load( filename, fileLoaderOnLoad, onFileLoadProgress, onError );
  219. },
  220. /**
  221. * Parses OBJ data synchronously from arraybuffer or string and returns the {@link Object3D}.
  222. *
  223. * @param {arraybuffer|string} content OBJ data as Uint8Array or String
  224. * @return {Object3D}
  225. */
  226. parse: function ( content ) {
  227. // fast-fail in case of illegal data
  228. if ( content === null || content === undefined ) {
  229. throw 'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing';
  230. }
  231. if ( this.parser.logging.enabled ) {
  232. console.time( 'OBJLoader parse: ' + this.modelName );
  233. }
  234. // Create default materials beforehand, but do not override previously set materials (e.g. during init)
  235. this.materialHandler.createDefaultMaterials( false );
  236. // code works directly on the material references, parser clear its materials before updating
  237. this.parser.setMaterials( this.materialHandler.getMaterials() );
  238. if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) {
  239. if ( this.parser.logging.enabled ) console.info( 'Parsing arrayBuffer...' );
  240. this.parser.execute( content );
  241. } else if ( typeof ( content ) === 'string' || content instanceof String ) {
  242. if ( this.parser.logging.enabled ) console.info( 'Parsing text...' );
  243. this.parser.executeLegacy( content );
  244. } else {
  245. this.parser.callbacks.onError( 'Provided content was neither of type String nor Uint8Array! Aborting...' );
  246. }
  247. if ( this.parser.logging.enabled ) {
  248. console.timeEnd( 'OBJLoader parse: ' + this.modelName );
  249. }
  250. return this.baseObject3d;
  251. },
  252. _onAssetAvailable: function ( payload ) {
  253. if ( payload.cmd !== 'assetAvailable' ) return;
  254. if ( payload.type === 'mesh' ) {
  255. let meshes = this.meshReceiver.buildMeshes( payload );
  256. for ( let mesh of meshes ) {
  257. this.baseObject3d.add( mesh );
  258. }
  259. } else if ( payload.type === 'material' ) {
  260. this.materialHandler.addPayloadMaterials( payload );
  261. }
  262. }
  263. } );
  264. export { OBJLoader2 };