OBJLoader.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797
  1. /**
  2. * @author mrdoob / http://mrdoob.com/
  3. */
  4. function OBJLoader_plugin() {
  5. IV.THREE.OBJLoader = (function () {
  6. // o object_name | g group_name
  7. var object_pattern = /^[og]\s*(.+)?/;
  8. // mtllib file_reference
  9. var material_library_pattern = /^mtllib /;
  10. // usemtl material_name
  11. var material_use_pattern = /^usemtl /;
  12. function ParserState() {
  13. var state = {
  14. objects: [],
  15. object: {},
  16. vertices: [],
  17. normals: [],
  18. colors: [],
  19. uvs: [],
  20. materialLibraries: [],
  21. startObject: function (name, fromDeclaration) {
  22. // If the current object (initial from reset) is not from a g/o declaration in the parsed
  23. // file. We need to use it for the first parsed g/o to keep things in sync.
  24. if (this.object && this.object.fromDeclaration === false) {
  25. this.object.name = name;
  26. this.object.fromDeclaration = (fromDeclaration !== false);
  27. return;
  28. }
  29. var previousMaterial = (this.object && typeof this.object.currentMaterial === 'function' ? this.object.currentMaterial() : undefined);
  30. if (this.object && typeof this.object._finalize === 'function') {
  31. this.object._finalize(true);
  32. }
  33. this.object = {
  34. name: name || '',
  35. fromDeclaration: (fromDeclaration !== false),
  36. geometry: {
  37. vertices: [],
  38. normals: [],
  39. colors: [],
  40. uvs: []
  41. },
  42. materials: [],
  43. smooth: true,
  44. startMaterial: function (name, libraries) {
  45. var previous = this._finalize(false);
  46. // New usemtl declaration overwrites an inherited material, except if faces were declared
  47. // after the material, then it must be preserved for proper MultiMaterial continuation.
  48. if (previous && (previous.inherited || previous.groupCount <= 0)) {
  49. this.materials.splice(previous.index, 1);
  50. }
  51. var material = {
  52. index: this.materials.length,
  53. name: name || '',
  54. mtllib: (Array.isArray(libraries) && libraries.length > 0 ? libraries[libraries.length - 1] : ''),
  55. smooth: (previous !== undefined ? previous.smooth : this.smooth),
  56. groupStart: (previous !== undefined ? previous.groupEnd : 0),
  57. groupEnd: -1,
  58. groupCount: -1,
  59. inherited: false,
  60. clone: function (index) {
  61. var cloned = {
  62. index: (typeof index === 'number' ? index : this.index),
  63. name: this.name,
  64. mtllib: this.mtllib,
  65. smooth: this.smooth,
  66. groupStart: 0,
  67. groupEnd: -1,
  68. groupCount: -1,
  69. inherited: false
  70. };
  71. cloned.clone = this.clone.bind(cloned);
  72. return cloned;
  73. }
  74. };
  75. this.materials.push(material);
  76. return material;
  77. },
  78. currentMaterial: function () {
  79. if (this.materials.length > 0) {
  80. return this.materials[this.materials.length - 1];
  81. }
  82. return undefined;
  83. },
  84. _finalize: function (end) {
  85. var lastMultiMaterial = this.currentMaterial();
  86. if (lastMultiMaterial && lastMultiMaterial.groupEnd === -1) {
  87. lastMultiMaterial.groupEnd = this.geometry.vertices.length / 3;
  88. lastMultiMaterial.groupCount = lastMultiMaterial.groupEnd - lastMultiMaterial.groupStart;
  89. lastMultiMaterial.inherited = false;
  90. }
  91. // Ignore objects tail materials if no face declarations followed them before a new o/g started.
  92. if (end && this.materials.length > 1) {
  93. for (var mi = this.materials.length - 1; mi >= 0; mi--) {
  94. if (this.materials[mi].groupCount <= 0) {
  95. this.materials.splice(mi, 1);
  96. }
  97. }
  98. }
  99. // Guarantee at least one empty material, this makes the creation later more straight forward.
  100. if (end && this.materials.length === 0) {
  101. this.materials.push({
  102. name: '',
  103. smooth: this.smooth
  104. });
  105. }
  106. return lastMultiMaterial;
  107. }
  108. };
  109. // Inherit previous objects material.
  110. // Spec tells us that a declared material must be set to all objects until a new material is declared.
  111. // If a usemtl declaration is encountered while this new object is being parsed, it will
  112. // overwrite the inherited material. Exception being that there was already face declarations
  113. // to the inherited material, then it will be preserved for proper MultiMaterial continuation.
  114. if (previousMaterial && previousMaterial.name && typeof previousMaterial.clone === 'function') {
  115. var declared = previousMaterial.clone(0);
  116. declared.inherited = true;
  117. this.object.materials.push(declared);
  118. }
  119. this.objects.push(this.object);
  120. },
  121. finalize: function () {
  122. if (this.object && typeof this.object._finalize === 'function') {
  123. this.object._finalize(true);
  124. }
  125. },
  126. parseVertexIndex: function (value, len) {
  127. var index = parseInt(value, 10);
  128. return (index >= 0 ? index - 1 : index + len / 3) * 3;
  129. },
  130. parseNormalIndex: function (value, len) {
  131. var index = parseInt(value, 10);
  132. return (index >= 0 ? index - 1 : index + len / 3) * 3;
  133. },
  134. parseUVIndex: function (value, len) {
  135. var index = parseInt(value, 10);
  136. return (index >= 0 ? index - 1 : index + len / 2) * 2;
  137. },
  138. addVertex: function (a, b, c) {
  139. var src = this.vertices;
  140. var dst = this.object.geometry.vertices;
  141. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  142. dst.push(src[b + 0], src[b + 1], src[b + 2]);
  143. dst.push(src[c + 0], src[c + 1], src[c + 2]);
  144. },
  145. addVertexPoint: function (a) {
  146. var src = this.vertices;
  147. var dst = this.object.geometry.vertices;
  148. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  149. },
  150. addVertexLine: function (a) {
  151. var src = this.vertices;
  152. var dst = this.object.geometry.vertices;
  153. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  154. },
  155. addNormal: function (a, b, c) {
  156. var src = this.normals;
  157. var dst = this.object.geometry.normals;
  158. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  159. dst.push(src[b + 0], src[b + 1], src[b + 2]);
  160. dst.push(src[c + 0], src[c + 1], src[c + 2]);
  161. },
  162. addColor: function (a, b, c) {
  163. var src = this.colors;
  164. var dst = this.object.geometry.colors;
  165. dst.push(src[a + 0], src[a + 1], src[a + 2]);
  166. dst.push(src[b + 0], src[b + 1], src[b + 2]);
  167. dst.push(src[c + 0], src[c + 1], src[c + 2]);
  168. },
  169. addUV: function (a, b, c) {
  170. var src = this.uvs;
  171. var dst = this.object.geometry.uvs;
  172. dst.push(src[a + 0], src[a + 1]);
  173. dst.push(src[b + 0], src[b + 1]);
  174. dst.push(src[c + 0], src[c + 1]);
  175. },
  176. addUVLine: function (a) {
  177. var src = this.uvs;
  178. var dst = this.object.geometry.uvs;
  179. dst.push(src[a + 0], src[a + 1]);
  180. },
  181. addFace: function (a, b, c, ua, ub, uc, na, nb, nc) {
  182. var vLen = this.vertices.length;
  183. var ia = this.parseVertexIndex(a, vLen);
  184. var ib = this.parseVertexIndex(b, vLen);
  185. var ic = this.parseVertexIndex(c, vLen);
  186. this.addVertex(ia, ib, ic);
  187. if (ua !== undefined && ua !== '') {
  188. var uvLen = this.uvs.length;
  189. ia = this.parseUVIndex(ua, uvLen);
  190. ib = this.parseUVIndex(ub, uvLen);
  191. ic = this.parseUVIndex(uc, uvLen);
  192. this.addUV(ia, ib, ic);
  193. }
  194. if (na !== undefined && na !== '') {
  195. // Normals are many times the same. If so, skip function call and parseInt.
  196. var nLen = this.normals.length;
  197. ia = this.parseNormalIndex(na, nLen);
  198. ib = na === nb ? ia : this.parseNormalIndex(nb, nLen);
  199. ic = na === nc ? ia : this.parseNormalIndex(nc, nLen);
  200. this.addNormal(ia, ib, ic);
  201. }
  202. if (this.colors.length > 0) {
  203. this.addColor(ia, ib, ic);
  204. }
  205. },
  206. addPointGeometry: function (vertices) {
  207. this.object.geometry.type = 'Points';
  208. var vLen = this.vertices.length;
  209. for (var vi = 0, l = vertices.length; vi < l; vi++) {
  210. this.addVertexPoint(this.parseVertexIndex(vertices[vi], vLen));
  211. }
  212. },
  213. addLineGeometry: function (vertices, uvs) {
  214. this.object.geometry.type = 'Line';
  215. var vLen = this.vertices.length;
  216. var uvLen = this.uvs.length;
  217. for (var vi = 0, l = vertices.length; vi < l; vi++) {
  218. this.addVertexLine(this.parseVertexIndex(vertices[vi], vLen));
  219. }
  220. for (var uvi = 0, l = uvs.length; uvi < l; uvi++) {
  221. this.addUVLine(this.parseUVIndex(uvs[uvi], uvLen));
  222. }
  223. }
  224. };
  225. state.startObject('', false);
  226. return state;
  227. }
  228. //
  229. function OBJLoader(manager) {
  230. this.manager = (manager !== undefined) ? manager : IV.THREE.DefaultLoadingManager;
  231. this.materials = null;
  232. }
  233. OBJLoader.prototype = {
  234. constructor: OBJLoader,
  235. load: function (url, onLoad, onProgress, onError) {
  236. var scope = this;
  237. var loader = new IV.THREE.FileLoader(scope.manager);
  238. loader.setPath(this.path);
  239. loader.load(url, function (text) {
  240. onLoad(scope.parse(text));
  241. }, onProgress, onError);
  242. },
  243. setPath: function (value) {
  244. this.path = value;
  245. return this;
  246. },
  247. setMaterials: function (materials) {
  248. this.materials = materials;
  249. return this;
  250. },
  251. parse: function (text) {
  252. console.time('OBJLoader');
  253. var state = new ParserState();
  254. if (text.indexOf('\r\n') !== -1) {
  255. // This is faster than String.split with regex that splits on both
  256. text = text.replace(/\r\n/g, '\n');
  257. }
  258. if (text.indexOf('\\\n') !== -1) {
  259. // join lines separated by a line continuation character (\)
  260. text = text.replace(/\\\n/g, '');
  261. }
  262. var lines = text.split('\n');
  263. var line = '', lineFirstChar = '';
  264. var lineLength = 0;
  265. var result = [];
  266. // Faster to just trim left side of the line. Use if available.
  267. var trimLeft = (typeof ''.trimLeft === 'function');
  268. for (var i = 0, l = lines.length; i < l; i++) {
  269. line = lines[i];
  270. line = trimLeft ? line.trimLeft() : line.trim();
  271. lineLength = line.length;
  272. if (lineLength === 0) continue;
  273. lineFirstChar = line.charAt(0);
  274. // @todo invoke passed in handler if any
  275. if (lineFirstChar === '#') continue;
  276. if (lineFirstChar === 'v') {
  277. var data = line.split(/\s+/);
  278. switch (data[0]) {
  279. case 'v':
  280. state.vertices.push(
  281. parseFloat(data[1]),
  282. parseFloat(data[2]),
  283. parseFloat(data[3])
  284. );
  285. if (data.length === 8) {
  286. state.colors.push(
  287. parseFloat(data[4]),
  288. parseFloat(data[5]),
  289. parseFloat(data[6])
  290. );
  291. }
  292. break;
  293. case 'vn':
  294. state.normals.push(
  295. parseFloat(data[1]),
  296. parseFloat(data[2]),
  297. parseFloat(data[3])
  298. );
  299. break;
  300. case 'vt':
  301. state.uvs.push(
  302. parseFloat(data[1]),
  303. parseFloat(data[2])
  304. );
  305. break;
  306. }
  307. } else if (lineFirstChar === 'f') {
  308. var lineData = line.substr(1).trim();
  309. var vertexData = lineData.split(/\s+/);
  310. var faceVertices = [];
  311. // Parse the face vertex data into an easy to work with format
  312. for (var j = 0, jl = vertexData.length; j < jl; j++) {
  313. var vertex = vertexData[j];
  314. if (vertex.length > 0) {
  315. var vertexParts = vertex.split('/');
  316. faceVertices.push(vertexParts);
  317. }
  318. }
  319. // Draw an edge between the first vertex and all subsequent vertices to form an n-gon
  320. var v1 = faceVertices[0];
  321. for (var j = 1, jl = faceVertices.length - 1; j < jl; j++) {
  322. var v2 = faceVertices[j];
  323. var v3 = faceVertices[j + 1];
  324. state.addFace(
  325. v1[0], v2[0], v3[0],
  326. v1[1], v2[1], v3[1],
  327. v1[2], v2[2], v3[2]
  328. );
  329. }
  330. } else if (lineFirstChar === 'l') {
  331. var lineParts = line.substring(1).trim().split(" ");
  332. var lineVertices = [], lineUVs = [];
  333. if (line.indexOf("/") === -1) {
  334. lineVertices = lineParts;
  335. } else {
  336. for (var li = 0, llen = lineParts.length; li < llen; li++) {
  337. var parts = lineParts[li].split("/");
  338. if (parts[0] !== "") lineVertices.push(parts[0]);
  339. if (parts[1] !== "") lineUVs.push(parts[1]);
  340. }
  341. }
  342. state.addLineGeometry(lineVertices, lineUVs);
  343. } else if (lineFirstChar === 'p') {
  344. var lineData = line.substr(1).trim();
  345. var pointData = lineData.split(" ");
  346. state.addPointGeometry(pointData);
  347. } else if ((result = object_pattern.exec(line)) !== null) {
  348. // o object_name
  349. // or
  350. // g group_name
  351. // WORKAROUND: https://bugs.chromium.org/p/v8/issues/detail?id=2869
  352. // var name = result[ 0 ].substr( 1 ).trim();
  353. var name = (" " + result[0].substr(1).trim()).substr(1);
  354. state.startObject(name);
  355. } else if (material_use_pattern.test(line)) {
  356. // material
  357. state.object.startMaterial(line.substring(7).trim(), state.materialLibraries);
  358. } else if (material_library_pattern.test(line)) {
  359. // mtl file
  360. state.materialLibraries.push(line.substring(7).trim());
  361. } else if (lineFirstChar === 's') {
  362. result = line.split(' ');
  363. // smooth shading
  364. // @todo Handle files that have varying smooth values for a set of faces inside one geometry,
  365. // but does not define a usemtl for each face set.
  366. // This should be detected and a dummy material created (later MultiMaterial and geometry groups).
  367. // This requires some care to not create extra material on each smooth value for "normal" obj files.
  368. // where explicit usemtl defines geometry groups.
  369. // Example asset: examples/models/obj/cerberus/Cerberus.obj
  370. /*
  371. * http://paulbourke.net/dataformats/obj/
  372. * or
  373. * http://www.cs.utah.edu/~boulos/cs3505/obj_spec.pdf
  374. *
  375. * From chapter "Grouping" Syntax explanation "s group_number":
  376. * "group_number is the smoothing group number. To turn off smoothing groups, use a value of 0 or off.
  377. * Polygonal elements use group numbers to put elements in different smoothing groups. For free-form
  378. * surfaces, smoothing groups are either turned on or off; there is no difference between values greater
  379. * than 0."
  380. */
  381. if (result.length > 1) {
  382. var value = result[1].trim().toLowerCase();
  383. state.object.smooth = (value !== '0' && value !== 'off');
  384. } else {
  385. // ZBrush can produce "s" lines #11707
  386. state.object.smooth = true;
  387. }
  388. var material = state.object.currentMaterial();
  389. if (material) material.smooth = state.object.smooth;
  390. } else {
  391. // Handle null terminated files without exception
  392. if (line === '\0') continue;
  393. throw new Error('IV.THREE.OBJLoader: Unexpected line: "' + line + '"');
  394. }
  395. }
  396. state.finalize();
  397. var container = new IV.THREE.Group();
  398. container.materialLibraries = [].concat(state.materialLibraries);
  399. for (var i = 0, l = state.objects.length; i < l; i++) {
  400. var object = state.objects[i];
  401. var geometry = object.geometry;
  402. var materials = object.materials;
  403. var isLine = (geometry.type === 'Line');
  404. var isPoints = (geometry.type === 'Points');
  405. var hasVertexColors = false;
  406. // Skip o/g line declarations that did not follow with any faces
  407. if (geometry.vertices.length === 0) continue;
  408. var buffergeometry = new IV.THREE.BufferGeometry();
  409. buffergeometry.addAttribute('position', new IV.THREE.Float32BufferAttribute(geometry.vertices, 3));
  410. if (geometry.normals.length > 0) {
  411. buffergeometry.addAttribute('normal', new IV.THREE.Float32BufferAttribute(geometry.normals, 3));
  412. } else {
  413. buffergeometry.computeVertexNormals();
  414. }
  415. if (geometry.colors.length > 0) {
  416. hasVertexColors = true;
  417. buffergeometry.addAttribute('color', new IV.THREE.Float32BufferAttribute(geometry.colors, 3));
  418. }
  419. if (geometry.uvs.length > 0) {
  420. buffergeometry.addAttribute('uv', new IV.THREE.Float32BufferAttribute(geometry.uvs, 2));
  421. }
  422. // Create materials
  423. var createdMaterials = [];
  424. for (var mi = 0, miLen = materials.length; mi < miLen; mi++) {
  425. var sourceMaterial = materials[mi];
  426. var material = undefined;
  427. if (this.materials !== null) {
  428. material = this.materials.create(sourceMaterial.name);
  429. // mtl etc. loaders probably can't create line materials correctly, copy properties to a line material.
  430. if (isLine && material && !(material instanceof IV.THREE.LineBasicMaterial)) {
  431. var materialLine = new IV.THREE.LineBasicMaterial();
  432. IV.THREE.Material.prototype.copy.call(materialLine, material);
  433. materialLine.color.copy(material.color);
  434. materialLine.lights = false;
  435. material = materialLine;
  436. } else if (isPoints && material && !(material instanceof IV.THREE.PointsMaterial)) {
  437. var materialPoints = new IV.THREE.PointsMaterial({size: 10, sizeAttenuation: false});
  438. IV.THREE.Material.prototype.copy.call(materialPoints, material);
  439. materialPoints.color.copy(material.color);
  440. materialPoints.map = material.map;
  441. materialPoints.lights = false;
  442. material = materialPoints;
  443. }
  444. }
  445. if (!material) {
  446. if (isLine) {
  447. material = new IV.THREE.LineBasicMaterial();
  448. } else if (isPoints) {
  449. material = new IV.THREE.PointsMaterial({size: 1, sizeAttenuation: false});
  450. } else {
  451. material = new IV.THREE.MeshPhongMaterial();
  452. }
  453. material.name = sourceMaterial.name;
  454. }
  455. material.flatShading = sourceMaterial.smooth ? false : true;
  456. material.vertexColors = hasVertexColors ? IV.THREE.VertexColors : IV.THREE.NoColors;
  457. createdMaterials.push(material);
  458. }
  459. // Create mesh
  460. var mesh;
  461. if (createdMaterials.length > 1) {
  462. for (var mi = 0, miLen = materials.length; mi < miLen; mi++) {
  463. var sourceMaterial = materials[mi];
  464. buffergeometry.addGroup(sourceMaterial.groupStart, sourceMaterial.groupCount, mi);
  465. }
  466. if (isLine) {
  467. mesh = new IV.THREE.LineSegments(buffergeometry, createdMaterials);
  468. } else if (isPoints) {
  469. mesh = new IV.THREE.Points(buffergeometry, createdMaterials);
  470. } else {
  471. mesh = new IV.THREE.Mesh(buffergeometry, createdMaterials);
  472. }
  473. } else {
  474. if (isLine) {
  475. mesh = new IV.THREE.LineSegments(buffergeometry, createdMaterials[0]);
  476. } else if (isPoints) {
  477. mesh = new IV.THREE.Points(buffergeometry, createdMaterials[0]);
  478. } else {
  479. mesh = new IV.THREE.Mesh(buffergeometry, createdMaterials[0]);
  480. }
  481. }
  482. mesh.name = object.name;
  483. container.add(mesh);
  484. }
  485. console.timeEnd('OBJLoader');
  486. return container;
  487. }
  488. };
  489. return OBJLoader;
  490. })();
  491. }