ObJS.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832
  1. /********************************************************************
  2. * The ObJS objectnitializes the canvas, assignin it to the HTML *
  3. * element, and set the required mouse events. *
  4. * #parameters: none *
  5. * #return: nothing *
  6. ********************************************************************/
  7. function ObJS(){
  8. /********************************************************************
  9. * Parameters for costumization. *
  10. ********************************************************************/
  11. var backColor = "rgba(200, 200, 200, 1)";
  12. var vertColor = "rgba(10, 10, 10, 1)";
  13. var edgeColor = "rgba(100, 70, 70, 1)";
  14. var faceColor = "rgba(180, 180, 255, .6)";
  15. var faceAlpha = .6;
  16. var textColor = "rgba(0, 0, 0, 1)";
  17. var vertSize = 4; //Make it even: at small scales will look better
  18. var rotationSpeed = 90; //Smaller = faster. 100 is a good speed
  19. var zoomSpeed = 0.161; //0-1. 0.2 or 0.3 are good speeds
  20. var moveSpeed = .5;
  21. /********************************************************************
  22. * Variable containing this object, to be refered from nested *
  23. * functions. *
  24. ********************************************************************/
  25. var thisObJS;
  26. /********************************************************************
  27. * Parameter used to scale the measures in the .obj file. Can be *
  28. * integer or float, greater than 0. 50 is a good default. *
  29. ********************************************************************/
  30. var scale;
  31. /********************************************************************
  32. * Variable to determine if the canvas has been initialized. *
  33. ********************************************************************/
  34. var canvasInitialized = false;
  35. /********************************************************************
  36. * Variable to determine if the mouse button is being holded down. *
  37. ********************************************************************/
  38. var mDown = false;
  39. var pinch = false;
  40. var pinchScale = 0;
  41. /********************************************************************
  42. * Variables containing the canvas and its context. *
  43. ********************************************************************/
  44. var canvas;
  45. var ctx;
  46. /********************************************************************
  47. * Variables containing the number of elements. *
  48. ********************************************************************/
  49. var totalVert;
  50. var totalMaterial = 0;
  51. var totalFace
  52. /********************************************************************
  53. * Arrays containing the vertices, faces and materials. *
  54. ********************************************************************/
  55. var material;
  56. var vert;
  57. var face;
  58. /********************************************************************
  59. * Booleans to determine wich elements are to draw. *
  60. ********************************************************************/
  61. var dVerts = true;
  62. var dEdges = true;
  63. var dFaces = true;
  64. var dBackg = true;
  65. /********************************************************************
  66. * Booleans to indicate if mtl file should be used. *
  67. ********************************************************************/
  68. var hasMtl = true;
  69. var useMtl = true;
  70. /********************************************************************
  71. * Global variables that will contain the position of the mouse in *
  72. * the previous frame to calculate rotation. *
  73. ********************************************************************/
  74. var pX = null;
  75. var pY = null;
  76. /********************************************************************
  77. * Function that initializes the canvas, assignin it to the HTML *
  78. * element, and set the required mouse events. *
  79. * #parameters: *
  80. * canv (canvas): canvas to use. If omited, the one named *
  81. * named "ObJSCanvas" will be used. *
  82. * #return: nothing *
  83. * #scope: public *
  84. ********************************************************************/
  85. this.initCanvas = function(canv){
  86. if (!canvasInitialized){
  87. if (canv!= null)
  88. canvas = canv;
  89. else
  90. canvas = document.getElementById("ObJSCanvas");
  91. ctx = canvas.getContext("2d");
  92. ctx.translate(canvas.width / 2, canvas.height / 2);
  93. canvas.onmousedown = function(e){
  94. pX = e.offsetX==undefined?e.layerX:e.offsetX;
  95. pY = e.offsetY==undefined?e.layerY:e.offsetY;
  96. mDown = true;
  97. };
  98. canvas.onmouseup = function(e){
  99. if(mDown)
  100. mouseClick(e);
  101. pX = null;
  102. pY = null;
  103. mDown = false;
  104. };
  105. canvas.onmousemove = function(e){
  106. if(!mDown)
  107. return;
  108. var x = e.offsetX==undefined?e.layerX:e.offsetX;
  109. var y = e.offsetY==undefined?e.layerY:e.offsetY;
  110. if (e.shiftKey){
  111. thisObJS.moveHorizontal(x - pX);
  112. thisObJS.moveVertical(y - pY);
  113. }
  114. else{
  115. thisObJS.rotateY(x - pX);
  116. thisObJS.rotateX(y - pY);
  117. }
  118. pX = x;
  119. pY = y;
  120. return false;
  121. };
  122. canvas.onmouseout = function(e){
  123. if(mDown)
  124. mDown = false;
  125. }
  126. canvas.addEventListener('mousewheel',function(e){
  127. e.preventDefault();
  128. if (event.wheelDelta > 0)
  129. thisObJS.zoom(1);
  130. else
  131. thisObJS.zoom(-1);
  132. return false;
  133. }, false);
  134. canvas.addEventListener('touchstart',function(e){
  135. if(e.touches.length == 2) {
  136. pinch = true;
  137. pinchScale = Math.sqrt((e.touches[0].clientX-e.touches[1].clientX) * (e.touches[0].clientX-e.touches[1].clientX) + (e.touches[0].clientY-e.touches[1].clientY) * (e.touches[0].clientY-e.touches[1].clientY));
  138. }
  139. return false;
  140. }, false);
  141. canvas.addEventListener('touchend',function(e){
  142. if(pinch)
  143. pinch = false;
  144. return false;
  145. }, false);
  146. canvas.addEventListener('touchcancel',function(e){
  147. if(pinch)
  148. pinch = false;
  149. return false;
  150. }, false);
  151. canvas.addEventListener('touchleave',function(e){
  152. if(pinch)
  153. pinch = false;
  154. return false;
  155. }, false);
  156. canvas.addEventListener('touchmove',function(e){
  157. e.preventDefault();
  158. if(pinch){
  159. var dist = Math.sqrt((e.touches[0].clientX-e.touches[1].clientX) * (e.touches[0].clientX-e.touches[1].clientX) + (e.touches[0].clientY-e.touches[1].clientY) * (e.touches[0].clientY-e.touches[1].clientY));
  160. if (dist > pinchScale)
  161. thisObJS.zoom(1);
  162. else if (dist < pinchScale)
  163. thisObJS.zoom(-1);
  164. pinchScale = dist;
  165. }
  166. else{
  167. var x = e.touches[0].clientX
  168. var y = e.touches[0].clientY;
  169. thisObJS.rotateY(x - pX);
  170. thisObJS.rotateX(y - pY);
  171. pX = x;
  172. pY = y;
  173. }
  174. return false;
  175. }, false);
  176. canvasInitialized = true;
  177. }
  178. };
  179. /********************************************************************
  180. * Main function, called every time a file is to be loaded. *
  181. * #parameters: *
  182. * file (string): name of the file, without path or extension. *
  183. * #return: nothing *
  184. * #scope: public *
  185. ********************************************************************/
  186. this.load = function(file){
  187. if(!canvasInitialized)
  188. initCanvas();
  189. //Get obj file
  190. var xmlhttp = new XMLHttpRequest();
  191. xmlhttp.open("GET", file, false);
  192. xmlhttp.send();
  193. var fileContent = xmlhttp.responseText;
  194. //Get mtl file
  195. xmlhttp = new XMLHttpRequest();
  196. xmlhttp.open("GET",file.substring(0, file.lastIndexOf(".")) + ".mtl", false);
  197. xmlhttp.send();
  198. var mtlContent = xmlhttp.responseText;
  199. initArrays();
  200. readFile(fileContent);
  201. readMtlFile(mtlContent);
  202. draw();
  203. };
  204. /********************************************************************
  205. * Getters that determine if an element is being drawn. *
  206. ********************************************************************/
  207. this.isBackgroundDrawn = function(){
  208. return dBackg;
  209. };
  210. this.isVertexDrawn = function(){
  211. return dVerts;
  212. };
  213. this.isEdgeDrawn = function(){
  214. return dEdges;
  215. };
  216. this.isFaceDrawn = function(){
  217. return dFaces;
  218. };
  219. /********************************************************************
  220. * Getters that determine if the model has associated materials. *
  221. ********************************************************************/
  222. this.hasMaterial = function(){
  223. return hasMtl;
  224. };
  225. /********************************************************************
  226. * Getters for the color of the elements. *
  227. ********************************************************************/
  228. this.getBackgroundColor = function (){
  229. var str = backColor;
  230. var r = str.substring(5, str.indexOf(', '));
  231. str = str.substring(str.indexOf(', ') + 2);
  232. var g = str.substring(0, str.indexOf(', '));
  233. str = str.substring(str.indexOf(', ') + 2);
  234. var b = str.substring(0, str.indexOf(', '));
  235. var a = 1;
  236. return {red: r, green: g, blue: b, alpha: a};
  237. };
  238. this.getVertexColor = function (){
  239. var str = vertColor;
  240. var r = str.substring(5, str.indexOf(', '));
  241. str = str.substring(str.indexOf(', ') + 2);
  242. var g = str.substring(0, str.indexOf(', '));
  243. str = str.substring(str.indexOf(', ') + 2);
  244. var b = str.substring(0, str.indexOf(', '));
  245. var a = 1;
  246. return {red: r, green: g, blue: b, alpha: a};
  247. };
  248. this.getEdgeColor = function (){
  249. var str = edgeColor;
  250. var r = str.substring(5, str.indexOf(', '));
  251. str = str.substring(str.indexOf(', ') + 2);
  252. var g = str.substring(0, str.indexOf(', '));
  253. str = str.substring(str.indexOf(', ') + 2);
  254. var b = str.substring(0, str.indexOf(', '));
  255. var a = 1;
  256. return {red: r, green: g, blue: b, alpha: a};
  257. };
  258. this.getFaceColor = function (){
  259. var str = faceColor;
  260. var r = str.substring(5, str.indexOf(', '));
  261. str = str.substring(str.indexOf(', ') + 2);
  262. var g = str.substring(0, str.indexOf(', '));
  263. str = str.substring(str.indexOf(', ') + 2);
  264. var b = str.substring(0, str.indexOf(', '));
  265. str = str.substring(str.indexOf(', ') + 2);
  266. var a = str.substring(0, str.indexOf(')'));
  267. return {red: r, green: g, blue: b, alpha: a};
  268. };
  269. /********************************************************************
  270. * Functions switching the elements drawn (dVerts, dEdges, dFaces). *
  271. * #parameters: *
  272. * on (boolean): indicating if the element is to be drawn. *
  273. * #return: nothing *
  274. * #scope: public *
  275. ********************************************************************/
  276. this.drawVertices = function(on){
  277. if (on == true || on == false){
  278. dVerts = on;
  279. draw();
  280. }
  281. };
  282. this.drawEdges = function(on){
  283. if (on == true || on == false){
  284. dEdges = on;
  285. draw();
  286. }
  287. };
  288. this.drawFaces = function(on){
  289. if (on == true || on == false){
  290. dFaces = on;
  291. draw();
  292. }
  293. };
  294. this.drawBackground = function(on){
  295. if (on == true || on == false){
  296. dBackg = on;
  297. draw();
  298. }
  299. };
  300. /********************************************************************
  301. * Functions switching the color of the elements. *
  302. * #parameters: *
  303. * code (string): hex color value, in #fff or #ffffff form. If *
  304. * wrong, a message will be printed to console, *
  305. * and nothing will be changed. *
  306. * #return: nothing *
  307. * #scope: public *
  308. ********************************************************************/
  309. this.setVerticesColor = function(code){
  310. if (isColor(code)){
  311. var color = hexToRgb(code);
  312. vertColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  313. draw();
  314. }
  315. else
  316. console.log("setVerticesColor(" + code + ") ERROR: " + code + " not a valid hex color");
  317. };
  318. this.setEdgesColor = function(code){
  319. if (isColor(code)){
  320. var color = hexToRgb(code);
  321. edgeColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  322. draw();
  323. }
  324. else
  325. console.log("setEdgesColor(" + code + ") ERROR: " + code + " not a valid hex color");
  326. };
  327. this.setFacesColor = function(code){
  328. if (isColor(code)){
  329. var color = hexToRgb(code);
  330. faceColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  331. draw();
  332. }
  333. else
  334. console.log("setFacesColor(" + code + ") ERROR: " + code + " not a valid hex color");
  335. };
  336. this.setBackgroundColor = function(code){
  337. if (isColor(code)){
  338. var color = hexToRgb(code);
  339. backColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  340. draw();
  341. }
  342. else
  343. console.log("setBackgroundColor(" + code + ") ERROR: " + code + " not a valid hex color");
  344. };
  345. /********************************************************************
  346. * Function switching the use of mtl file for color. *
  347. * #parameters: *
  348. * value (boolean): indicating if the element is to be drawn. *
  349. * #return: nothing *
  350. * #scope: public *
  351. ********************************************************************/
  352. this.linkMaterial = function(value){
  353. useMtl = value;
  354. draw();
  355. }
  356. /********************************************************************
  357. * Function switching the alpha value of the faces. *
  358. * #parameters: *
  359. * percent (int): Value (0-100) of alpha. Must be processed (0-1) *
  360. * #return: nothing *
  361. * #scope: public *
  362. ********************************************************************/
  363. this.setAlpha = function(percent){
  364. if (percent >= 0 && percent <= 100){
  365. faceAlpha = percent / 100;
  366. faceColor = faceColor.substring(0, faceColor.lastIndexOf(",") + 2) + faceAlpha + ")";
  367. draw();
  368. }
  369. else
  370. console.log("setAlpha(" + percent + "); ERROR: Only values between 0 and 100 are allowed");
  371. };
  372. /********************************************************************
  373. * Function switching the rotation speed. *
  374. * #parameters: *
  375. * percent (int): Value (0-10) of speed. *
  376. * #return: nothing *
  377. * #scope: public *
  378. ********************************************************************/
  379. this.setRotationSpeed = function(percent){
  380. if (percent >= 0 && percent <= 10){
  381. rotationSpeed = Math.round((10 - percent) * 30);
  382. if (rotationSpeed == 0)
  383. rotationSpeed = 1;
  384. }
  385. else
  386. console.log("setRotationSpeed(" + percent + "); ERROR: Only values between 0 and 10 are allowed");
  387. }
  388. /********************************************************************
  389. * Functions that rotate elements in the canvas along the *
  390. * correspondent axys, calculating the new position for each vertex *
  391. * in the vert array. *
  392. * #parameters: *
  393. * des (int): distance to rotate. *
  394. * #return: nothing *
  395. * #scope: public *
  396. ********************************************************************/
  397. this.rotateY = function(des){
  398. for (var i = 0; i < vert.length; i ++) {
  399. var x = vert[i][0];
  400. var z = vert[i][2];
  401. vert[i][0] = x * Math.cos(des / rotationSpeed) - z * Math.sin(des / rotationSpeed);
  402. vert[i][2] = z * Math.cos(des / rotationSpeed) + x * Math.sin(des / rotationSpeed);
  403. }
  404. draw();
  405. };
  406. this.rotateX = function(des){
  407. for (var i = 0; i < vert.length; i ++) {
  408. var y = vert[i][1];
  409. var z = vert[i][2];
  410. vert[i][1] = y * Math.cos(des / rotationSpeed) - z * Math.sin(des / rotationSpeed);
  411. vert[i][2] = z * Math.cos(des / rotationSpeed) + y * Math.sin(des / rotationSpeed);
  412. }
  413. draw();
  414. };
  415. /********************************************************************
  416. * Function switching the movement speed of the model. *
  417. * #parameters: *
  418. * percent (int): Value (0-10) of speed. *
  419. * #return: nothing *
  420. * #scope: public *
  421. ********************************************************************/
  422. this.setMovementSpeed = function(percent){
  423. if (percent >= 0 && percent <= 10)
  424. moveSpeed = ((percent * 0.8) / 10) + 0.01;
  425. else
  426. console.log("setMoveSpeed(" + percent + "); ERROR: Only values between 0 and 10 are allowed");
  427. }
  428. /********************************************************************
  429. * Functions that move elements in the canvas along the selected *
  430. * direction, calculating the new position for each vertex in the *
  431. * vert array. *
  432. * #parameters: *
  433. * des (int): distance to move. *
  434. * #return: nothing *
  435. * #scope: public *
  436. ********************************************************************/
  437. this.moveVertical = function(des){
  438. for (var i = 0; i < vert.length; i ++)
  439. vert[i][1] = (vert[i][1] * 1) + des * (moveSpeed / 50);
  440. draw();
  441. };
  442. this.moveHorizontal = function(des){
  443. for (var i = 0; i < vert.length; i ++)
  444. vert[i][0] = (vert[i][0] * 1) + des * (moveSpeed / 50);
  445. draw();
  446. };
  447. /********************************************************************
  448. * Function switching the zoom speede of the faces. *
  449. * #parameters: *
  450. * percent (int): Value (0-100) of speed. *
  451. * #return: nothing *
  452. * #scope: public *
  453. ********************************************************************/
  454. this.setZoomSpeed = function(percent){
  455. if (percent >= 0 && percent <= 10)
  456. zoomSpeed = ((percent * 0.8) / 10) + 0.01;
  457. else
  458. console.log("setZoomSpeed(" + percent + "); ERROR: Only values between 0 and 10 are allowed");
  459. }
  460. /********************************************************************
  461. * Function that changes the scale variable, witch results in a *
  462. * zoom in or zoom out effect. *
  463. * #parameters: none *
  464. * #return: nothing *
  465. * #scope: public *
  466. ********************************************************************/
  467. this.zoom = function(val){
  468. scale = scale + val * scale * zoomSpeed;
  469. draw();
  470. };
  471. /********************************************************************
  472. * Function that clears the arrays and the canvas. Use to unload a *
  473. * model. *
  474. * #parameters: none *
  475. * #return: nothing *
  476. * #scope: public *
  477. ********************************************************************/
  478. this.clear = function(){
  479. initArrays();
  480. clearCanvas();
  481. };
  482. /********************************************************************
  483. * Function that turns a hex color code in RGB. *
  484. * stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb *
  485. * #parameters: *
  486. * hex (string): color code, for example "#33ff99" *
  487. * #return: (Array) r, g, b, with their correspondent color. *
  488. * #scope: private *
  489. ********************************************************************/
  490. var hexToRgb = function(hex) {
  491. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  492. return result ? {
  493. r: parseInt(result[1], 16),
  494. g: parseInt(result[2], 16),
  495. b: parseInt(result[3], 16)
  496. } : null;
  497. };
  498. /********************************************************************
  499. * Function that checks if a string is a valid hexadecimal color *
  500. * code, in the format '#ffffff' or '#fff' *
  501. * #parameters: *
  502. * code (string): Code to check. *
  503. * #return: (Boolean) True if valid color code, false otherwise. *
  504. * #scope: private *
  505. ********************************************************************/
  506. var isColor = function(code){
  507. if (code[0] != '#')
  508. return false;
  509. if (code.length != 4 && code.length != 7)
  510. return false
  511. for (var i = 1; i < code.length; i ++)
  512. if (code[i] < '0' || (code[i] > 9 && code[i] < 'A') || (code[i] > 'Z' && code[i] < 'a') || code[i] > 'z')
  513. return false;
  514. return true;
  515. };
  516. /********************************************************************
  517. * Function that clears the canvas and gets it ready to draw on it. *
  518. * #parameters: none *
  519. * #return: nothing *
  520. * #scope: private *
  521. ********************************************************************/
  522. var clearCanvas = function(){
  523. ctx.clearRect(0, 0, canvas.width, canvas.height);
  524. if (dBackg)
  525. ctx.fillStyle = backColor;
  526. else
  527. ctx.fillStyle = "#ffffff";
  528. ctx.fillRect(-canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);
  529. };
  530. /********************************************************************
  531. * Function initializing the arrays obj, vert and face as empty *
  532. * arrays. *
  533. * #parameters: none *
  534. * #return: nothing *
  535. * #scope: private *
  536. ********************************************************************/
  537. var initArrays = function(){
  538. material = null;
  539. vert = null;
  540. face = null;
  541. material = new Array();
  542. vert = new Array();
  543. face = new Array();
  544. };
  545. /********************************************************************
  546. * Function tat populates the vert[] array with and array of three *
  547. * elements, containig the coordinates, and the face[] array with *
  548. * the vertices forming the face, plus one element indicating the *
  549. * codename of the material. *
  550. * #parameters: *
  551. * text (string): the content of the obj file. *
  552. * #return: nothing *
  553. * #scope: private *
  554. ********************************************************************/
  555. var readFile = function(text){
  556. var line;
  557. var v = 0;
  558. var f = 0;
  559. var m = 0;
  560. var max = 0;
  561. var j;
  562. var dist;
  563. var fac;
  564. var mat = "null";
  565. text = text + "\n";
  566. while (text.indexOf("\n") != -1){
  567. line = text.substring(0, text.indexOf("\n"));
  568. if (line.substring(0, 2) == "v "){
  569. vert[v] = new Array(3);
  570. line = line.substring(2);
  571. vert[v][0] = line.substring(0, line.indexOf(" "));
  572. line = line.substring(line.indexOf(" ") + 1);
  573. vert[v][1] = line.substring(0, line.indexOf(" "));
  574. line = line.substring(line.indexOf(" ") + 1);
  575. vert[v][2] = line;
  576. dist = Math.sqrt(vert[v][0] * vert[v][0] + vert[v][1] * vert[v][1] + vert[v][2] * vert[v][2]);
  577. if (dist > max)
  578. max = dist;
  579. v = v + 1;
  580. }
  581. else if (line.substring(0,2) == "f "){
  582. line = line.substring(2);
  583. face[f] = new Array();
  584. j = 0;
  585. while(line.indexOf(" ") != -1){
  586. face[f][j] = line.substring(0, line.indexOf(" "));
  587. if (face[f][j].indexOf('/') != -1)
  588. face[f][j] = face[f][j].substring(0, face[f][j].indexOf('/'));
  589. face[f][j] = face[f][j] - 1;
  590. line = line.substring(line.indexOf(" ") + 1);
  591. j = j + 1;
  592. }
  593. face[f][j] = line;
  594. if (face[f][j].indexOf('/') != -1)
  595. face[f][j] = face[f][j].substring(0, face[f][j].indexOf('/'));
  596. face[f][j] = face[f][j] - 1;
  597. face[f][j + 1] = mat;
  598. f = f + 1;
  599. }
  600. else if (line.substring(0, 6) == "usemtl"){
  601. mat = line.substring(7);
  602. }
  603. text = text.substring(text.indexOf("\n") + 1);
  604. }
  605. scale = calculateScale(max);
  606. totalVert = vert.length;
  607. totalFace = face.length;
  608. };
  609. /********************************************************************
  610. * Function tat populates the material[] array with an array *
  611. * containig, four values: the material name, and the three RGB *
  612. * values. *
  613. * #parameters: *
  614. * text (string): the content of the mtl file. *
  615. * #return: nothing *
  616. * #scope: private *
  617. ********************************************************************/
  618. var readMtlFile = function(text){
  619. text = text + "\n";
  620. i = -1;
  621. while (text.indexOf("\n") != -1){
  622. line = text.substring(0, text.indexOf("\n"));
  623. if (line.substring(0, 6) == "newmtl"){
  624. i = i + 1;
  625. material[i] = new Array(4);
  626. material[i][0] = line.substring(line.indexOf(" ") + 1);
  627. }
  628. //Kd, ddifuse color, usefull
  629. //Ka, ambient color, not now
  630. //Ks, specular color, not now
  631. //d or TR, transparency, not now
  632. else if (line.substring(0, 3) == "Kd "){
  633. line = line.substring(3);
  634. material[i][1] = line.substring(0, line.indexOf(" "));
  635. line = line.substring(line.indexOf(" ") + 1);
  636. material[i][2] = line.substring(0, line.indexOf(" "));
  637. line = line.substring(line.indexOf(" ") + 1);
  638. material[i][3] = line;
  639. }
  640. text = text.substring(text.indexOf("\n") + 1);
  641. }
  642. totalMaterial = material.length;
  643. if (totalMaterial == 0)
  644. hasMtl = false;
  645. };
  646. /********************************************************************
  647. * Function that automatically calculates the best scale for the *
  648. * modelermined number of elements, containing the verices that *
  649. * form a face, so the bigest dimension from the object can fit in *
  650. * the smallest dimension of the canvas. *
  651. * #parameters: *
  652. * text (int): the farthest vertex, from the center. *
  653. * #return: (int) The scale to be aplied. *
  654. * #scope: private *
  655. ********************************************************************/
  656. var calculateScale = function(max){
  657. var dim;
  658. if (canvas.width < canvas.height)
  659. dim = canvas.width;
  660. else
  661. dim = canvas.height;
  662. var sc = Math.round((0.95 * dim) / (2 * max));
  663. return sc;
  664. };
  665. /********************************************************************
  666. * Function that compares the average Z coordinate of two faces. *
  667. * Must be used when sorting the face array. *
  668. * #parameters: *
  669. * a (Array): One face. *
  670. * b (Array): The other face. *
  671. * #return: (int) -1, 1 or 0. *
  672. * #scope: private *
  673. ********************************************************************/
  674. var faceComparator = function(a,b){
  675. var aZ;
  676. var bZ;
  677. var i = 0;
  678. var sum = 0.0;
  679. while (i < a.length - 1){
  680. sum = sum + parseFloat(vert[a[i]][2]);
  681. i = i + 1;
  682. }
  683. aZ = sum / parseFloat(i);
  684. i = 0;
  685. sum = 0;
  686. while (i < b.length - 1){
  687. sum = sum + parseFloat(1 * vert[b[i]][2]);
  688. i = i + 1;
  689. }
  690. bZ = sum / parseFloat(i);
  691. if (aZ < bZ) return -1;
  692. if (aZ > bZ) return 1;
  693. return 0;
  694. };
  695. /********************************************************************
  696. * Function that writes text in the corner of the canvas. Must be *
  697. * called when everithing has been drawn. *
  698. * #parameters: none *
  699. * #return: nothing *
  700. * #scope: private *
  701. ********************************************************************/
  702. var writeCredits = function(){
  703. ctx.fillStyle = textColor;
  704. ctx.font = "12px Arial";
  705. var h = canvas.height / 2 - 14;
  706. var w = 10 - (canvas.width / 2);
  707. ctx.fillText("ObJS: " + totalVert + " vertices " + totalFace + " faces " + totalMaterial + " materials", w, h);
  708. };
  709. /********************************************************************
  710. * Function that draws th vertices, faces and edges in the canvas. *
  711. * #parameters: none *
  712. * #return: nothing *
  713. * #scope: private *
  714. ********************************************************************/
  715. var draw = function(){
  716. face = face.sort(faceComparator).reverse();
  717. clearCanvas();
  718. for (var i = 0; i < face.length; i++){
  719. ctx.strokeStyle = edgeColor;
  720. ctx.fillStyle = vertColor;
  721. ctx.beginPath();
  722. ctx.moveTo(scale * vert[face[i][0]][0], scale * vert[face[i][0]][1]);
  723. for (var j = 1; j < face[i].length - 1; j++) {
  724. ctx.lineTo(scale * vert[face[i][j]][0], scale * vert[face[i][j]][1]);
  725. if(dEdges)
  726. ctx.stroke();
  727. if(dVerts){
  728. var x = scale * vert[face[i][j]][0] - (vertSize / 2);
  729. var w = vertSize;
  730. var y = scale * vert[face[i][j]][1] - (vertSize / 2);
  731. var h = vertSize;
  732. ctx.fillRect(x, y, w, h);
  733. }
  734. }
  735. ctx.closePath();
  736. if (useMtl){
  737. //Get material with the same name as the one in the last element of the face
  738. j = 0;
  739. while (material[j][0] != face[i][face[i].length - 1] && j < material.length)
  740. j = j + 1;
  741. if (material[j][0] == face[i][face[i].length - 1])
  742. ctx.fillStyle = "rgba(" + Math.round(255 * material[j][1]) + ", " + Math.round(255 * material[j][2]) + ", " + Math.round(255 * material[j][3]) + ", " + faceAlpha + ")";
  743. else
  744. ctx.fillStyle = faceColor;
  745. }
  746. else
  747. ctx.fillStyle = faceColor;
  748. if(dFaces)
  749. ctx.fill();
  750. }
  751. writeCredits();
  752. };
  753. /********************************************************************
  754. * TODO: Function used when something in the canvas is clicked. *
  755. * #parameters: none *
  756. * #return: nothing *
  757. * #scope: private *
  758. ********************************************************************/
  759. var mouseClick = function(){
  760. };
  761. thisObJS = this;
  762. return this;
  763. }