OBJLoader2.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  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.1';
  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. * @param overrideExisting boolean Override existing material
  103. * @return {OBJLoader2}
  104. */
  105. addMaterials: function ( materials, overrideExisting ) {
  106. this.materialHandler.addMaterials( materials, overrideExisting );
  107. return this;
  108. },
  109. /**
  110. * See {@link OBJLoader2Parser.setCallbackOnAssetAvailable}
  111. * @return {OBJLoader2}
  112. */
  113. setCallbackOnAssetAvailable: function ( onAssetAvailable ) {
  114. this.parser.setCallbackOnAssetAvailable( onAssetAvailable );
  115. return this;
  116. },
  117. /**
  118. * See {@link OBJLoader2Parser.setCallbackOnProgress}
  119. * @return {OBJLoader2}
  120. */
  121. setCallbackOnProgress: function ( onProgress ) {
  122. this.parser.setCallbackOnProgress( onProgress );
  123. return this;
  124. },
  125. /**
  126. * See {@link OBJLoader2Parser.setCallbackOnError}
  127. * @return {OBJLoader2}
  128. */
  129. setCallbackOnError: function ( onError ) {
  130. this.parser.setCallbackOnError( onError );
  131. return this;
  132. },
  133. /**
  134. * See {@link OBJLoader2Parser.setCallbackOnLoad}
  135. * @return {OBJLoader2}
  136. */
  137. setCallbackOnLoad: function ( onLoad ) {
  138. this.parser.setCallbackOnLoad( onLoad );
  139. return this;
  140. },
  141. /**
  142. * Register a function that is called once a single mesh is available and it could be altered by the supplied function.
  143. *
  144. * @param {Function} [onMeshAlter]
  145. * @return {OBJLoader2}
  146. */
  147. setCallbackOnMeshAlter: function ( onMeshAlter ) {
  148. this.meshReceiver._setCallbacks( this.parser.callbacks.onProgress, onMeshAlter );
  149. return this;
  150. },
  151. /**
  152. * Register a function that is called once all materials have been loaded and they could be altered by the supplied function.
  153. *
  154. * @param {Function} [onLoadMaterials]
  155. * @return {OBJLoader2}
  156. */
  157. setCallbackOnLoadMaterials: function ( onLoadMaterials ) {
  158. this.materialHandler._setCallbacks( onLoadMaterials );
  159. return this;
  160. },
  161. /**
  162. * Use this convenient method to load a file at the given URL. By default the fileLoader uses an ArrayBuffer.
  163. *
  164. * @param {string} url A string containing the path/URL of the file to be loaded.
  165. * @param {function} onLoad A function to be called after loading is successfully completed. The function receives loaded Object3D as an argument.
  166. * @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.
  167. * @param {function} [onError] A function to be called if an error occurs during loading. The function receives the error as an argument.
  168. * @param {function} [onMeshAlter] Called after every single mesh is made available by the parser
  169. */
  170. load: function ( url, onLoad, onFileLoadProgress, onError, onMeshAlter ) {
  171. let scope = this;
  172. if ( onLoad === null || onLoad === undefined || ! ( onLoad instanceof Function ) ) {
  173. let errorMessage = 'onLoad is not a function! Aborting...';
  174. scope.parser.callbacks.onError( errorMessage );
  175. throw errorMessage;
  176. } else {
  177. this.parser.setCallbackOnLoad( onLoad );
  178. }
  179. if ( onError === null || onError === undefined || ! ( onError instanceof Function ) ) {
  180. onError = function ( event ) {
  181. let errorMessage = event;
  182. if ( event.currentTarget && event.currentTarget.statusText !== null ) {
  183. errorMessage = 'Error occurred while downloading!\nurl: ' + event.currentTarget.responseURL + '\nstatus: ' + event.currentTarget.statusText;
  184. }
  185. scope.parser.callbacks.onError( errorMessage );
  186. };
  187. }
  188. if ( ! url ) {
  189. onError( 'An invalid url was provided. Unable to continue!' );
  190. }
  191. let urlFull = new URL( url, window.location.href ).href;
  192. let filename = urlFull;
  193. let urlParts = urlFull.split( '/' );
  194. if ( urlParts.length > 2 ) {
  195. filename = urlParts[ urlParts.length - 1 ];
  196. let urlPartsPath = urlParts.slice( 0, urlParts.length - 1 ).join( '/' ) + '/';
  197. if ( urlPartsPath !== undefined && urlPartsPath !== null ) this.path = urlPartsPath;
  198. }
  199. if ( onFileLoadProgress === null || onFileLoadProgress === undefined || ! ( onFileLoadProgress instanceof Function ) ) {
  200. let numericalValueRef = 0;
  201. let numericalValue = 0;
  202. onFileLoadProgress = function ( event ) {
  203. if ( ! event.lengthComputable ) return;
  204. numericalValue = event.loaded / event.total;
  205. if ( numericalValue > numericalValueRef ) {
  206. numericalValueRef = numericalValue;
  207. let output = 'Download of "' + url + '": ' + ( numericalValue * 100 ).toFixed( 2 ) + '%';
  208. scope.parser.callbacks.onProgress( 'progressLoad', output, numericalValue );
  209. }
  210. };
  211. }
  212. this.setCallbackOnMeshAlter( onMeshAlter );
  213. let fileLoaderOnLoad = function ( content ) {
  214. scope.parser.callbacks.onLoad( scope.parse( content ), "OBJLoader2#load: Parsing completed" );
  215. };
  216. let fileLoader = new FileLoader( this.manager );
  217. fileLoader.setPath( this.path || this.resourcePath );
  218. fileLoader.setResponseType( 'arraybuffer' );
  219. fileLoader.load( filename, fileLoaderOnLoad, onFileLoadProgress, onError );
  220. },
  221. /**
  222. * Parses OBJ data synchronously from arraybuffer or string and returns the {@link Object3D}.
  223. *
  224. * @param {arraybuffer|string} content OBJ data as Uint8Array or String
  225. * @return {Object3D}
  226. */
  227. parse: function ( content ) {
  228. // fast-fail in case of illegal data
  229. if ( content === null || content === undefined ) {
  230. throw 'Provided content is not a valid ArrayBuffer or String. Unable to continue parsing';
  231. }
  232. if ( this.parser.logging.enabled ) {
  233. console.time( 'OBJLoader parse: ' + this.modelName );
  234. }
  235. // Create default materials beforehand, but do not override previously set materials (e.g. during init)
  236. this.materialHandler.createDefaultMaterials( false );
  237. // code works directly on the material references, parser clear its materials before updating
  238. this.parser.setMaterials( this.materialHandler.getMaterials() );
  239. if ( content instanceof ArrayBuffer || content instanceof Uint8Array ) {
  240. if ( this.parser.logging.enabled ) console.info( 'Parsing arrayBuffer...' );
  241. this.parser.execute( content );
  242. } else if ( typeof ( content ) === 'string' || content instanceof String ) {
  243. if ( this.parser.logging.enabled ) console.info( 'Parsing text...' );
  244. this.parser.executeLegacy( content );
  245. } else {
  246. this.parser.callbacks.onError( 'Provided content was neither of type String nor Uint8Array! Aborting...' );
  247. }
  248. if ( this.parser.logging.enabled ) {
  249. console.timeEnd( 'OBJLoader parse: ' + this.modelName );
  250. }
  251. return this.baseObject3d;
  252. },
  253. _onAssetAvailable: function ( payload ) {
  254. if ( payload.cmd !== 'assetAvailable' ) return;
  255. if ( payload.type === 'mesh' ) {
  256. let meshes = this.meshReceiver.buildMeshes( payload );
  257. for ( let mesh of meshes ) {
  258. this.baseObject3d.add( mesh );
  259. }
  260. } else if ( payload.type === 'material' ) {
  261. this.materialHandler.addPayloadMaterials( payload );
  262. }
  263. }
  264. } );
  265. export { OBJLoader2 };