OBJLoader.js 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370
  1. var getObjLoader = function(){
  2. THREE.Cache.enabled = true //add 记录获取过的obj
  3. var BufferAttribute = THREE.BufferAttribute
  4. function Int8BufferAttribute( array, itemSize, normalized ) {
  5. BufferAttribute.call( this, new Int8Array( array ), itemSize, normalized );
  6. }
  7. Int8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  8. Int8BufferAttribute.prototype.constructor = Int8BufferAttribute;
  9. function Uint8BufferAttribute( array, itemSize, normalized ) {
  10. BufferAttribute.call( this, new Uint8Array( array ), itemSize, normalized );
  11. }
  12. Uint8BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  13. Uint8BufferAttribute.prototype.constructor = Uint8BufferAttribute;
  14. function Uint8ClampedBufferAttribute( array, itemSize, normalized ) {
  15. BufferAttribute.call( this, new Uint8ClampedArray( array ), itemSize, normalized );
  16. }
  17. Uint8ClampedBufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  18. Uint8ClampedBufferAttribute.prototype.constructor = Uint8ClampedBufferAttribute;
  19. function Int16BufferAttribute( array, itemSize, normalized ) {
  20. BufferAttribute.call( this, new Int16Array( array ), itemSize, normalized );
  21. }
  22. Int16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  23. Int16BufferAttribute.prototype.constructor = Int16BufferAttribute;
  24. function Uint16BufferAttribute( array, itemSize, normalized ) {
  25. BufferAttribute.call( this, new Uint16Array( array ), itemSize, normalized );
  26. }
  27. Uint16BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  28. Uint16BufferAttribute.prototype.constructor = Uint16BufferAttribute;
  29. function Int32BufferAttribute( array, itemSize, normalized ) {
  30. BufferAttribute.call( this, new Int32Array( array ), itemSize, normalized );
  31. }
  32. Int32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  33. Int32BufferAttribute.prototype.constructor = Int32BufferAttribute;
  34. function Uint32BufferAttribute( array, itemSize, normalized ) {
  35. BufferAttribute.call( this, new Uint32Array( array ), itemSize, normalized );
  36. }
  37. Uint32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  38. Uint32BufferAttribute.prototype.constructor = Uint32BufferAttribute;
  39. function Float32BufferAttribute( array, itemSize, normalized ) {
  40. BufferAttribute.call( this, new Float32Array( array ), itemSize, normalized );
  41. }
  42. Float32BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  43. Float32BufferAttribute.prototype.constructor = Float32BufferAttribute;
  44. function Float64BufferAttribute( array, itemSize, normalized ) {
  45. BufferAttribute.call( this, new Float64Array( array ), itemSize, normalized );
  46. }
  47. Float64BufferAttribute.prototype = Object.create( BufferAttribute.prototype );
  48. Float64BufferAttribute.prototype.constructor = Float64BufferAttribute;
  49. function LoadingManager( onLoad, onProgress, onError ) {
  50. var scope = this;
  51. var isLoading = false;
  52. var itemsLoaded = 0;
  53. var itemsTotal = 0;
  54. var urlModifier = undefined;
  55. this.onStart = undefined;
  56. this.onLoad = onLoad;
  57. this.onProgress = onProgress;
  58. this.onError = onError;
  59. this.itemStart = function ( url ) {
  60. itemsTotal ++;
  61. if ( isLoading === false ) {
  62. if ( scope.onStart !== undefined ) {
  63. scope.onStart( url, itemsLoaded, itemsTotal );
  64. }
  65. }
  66. isLoading = true;
  67. };
  68. this.itemEnd = function ( url ) {
  69. itemsLoaded ++;
  70. if ( scope.onProgress !== undefined ) {
  71. scope.onProgress( url, itemsLoaded, itemsTotal );
  72. }
  73. if ( itemsLoaded === itemsTotal ) {
  74. isLoading = false;
  75. if ( scope.onLoad !== undefined ) {
  76. scope.onLoad();
  77. }
  78. }
  79. };
  80. this.itemError = function ( url ) {
  81. if ( scope.onError !== undefined ) {
  82. scope.onError( url );
  83. }
  84. };
  85. this.resolveURL = function ( url ) {
  86. if ( urlModifier ) {
  87. return urlModifier( url );
  88. }
  89. return url;
  90. };
  91. this.setURLModifier = function ( transform ) {
  92. urlModifier = transform;
  93. return this;
  94. };
  95. }
  96. var DefaultLoadingManager1 = new LoadingManager();
  97. /**
  98. * @author mrdoob / http://mrdoob.com/
  99. */
  100. var loading = {};
  101. function FileLoader( manager ) {
  102. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager1;
  103. }
  104. Object.assign( FileLoader.prototype, {
  105. load: function ( url, onLoad, onProgress, onError ) {
  106. if ( url === undefined ) url = '';
  107. if ( this.path !== undefined ) url = this.path + url;
  108. url = this.manager.resolveURL( url );
  109. var scope = this;
  110. var cached = THREE.Cache.get( url );
  111. if ( cached !== undefined ) {
  112. /* scope.manager.itemStart( url );
  113. setTimeout( function () {
  114. if ( onLoad ) onLoad( cached );
  115. scope.manager.itemEnd( url );
  116. }, 0 );
  117. return cached;
  118. */
  119. //改 直接返回obj
  120. if ( onLoad ) onLoad( cached.clone() );
  121. return cached.clone()
  122. }
  123. // Check if request is duplicate
  124. if ( loading[ url ] !== undefined ) {
  125. loading[ url ].push( {
  126. onLoad: onLoad,
  127. onProgress: onProgress,
  128. onError: onError
  129. } );
  130. return;
  131. }
  132. // Check for data: URI
  133. var dataUriRegex = /^data:(.*?)(;base64)?,(.*)$/;
  134. var dataUriRegexResult = url.match( dataUriRegex );
  135. // Safari can not handle Data URIs through XMLHttpRequest so process manually
  136. if ( dataUriRegexResult ) {
  137. var mimeType = dataUriRegexResult[ 1 ];
  138. var isBase64 = !! dataUriRegexResult[ 2 ];
  139. var data = dataUriRegexResult[ 3 ];
  140. data = window.decodeURIComponent( data );
  141. if ( isBase64 ) data = window.atob( data );
  142. try {
  143. var response;
  144. var responseType = ( this.responseType || '' ).toLowerCase();
  145. switch ( responseType ) {
  146. case 'arraybuffer':
  147. case 'blob':
  148. var view = new Uint8Array( data.length );
  149. for ( var i = 0; i < data.length; i ++ ) {
  150. view[ i ] = data.charCodeAt( i );
  151. }
  152. if ( responseType === 'blob' ) {
  153. response = new Blob( [ view.buffer ], { type: mimeType } );
  154. } else {
  155. response = view.buffer;
  156. }
  157. break;
  158. case 'document':
  159. var parser = new DOMParser();
  160. response = parser.parseFromString( data, mimeType );
  161. break;
  162. case 'json':
  163. response = JSON.parse( data );
  164. break;
  165. default: // 'text' or other
  166. response = data;
  167. break;
  168. }
  169. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  170. window.setTimeout( function () {
  171. if ( onLoad ) onLoad( response );
  172. scope.manager.itemEnd( url );
  173. }, 0 );
  174. } catch ( error ) {
  175. // Wait for next browser tick like standard XMLHttpRequest event dispatching does
  176. window.setTimeout( function () {
  177. if ( onError ) onError( error );
  178. scope.manager.itemEnd( url );
  179. scope.manager.itemError( url );
  180. }, 0 );
  181. }
  182. } else {
  183. // Initialise array for duplicate requests
  184. loading[ url ] = [];
  185. loading[ url ].push( {
  186. onLoad: onLoad,
  187. onProgress: onProgress,
  188. onError: onError
  189. } );
  190. var request = new XMLHttpRequest();
  191. request.open( 'GET', url, true );
  192. request.addEventListener( 'load', function ( event ) {
  193. var response = this.response;
  194. //THREE.Cache.add( url, response );
  195. var callbacks = loading[ url ];
  196. delete loading[ url ];
  197. if ( this.status === 200 || this.status === 0 ) {
  198. // Some browsers return HTTP Status 0 when using non-http protocol
  199. // e.g. 'file://' or 'data://'. Handle as success.
  200. if ( this.status === 0 ) console.warn( 'THREE.FileLoader: HTTP Status 0 received.' );
  201. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  202. var callback = callbacks[ i ];
  203. if ( callback.onLoad ) callback.onLoad( response );
  204. }
  205. scope.manager.itemEnd( url );
  206. } else {
  207. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  208. var callback = callbacks[ i ];
  209. if ( callback.onError ) callback.onError( event );
  210. }
  211. scope.manager.itemEnd( url );
  212. scope.manager.itemError( url );
  213. }
  214. }, false );
  215. request.addEventListener( 'progress', function ( event ) {
  216. var callbacks = loading[ url ];
  217. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  218. var callback = callbacks[ i ];
  219. if ( callback.onProgress ) callback.onProgress( event );
  220. }
  221. }, false );
  222. request.addEventListener( 'error', function ( event ) {
  223. var callbacks = loading[ url ];
  224. delete loading[ url ];
  225. for ( var i = 0, il = callbacks.length; i < il; i ++ ) {
  226. var callback = callbacks[ i ];
  227. if ( callback.onError ) callback.onError( event );
  228. }
  229. scope.manager.itemEnd( url );
  230. scope.manager.itemError( url );
  231. }, false );
  232. if ( this.responseType !== undefined ) request.responseType = this.responseType;
  233. if ( this.withCredentials !== undefined ) request.withCredentials = this.withCredentials;
  234. if ( request.overrideMimeType ) request.overrideMimeType( this.mimeType !== undefined ? this.mimeType : 'text/plain' );
  235. for ( var header in this.requestHeader ) {
  236. request.setRequestHeader( header, this.requestHeader[ header ] );
  237. }
  238. request.send( null );
  239. }
  240. scope.manager.itemStart( url );
  241. return request;
  242. },
  243. setPath: function ( value ) {
  244. this.path = value;
  245. return this;
  246. },
  247. setResponseType: function ( value ) {
  248. this.responseType = value;
  249. return this;
  250. },
  251. setWithCredentials: function ( value ) {
  252. this.withCredentials = value;
  253. return this;
  254. },
  255. setMimeType: function ( value ) {
  256. this.mimeType = value;
  257. return this;
  258. },
  259. setRequestHeader: function ( value ) {
  260. this.requestHeader = value;
  261. return this;
  262. }
  263. } );
  264. THREE.FileLoader = FileLoader
  265. THREE.OBJLoader = ( function () {
  266. var BufferGeometry = THREE.BufferGeometry;
  267. var DefaultLoadingManager = DefaultLoadingManager1//THREE.DefaultLoadingManager;
  268. var FileLoader = THREE.FileLoader;
  269. //var Float32BufferAttribute = THREE.Float32BufferAttribute;
  270. var Group = THREE.Group;
  271. var LineBasicMaterial = THREE.LineBasicMaterial;
  272. var LineSegments = THREE.LineSegments;
  273. var Material = THREE.Material;
  274. var Mesh = THREE.Mesh;
  275. var MeshPhongMaterial = THREE.MeshPhongMaterial;
  276. var NoColors = THREE.NoColors;
  277. var PointsMaterial = THREE.PointsMaterial;
  278. var VertexColors = THREE.VertexColors;
  279. // o object_name | g group_name
  280. var object_pattern = /^[og]\s*(.+)?/;
  281. // mtllib file_reference
  282. var material_library_pattern = /^mtllib /;
  283. // usemtl material_name
  284. var material_use_pattern = /^usemtl /;
  285. function ParserState() {
  286. var state = {
  287. objects: [],
  288. object: {},
  289. vertices: [],
  290. normals: [],
  291. colors: [],
  292. uvs: [],
  293. materialLibraries: [],
  294. startObject: function ( name, fromDeclaration ) {
  295. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  296. // file. We need to use it for the first parsed g/o to keep things in sync.
  297. if ( this.object && this.object.fromDeclaration === false ) {
  298. this.object.name = name;
  299. this.object.fromDeclaration = ( fromDeclaration !== false );
  300. return;
  301. }
  302. var previousMaterial = ( this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined );
  303. if ( this.object && typeof this.object._finalize === 'function' ) {
  304. this.object._finalize( true );
  305. }
  306. this.object = {
  307. name: name || '',
  308. fromDeclaration: ( fromDeclaration !== false ),
  309. geometry: {
  310. vertices: [],
  311. normals: [],
  312. colors: [],
  313. uvs: []
  314. },
  315. materials: [],
  316. smooth: true,
  317. startMaterial: function ( name, libraries ) {
  318. var previous = this._finalize( false );
  319. // New usemtl declaration overwrites an inherited material, except if faces were declared
  320. // after the material, then it must be preserved for proper MultiMaterial continuation.
  321. if ( previous && ( previous.inherited || previous.groupCount <= 0 ) ) {
  322. this.materials.splice( previous.index, 1 );
  323. }
  324. var material = {
  325. index: this.materials.length,
  326. name: name || '',
  327. mtllib: ( Array.isArray( libraries ) && libraries.length > 0 ? libraries[ libraries.length - 1 ] : '' ),
  328. smooth: ( previous !== undefined ? previous.smooth : this.smooth ),
  329. groupStart: ( previous !== undefined ? previous.groupEnd : 0 ),
  330. groupEnd: - 1,
  331. groupCount: - 1,
  332. inherited: false,
  333. clone: function ( index ) {
  334. var cloned = {
  335. index: ( typeof index === 'number' ? index : this.index ),
  336. name: this.name,
  337. mtllib: this.mtllib,
  338. smooth: this.smooth,
  339. groupStart: 0,
  340. groupEnd: - 1,
  341. groupCount: - 1,
  342. inherited: false
  343. };
  344. cloned.clone = this.clone.bind( cloned );
  345. return cloned;
  346. }
  347. };
  348. this.materials.push( material );
  349. return material;
  350. },
  351. currentMaterial: function () {
  352. if ( this.materials.length > 0 ) {
  353. return this.materials[ this.materials.length - 1 ];
  354. }
  355. return undefined;
  356. },
  357. _finalize: function ( end ) {
  358. var lastMultiMaterial = this.currentMaterial();
  359. if ( lastMultiMaterial && lastMultiMaterial.groupEnd === - 1 ) {
  360. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  361. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  362. lastMultiMaterial.inherited = false;
  363. }
  364. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  365. if ( end && this.materials.length > 1 ) {
  366. for ( var mi = this.materials.length - 1; mi >= 0; mi -- ) {
  367. if ( this.materials[ mi ].groupCount <= 0 ) {
  368. this.materials.splice( mi, 1 );
  369. }
  370. }
  371. }
  372. // Guarantee at least one empty material, this makes the creation later more straight forward.
  373. if ( end && this.materials.length === 0 ) {
  374. this.materials.push( {
  375. name: '',
  376. smooth: this.smooth
  377. } );
  378. }
  379. return lastMultiMaterial;
  380. }
  381. };
  382. // Inherit previous objects material.
  383. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  384. // If a usemtl declaration is encountered while this new object is being parsed, it will
  385. // overwrite the inherited material. Exception being that there was already face declarations
  386. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  387. if ( previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function' ) {
  388. var declared = previousMaterial.clone( 0 );
  389. declared.inherited = true;
  390. this.object.materials.push( declared );
  391. }
  392. this.objects.push( this.object );
  393. },
  394. finalize: function () {
  395. if ( this.object && typeof this.object._finalize === 'function' ) {
  396. this.object._finalize( true );
  397. }
  398. },
  399. parseVertexIndex: function ( value, len ) {
  400. var index = parseInt( value, 10 );
  401. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  402. },
  403. parseNormalIndex: function ( value, len ) {
  404. var index = parseInt( value, 10 );
  405. return ( index >= 0 ? index - 1 : index + len / 3 ) * 3;
  406. },
  407. parseUVIndex: function ( value, len ) {
  408. var index = parseInt( value, 10 );
  409. return ( index >= 0 ? index - 1 : index + len / 2 ) * 2;
  410. },
  411. addVertex: function ( a, b, c ) {
  412. var src = this.vertices;
  413. var dst = this.object.geometry.vertices;
  414. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  415. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  416. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  417. },
  418. addVertexPoint: function ( a ) {
  419. var src = this.vertices;
  420. var dst = this.object.geometry.vertices;
  421. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  422. },
  423. addVertexLine: function ( a ) {
  424. var src = this.vertices;
  425. var dst = this.object.geometry.vertices;
  426. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  427. },
  428. addNormal: function ( a, b, c ) {
  429. var src = this.normals;
  430. var dst = this.object.geometry.normals;
  431. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  432. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  433. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  434. },
  435. addColor: function ( a, b, c ) {
  436. var src = this.colors;
  437. var dst = this.object.geometry.colors;
  438. dst.push( src[ a + 0 ], src[ a + 1 ], src[ a + 2 ] );
  439. dst.push( src[ b + 0 ], src[ b + 1 ], src[ b + 2 ] );
  440. dst.push( src[ c + 0 ], src[ c + 1 ], src[ c + 2 ] );
  441. },
  442. addUV: function ( a, b, c ) {
  443. var src = this.uvs;
  444. var dst = this.object.geometry.uvs;
  445. dst.push( src[ a + 0 ], src[ a + 1 ] );
  446. dst.push( src[ b + 0 ], src[ b + 1 ] );
  447. dst.push( src[ c + 0 ], src[ c + 1 ] );
  448. },
  449. addUVLine: function ( a ) {
  450. var src = this.uvs;
  451. var dst = this.object.geometry.uvs;
  452. dst.push( src[ a + 0 ], src[ a + 1 ] );
  453. },
  454. addFace: function ( a, b, c, ua, ub, uc, na, nb, nc ) {
  455. var vLen = this.vertices.length;
  456. var ia = this.parseVertexIndex( a, vLen );
  457. var ib = this.parseVertexIndex( b, vLen );
  458. var ic = this.parseVertexIndex( c, vLen );
  459. this.addVertex( ia, ib, ic );
  460. if ( ua !== undefined && ua !== '' ) {
  461. var uvLen = this.uvs.length;
  462. ia = this.parseUVIndex( ua, uvLen );
  463. ib = this.parseUVIndex( ub, uvLen );
  464. ic = this.parseUVIndex( uc, uvLen );
  465. this.addUV( ia, ib, ic );
  466. }
  467. if ( na !== undefined && na !== '' ) {
  468. // Normals are many times the same. If so, skip function call and parseInt.
  469. var nLen = this.normals.length;
  470. ia = this.parseNormalIndex( na, nLen );
  471. ib = na === nb ? ia : this.parseNormalIndex( nb, nLen );
  472. ic = na === nc ? ia : this.parseNormalIndex( nc, nLen );
  473. this.addNormal( ia, ib, ic );
  474. }
  475. if ( this.colors.length > 0 ) {
  476. this.addColor( ia, ib, ic );
  477. }
  478. },
  479. addPointGeometry: function ( vertices ) {
  480. this.object.geometry.type = 'Points';
  481. var vLen = this.vertices.length;
  482. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  483. this.addVertexPoint( this.parseVertexIndex( vertices[ vi ], vLen ) );
  484. }
  485. },
  486. addLineGeometry: function ( vertices, uvs ) {
  487. this.object.geometry.type = 'Line';
  488. var vLen = this.vertices.length;
  489. var uvLen = this.uvs.length;
  490. for ( var vi = 0, l = vertices.length; vi < l; vi ++ ) {
  491. this.addVertexLine( this.parseVertexIndex( vertices[ vi ], vLen ) );
  492. }
  493. for ( var uvi = 0, l = uvs.length; uvi < l; uvi ++ ) {
  494. this.addUVLine( this.parseUVIndex( uvs[ uvi ], uvLen ) );
  495. }
  496. }
  497. };
  498. state.startObject( '', false );
  499. return state;
  500. }
  501. //
  502. function OBJLoader( manager ) {
  503. this.manager = ( manager !== undefined ) ? manager : DefaultLoadingManager1;
  504. this.materials = null;
  505. }
  506. OBJLoader.prototype = {
  507. constructor: OBJLoader,
  508. load: function ( url, onLoad, onProgress, onError ) {
  509. var scope = this;
  510. var loader = new FileLoader( scope.manager );
  511. loader.setPath( this.path );
  512. loader.load( url, function ( text ) {
  513. if(text instanceof THREE.Object3D)onLoad(text) //add 返回cache中的obj
  514. else{
  515. var object = scope.parse( text )
  516. THREE.Cache.add( url, object );
  517. onLoad( object );
  518. }
  519. }, onProgress, onError );
  520. },
  521. setPath: function ( value ) {
  522. this.path = value;
  523. return this;
  524. },
  525. setMaterials: function ( materials ) {
  526. this.materials = materials;
  527. return this;
  528. },
  529. parse: function ( text ) {
  530. console.time( 'OBJLoader' );
  531. var state = new ParserState();
  532. if ( text.indexOf( '\r\n' ) !== - 1 ) {
  533. // This is faster than String.split with regex that splits on both
  534. text = text.replace( /\r\n/g, '\n' );
  535. }
  536. if ( text.indexOf( '\\\n' ) !== - 1 ) {
  537. // join lines separated by a line continuation character (\)
  538. text = text.replace( /\\\n/g, '' );
  539. }
  540. var lines = text.split( '\n' );
  541. var line = '', lineFirstChar = '';
  542. var lineLength = 0;
  543. var result = [];
  544. // Faster to just trim left side of the line. Use if available.
  545. var trimLeft = ( typeof ''.trimLeft === 'function' );
  546. for ( var i = 0, l = lines.length; i < l; i ++ ) {
  547. line = lines[ i ];
  548. line = trimLeft ? line.trimLeft() : line.trim();
  549. lineLength = line.length;
  550. if ( lineLength === 0 ) continue;
  551. lineFirstChar = line.charAt( 0 );
  552. // @todo invoke passed in handler if any
  553. if ( lineFirstChar === '#' ) continue;
  554. if ( lineFirstChar === 'v' ) {
  555. var data = line.split( /\s+/ );
  556. switch ( data[ 0 ] ) {
  557. case 'v':
  558. state.vertices.push(
  559. parseFloat( data[ 1 ] ),
  560. parseFloat( data[ 2 ] ),
  561. parseFloat( data[ 3 ] )
  562. );
  563. if ( data.length >= 7 ) {
  564. state.colors.push(
  565. parseFloat( data[ 4 ] ),
  566. parseFloat( data[ 5 ] ),
  567. parseFloat( data[ 6 ] )
  568. );
  569. }
  570. break;
  571. case 'vn':
  572. state.normals.push(
  573. parseFloat( data[ 1 ] ),
  574. parseFloat( data[ 2 ] ),
  575. parseFloat( data[ 3 ] )
  576. );
  577. break;
  578. case 'vt':
  579. state.uvs.push(
  580. parseFloat( data[ 1 ] ),
  581. parseFloat( data[ 2 ] )
  582. );
  583. break;
  584. }
  585. } else if ( lineFirstChar === 'f' ) {
  586. var lineData = line.substr( 1 ).trim();
  587. var vertexData = lineData.split( /\s+/ );
  588. var faceVertices = [];
  589. // Parse the face vertex data into an easy to work with format
  590. for ( var j = 0, jl = vertexData.length; j < jl; j ++ ) {
  591. var vertex = vertexData[ j ];
  592. if ( vertex.length > 0 ) {
  593. var vertexParts = vertex.split( '/' );
  594. faceVertices.push( vertexParts );
  595. }
  596. }
  597. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  598. var v1 = faceVertices[ 0 ];
  599. for ( var j = 1, jl = faceVertices.length - 1; j < jl; j ++ ) {
  600. var v2 = faceVertices[ j ];
  601. var v3 = faceVertices[ j + 1 ];
  602. state.addFace(
  603. v1[ 0 ], v2[ 0 ], v3[ 0 ],
  604. v1[ 1 ], v2[ 1 ], v3[ 1 ],
  605. v1[ 2 ], v2[ 2 ], v3[ 2 ]
  606. );
  607. }
  608. } else if ( lineFirstChar === 'l' ) {
  609. var lineParts = line.substring( 1 ).trim().split( " " );
  610. var lineVertices = [], lineUVs = [];
  611. if ( line.indexOf( "/" ) === - 1 ) {
  612. lineVertices = lineParts;
  613. } else {
  614. for ( var li = 0, llen = lineParts.length; li < llen; li ++ ) {
  615. var parts = lineParts[ li ].split( "/" );
  616. if ( parts[ 0 ] !== "" ) lineVertices.push( parts[ 0 ] );
  617. if ( parts[ 1 ] !== "" ) lineUVs.push( parts[ 1 ] );
  618. }
  619. }
  620. state.addLineGeometry( lineVertices, lineUVs );
  621. } else if ( lineFirstChar === 'p' ) {
  622. var lineData = line.substr( 1 ).trim();
  623. var pointData = lineData.split( " " );
  624. state.addPointGeometry( pointData );
  625. } else if ( ( result = object_pattern.exec( line ) ) !== null ) {
  626. // o object_name
  627. // or
  628. // g group_name
  629. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  630. // var name = result[ 0 ].substr( 1 ).trim();
  631. var name = ( " " + result[ 0 ].substr( 1 ).trim() ).substr( 1 );
  632. state.startObject( name );
  633. } else if ( material_use_pattern.test( line ) ) {
  634. // material
  635. state.object.startMaterial( line.substring( 7 ).trim(), state.materialLibraries );
  636. } else if ( material_library_pattern.test( line ) ) {
  637. // mtl file
  638. state.materialLibraries.push( line.substring( 7 ).trim() );
  639. } else if ( lineFirstChar === 's' ) {
  640. result = line.split( ' ' );
  641. // smooth shading
  642. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  643. // but does not define a usemtl for each face set.
  644. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  645. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  646. // where explicit usemtl defines geometry groups.
  647. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  648. /*
  649. * http://paulbourke.net/dataformats/obj/
  650. * or
  651. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  652. *
  653. * From chapter "Grouping" Syntax explanation "s group_number":
  654. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  655. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  656. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  657. * than 0."
  658. */
  659. if ( result.length > 1 ) {
  660. var value = result[ 1 ].trim().toLowerCase();
  661. state.object.smooth = ( value !== '0' && value !== 'off' );
  662. } else {
  663. // ZBrush can produce "s" lines #11707
  664. state.object.smooth = true;
  665. }
  666. var material = state.object.currentMaterial();
  667. if ( material ) material.smooth = state.object.smooth;
  668. } else {
  669. // Handle null terminated files without exception
  670. if ( line === '\0' ) continue;
  671. throw new Error( 'THREE.OBJLoader: Unexpected line: "' + line + '"' );
  672. }
  673. }
  674. state.finalize();
  675. var container = new Group();
  676. container.materialLibraries = [].concat( state.materialLibraries );
  677. for ( var i = 0, l = state.objects.length; i < l; i ++ ) {
  678. var object = state.objects[ i ];
  679. var geometry = object.geometry;
  680. var materials = object.materials;
  681. var isLine = ( geometry.type === 'Line' );
  682. var isPoints = ( geometry.type === 'Points' );
  683. var hasVertexColors = false;
  684. // Skip o/g line declarations that did not follow with any faces
  685. if ( geometry.vertices.length === 0 ) continue;
  686. var buffergeometry = new BufferGeometry();
  687. buffergeometry.addAttribute( 'position', new Float32BufferAttribute( geometry.vertices, 3 ) );
  688. if ( geometry.normals.length > 0 ) {
  689. buffergeometry.addAttribute( 'normal', new Float32BufferAttribute( geometry.normals, 3 ) );
  690. } else {
  691. buffergeometry.computeVertexNormals();
  692. }
  693. if ( geometry.colors.length > 0 ) {
  694. hasVertexColors = true;
  695. //buffergeometry.addAttribute( 'color', new Float32BufferAttribute( geometry.colors, 3 ) );
  696. buffergeometry.attributes[ 'color' ] = new Float32BufferAttribute( geometry.color, 3 )
  697. }
  698. if ( geometry.uvs.length > 0 ) {
  699. //buffergeometry.addAttribute( 'uv', new Float32BufferAttribute( geometry.uvs, 2 ) );
  700. buffergeometry.attributes[ 'uv' ] = new Float32BufferAttribute( geometry.uvs, 2 )
  701. }
  702. // Create materials
  703. var createdMaterials = [];
  704. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  705. var sourceMaterial = materials[ mi ];
  706. var material = undefined;
  707. if ( this.materials !== null ) {
  708. material = this.materials.create( sourceMaterial.name );
  709. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  710. if ( isLine && material && ! ( material instanceof LineBasicMaterial ) ) {
  711. var materialLine = new LineBasicMaterial();
  712. Material.prototype.copy.call( materialLine, material );
  713. materialLine.color.copy( material.color );
  714. materialLine.lights = false;
  715. material = materialLine;
  716. } else if ( isPoints && material && ! ( material instanceof PointsMaterial ) ) {
  717. var materialPoints = new PointsMaterial( { size: 10, sizeAttenuation: false } );
  718. Material.prototype.copy.call( materialPoints, material );
  719. materialPoints.color.copy( material.color );
  720. materialPoints.map = material.map;
  721. materialPoints.lights = false;
  722. material = materialPoints;
  723. }
  724. }
  725. if ( ! material ) {
  726. if ( isLine ) {
  727. material = new LineBasicMaterial();
  728. } else if ( isPoints ) {
  729. material = new PointsMaterial( { size: 1, sizeAttenuation: false } );
  730. } else {
  731. material = new MeshPhongMaterial();
  732. }
  733. material.name = sourceMaterial.name;
  734. }
  735. material.flatShading = sourceMaterial.smooth ? false : true;
  736. material.vertexColors = hasVertexColors ? VertexColors : NoColors;
  737. createdMaterials.push( material );
  738. }
  739. // Create mesh
  740. var mesh;
  741. if ( createdMaterials.length > 1 ) {
  742. for ( var mi = 0, miLen = materials.length; mi < miLen; mi ++ ) {
  743. var sourceMaterial = materials[ mi ];
  744. buffergeometry.addGroup( sourceMaterial.groupStart, sourceMaterial.groupCount, mi );
  745. }
  746. if ( isLine ) {
  747. mesh = new LineSegments( buffergeometry, createdMaterials );
  748. } else if ( isPoints ) {
  749. mesh = new Points( buffergeometry, createdMaterials );
  750. } else {
  751. mesh = new Mesh( buffergeometry, createdMaterials );
  752. }
  753. } else {
  754. if ( isLine ) {
  755. mesh = new LineSegments( buffergeometry, createdMaterials[ 0 ] );
  756. } else if ( isPoints ) {
  757. mesh = new Points( buffergeometry, createdMaterials[ 0 ] );
  758. } else {
  759. mesh = new Mesh( buffergeometry, createdMaterials[ 0 ] );
  760. }
  761. }
  762. mesh.name = object.name;
  763. container.add( mesh );
  764. }
  765. console.timeEnd( 'OBJLoader' );
  766. return container;
  767. }
  768. };
  769. THREE.Box3Helper = function( box, hex ) {
  770. this.type = 'Box3Helper';
  771. this.box = box;
  772. var color = ( hex !== undefined ) ? hex : 0xffff00;
  773. var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
  774. var positions = [ 1, 1, 1, - 1, 1, 1, - 1, - 1, 1, 1, - 1, 1, 1, 1, - 1, - 1, 1, - 1, - 1, - 1, - 1, 1, - 1, - 1 ];
  775. var geometry = new THREE.BufferGeometry();
  776. geometry.setIndex( new THREE.BufferAttribute( indices, 1 ) );
  777. geometry.addAttribute( 'position', new Float32BufferAttribute( positions, 3 ) );
  778. THREE.LineSegments.call( this, geometry, new THREE.LineBasicMaterial( { color: color } ) );
  779. this.geometry.computeBoundingSphere();
  780. }
  781. THREE.Box3Helper.prototype = Object.create( THREE.LineSegments.prototype );
  782. THREE.Box3Helper.prototype.constructor = THREE.Box3Helper;
  783. THREE.Box3Helper.prototype.updateMatrixWorld = function ( force ) {
  784. var box = this.box;
  785. //if ( box.isEmpty() ) return;
  786. box.center( this.position );
  787. box.size( this.scale );
  788. this.scale.multiplyScalar( 0.5 );
  789. THREE.Object3D.prototype.updateMatrixWorld.call( this, force );
  790. };
  791. THREE.Box3Helper.prototype.clone = function() {
  792. return new this.constructor(this.box, this.material.color)//.copy(this)
  793. }
  794. return OBJLoader;
  795. } )();
  796. }