OBJLoader2.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /**
  2. * @author Kai Salmen / https://kaisalmen.de
  3. * Development repository: https://github.com/kaisalmen/WWOBJLoader
  4. */
  5. import {
  6. LoadingManager,
  7. FileLoader,
  8. Object3D,
  9. Loader
  10. } from "../../../build/three.module.js";
  11. import { OBJLoader2Parser } from "./obj2/worker/parallel/OBJLoader2Parser.js";
  12. import { MeshReceiver } from "./obj2/shared/MeshReceiver.js";
  13. import { MaterialHandler } from "./obj2/shared/MaterialHandler.js";
  14. /**
  15. * Creates a new OBJLoader2. Use it to load OBJ data from files or to parse OBJ data from arraybuffer or text.
  16. *
  17. * @param {LoadingManager} [manager] The loadingManager for the loader to use. Default is {@link LoadingManager}
  18. * @constructor
  19. */
  20. const OBJLoader2 = function ( manager ) {
  21. Loader.call( this, manager );
  22. this.parser = new OBJLoader2Parser();
  23. this.modelName = '';
  24. this.instanceNo = 0;
  25. this.baseObject3d = new Object3D();
  26. this.materialHandler = new MaterialHandler();
  27. this.meshReceiver = new MeshReceiver( this.materialHandler );
  28. // as OBJLoader2 is no longer derived from OBJLoader2Parser, we need to override the default onAssetAvailable callback
  29. let scope = this;
  30. let defaultOnAssetAvailable = function ( payload ) {
  31. scope._onAssetAvailable( payload );
  32. };
  33. this.parser.setCallbackOnAssetAvailable( defaultOnAssetAvailable );
  34. };
  35. OBJLoader2.OBJLOADER2_VERSION = '3.1.0';
  36. console.info( 'Using OBJLoader2 version: ' + OBJLoader2.OBJLOADER2_VERSION );
  37. OBJLoader2.prototype = Object.assign( Object.create( Loader.prototype ), {
  38. constructor: OBJLoader2,
  39. /**
  40. * See {@link OBJLoader2Parser.setLogging}
  41. * @return {OBJLoader2}
  42. */
  43. setLogging: function ( enabled, debug ) {
  44. this.parser.setLogging( enabled, debug );
  45. return this;
  46. },
  47. /**
  48. * See {@link OBJLoader2Parser.setMaterialPerSmoothingGroup}
  49. * @return {OBJLoader2}
  50. */
  51. setMaterialPerSmoothingGroup: function ( materialPerSmoothingGroup ) {
  52. this.parser.setMaterialPerSmoothingGroup( materialPerSmoothingGroup );
  53. return this;
  54. },
  55. /**
  56. * See {@link OBJLoader2Parser.setUseOAsMesh}
  57. * @return {OBJLoader2}
  58. */
  59. setUseOAsMesh: function ( useOAsMesh ) {
  60. this.parser.setUseOAsMesh( useOAsMesh );
  61. return this;
  62. },
  63. /**
  64. * See {@link OBJLoader2Parser.setUseIndices}
  65. * @return {OBJLoader2}
  66. */
  67. setUseIndices: function ( useIndices ) {
  68. this.parser.setUseIndices( useIndices );
  69. return this;
  70. },
  71. /**
  72. * See {@link OBJLoader2Parser.setDisregardNormals}
  73. * @return {OBJLoader2}
  74. */
  75. setDisregardNormals: function ( disregardNormals ) {
  76. this.parser.setDisregardNormals( disregardNormals );
  77. return this;
  78. },
  79. /**
  80. * Set the name of the model.
  81. *
  82. * @param {string} modelName
  83. * @return {OBJLoader2}
  84. */
  85. setModelName: function ( modelName ) {
  86. this.modelName = modelName ? modelName : this.modelName;
  87. return this;
  88. },
  89. /**
  90. * Set the node where the loaded objects will be attached directly.
  91. *
  92. * @param {Object3D} baseObject3d Object already attached to scenegraph where new meshes will be attached to
  93. * @return {OBJLoader2}
  94. */
  95. setBaseObject3d: function ( baseObject3d ) {
  96. this.baseObject3d = ( baseObject3d === undefined || baseObject3d === null ) ? this.baseObject3d : baseObject3d;
  97. return this;
  98. },
  99. /**
  100. * Add materials as associated array.
  101. *
  102. * @param {Object} materials Object with named {@link Material}
  103. * @return {OBJLoader2}
  104. */
  105. addMaterials: function ( materials ) {
  106. this.materialHandler.addMaterials( materials );
  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 };
粤ICP备19079148号