ObJS.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  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(file, canv){
  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. /********************************************************************
  21. * Variable containing this object, to be refered from nested *
  22. * functions. *
  23. ********************************************************************/
  24. var thisObJS;
  25. /********************************************************************
  26. * Parameter used to scale the measures in the .obj file. Can be *
  27. * integer or float, greater than 0. 50 is a good default. *
  28. ********************************************************************/
  29. var scale;
  30. /********************************************************************
  31. * Variable to determine if the canvas has been initialized. *
  32. ********************************************************************/
  33. var canvasInitialized = false;
  34. /********************************************************************
  35. * Variable to determine if the mouse button is being holded down. *
  36. ********************************************************************/
  37. var mDown = false;
  38. /********************************************************************
  39. * Variables containing the canvas and its context. *
  40. ********************************************************************/
  41. var canvas;
  42. var ctx;
  43. /********************************************************************
  44. * Variables containing the number of elements. *
  45. ********************************************************************/
  46. var totalVert;
  47. var totalMaterial;
  48. var totalFace
  49. /********************************************************************
  50. * Arrays containing the vertices, faces and materials. *
  51. ********************************************************************/
  52. var material;
  53. var vert;
  54. var face;
  55. /********************************************************************
  56. * Booleans to determine wich elements are to draw. *
  57. ********************************************************************/
  58. var dVerts = true;
  59. var dEdges = true;
  60. var dFaces = true;
  61. var dBackg = true;
  62. /********************************************************************
  63. * Booleans to indicate if mtl file should be used. *
  64. ********************************************************************/
  65. var useMtl = true;
  66. /********************************************************************
  67. * Global variables that will contain the position of the mouse in *
  68. * the previous frame to calculate rotation. *
  69. ********************************************************************/
  70. var pX = null;
  71. var pY = null;
  72. /********************************************************************
  73. * Function that initializes the canvas, assignin it to the HTML *
  74. * element, and set the required mouse events. *
  75. * #parameters: *
  76. * canv (canvas): canvas to use. If omited, the one named *
  77. * named "ObJSCanvas" will be used. *
  78. * #return: nothing *
  79. * #scope: public *
  80. ********************************************************************/
  81. this.initCanvas = function(canv){
  82. if (!canvasInitialized){
  83. if (canv!= null)
  84. canvas = canv;
  85. else
  86. canvas = document.getElementById("ObJSCanvas");
  87. ctx = canvas.getContext("2d");
  88. ctx.translate(canvas.width / 2, canvas.height / 2);
  89. canvas.onmousedown = function(e){
  90. pX = e.offsetX==undefined?e.layerX:e.offsetX;
  91. pY = e.offsetY==undefined?e.layerY:e.offsetY;
  92. mDown = true;
  93. };
  94. canvas.onmouseup = function(e){
  95. if(mDown)
  96. mouseClick(e);
  97. pX = null;
  98. pY = null;
  99. mDown = false;
  100. };
  101. canvas.onmousemove = function(e){
  102. if(!mDown)
  103. return;
  104. var x = e.offsetX==undefined?e.layerX:e.offsetX;
  105. var y = e.offsetY==undefined?e.layerY:e.offsetY;
  106. thisObJS.rotateY(x - pX);
  107. thisObJS.rotateX(y - pY);
  108. pX = x;
  109. pY = y;
  110. draw();
  111. return false;
  112. };
  113. canvas.addEventListener('mousewheel',function(event){
  114. if (event.wheelDelta > 0)
  115. thisObJS.zoom("-");
  116. else
  117. thisObJS.zoom("+");
  118. return false;
  119. }, false);
  120. canvasInitialized = true;
  121. }
  122. };
  123. /********************************************************************
  124. * Main function, called every time a file is to be loaded. *
  125. * #parameters: *
  126. * file (string): name of the file, without path or extension. *
  127. * #return: nothing *
  128. * #scope: public *
  129. ********************************************************************/
  130. this.load = function(file){
  131. //Get obj file
  132. var xmlhttp = new XMLHttpRequest();
  133. xmlhttp.open("GET", file, false);
  134. xmlhttp.send();
  135. var fileContent = xmlhttp.responseText;
  136. //Get mtl file
  137. xmlhttp = new XMLHttpRequest();
  138. xmlhttp.open("GET",file.substring(0, file.lastIndexOf(".")) + ".mtl", false);
  139. console.log("GET" + file.substring(0, file.lastIndexOf(".")) + ".mtl");
  140. xmlhttp.send();
  141. var mtlContent = xmlhttp.responseText;
  142. initArrays();
  143. readFile(fileContent);
  144. readMtlFile(mtlContent);
  145. draw();
  146. };
  147. /********************************************************************
  148. * Function switching the elements to draw (dVerts, dEdges, dFaces) *
  149. * #parameters: *
  150. * name (string): key to the element to draw. *
  151. * value (boolean): indicating if the element is to be drawn. *
  152. * #return: nothing *
  153. * #scope: public *
  154. ********************************************************************/
  155. this.drawElement = function(name, value){
  156. switch (name){
  157. case "verts":
  158. dVerts = value;
  159. break;
  160. case "edges":
  161. dEdges = value;
  162. break;
  163. case "faces":
  164. dFaces = value;
  165. break;
  166. case "backg":
  167. dBackg = value;
  168. break;
  169. }
  170. draw();
  171. };
  172. /********************************************************************
  173. * Function that turns a hex color code in RGB. *
  174. * stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb *
  175. * #parameters: *
  176. * hex (string): color code, for example "#33ff99" *
  177. * #return: (Array) r, g, b, with their correspondent color. *
  178. * #scope: private *
  179. ********************************************************************/
  180. var hexToRgb = function(hex) {
  181. var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  182. return result ? {
  183. r: parseInt(result[1], 16),
  184. g: parseInt(result[2], 16),
  185. b: parseInt(result[3], 16)
  186. } : null;
  187. };
  188. /********************************************************************
  189. * Function switching the color of the elements. *
  190. * #parameters: *
  191. * name (string): key to the element to colorize. *
  192. * value (boolean): indicating if the element is to be drawn. *
  193. * #return: nothing *
  194. * #scope: public *
  195. ********************************************************************/
  196. this.colorElement = function(name, value){
  197. var color = hexToRgb(value)
  198. var str = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)"
  199. switch (name){
  200. case "backg":
  201. backColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  202. break;
  203. case "verts":
  204. vertColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  205. break;
  206. case "edges":
  207. edgeColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", 1)";
  208. break;
  209. case "faces":
  210. faceColor = "rgba(" + color.r + ", " + color.g + ", " + color.b + ", " + faceAlpha + ")";
  211. break;
  212. }
  213. draw();
  214. };
  215. /********************************************************************
  216. * Function switching the alpha value of the faces. *
  217. * #parameters: *
  218. * percent (int): Value (0-100) of alpha. Must be processed (0-1) *
  219. * #return: nothing *
  220. * #scope: public *
  221. ********************************************************************/
  222. this.setAlpha = function(percent){
  223. if (percent >= 0 && percent <= 100){
  224. faceAlpha = percent / 100;
  225. faceColor = faceColor.substring(0, faceColor.lastIndexOf(",") + 2) + faceAlpha + ")";
  226. draw();
  227. }
  228. else
  229. console.log("setAlpha(" + percent + "); ERROR: Only values between 0 and 100 are allowed");
  230. };
  231. /********************************************************************
  232. * Function switching the rotation speed. *
  233. * #parameters: *
  234. * percent (int): Value (0-10) of speed. *
  235. * #return: nothing *
  236. * #scope: public *
  237. ********************************************************************/
  238. this.setRotationSpeed = function(percent){
  239. if (percent >= 0 && percent <= 10){
  240. rotationSpeed = Math.round((10 - percent) * 30);
  241. if (rotationSpeed == 0)
  242. rotationSpeed = 1;
  243. }
  244. else
  245. console.log("setRotationSpeed(" + percent + "); ERROR: Only values between 0 and 10 are allowed");
  246. }
  247. /********************************************************************
  248. * Function that rotates elements in the canvas along the Y axis, *
  249. * calculating the new position for each vertex in the vert array. *
  250. * #parameters: *
  251. * des (int): mouse displacement from the last frame. *
  252. * #return: nothing *
  253. * #scope: public *
  254. ********************************************************************/
  255. this.rotateY = function(des){
  256. for (var i = 0; i < vert.length; i ++) {
  257. var x = vert[i][0];
  258. var z = vert[i][2];
  259. vert[i][0] = x * Math.cos(des / rotationSpeed) - z * Math.sin(des / rotationSpeed);
  260. vert[i][2] = z * Math.cos(des / rotationSpeed) + x * Math.sin(des / rotationSpeed);
  261. }
  262. };
  263. /********************************************************************
  264. * Function that rotates elements in the canvas along the X axis, *
  265. * calculating the new position for each vertex in the vert array. *
  266. * #parameters: *
  267. * des (int): mouse displacement from the last frame. *
  268. * #return: nothing *
  269. * #scope: public *
  270. ********************************************************************/
  271. this.rotateX = function(des){
  272. for (var i = 0; i < vert.length; i ++) {
  273. var y = vert[i][1];
  274. var z = vert[i][2];
  275. vert[i][1] = y * Math.cos(des / rotationSpeed) - z * Math.sin(des / rotationSpeed);
  276. vert[i][2] = z * Math.cos(des / rotationSpeed) + y * Math.sin(des / rotationSpeed);
  277. }
  278. };
  279. /********************************************************************
  280. * Function switching the zoom speede of the faces. *
  281. * #parameters: *
  282. * percent (int): Value (0-100) of speed. *
  283. * #return: nothing *
  284. * #scope: public *
  285. ********************************************************************/
  286. this.setZoomSpeed = function(percent){
  287. if (percent >= 0 && percent <= 10)
  288. zoomSpeed = ((percent * 0.8) / 10) + 0.01;
  289. else
  290. console.log("setZoomSpeed(" + percent + "); ERROR: Only values between 0 and 10 are allowed");
  291. }
  292. /********************************************************************
  293. * Function that changes the scale variable, witch results in a *
  294. * zoom in or zoom out effect. *
  295. * #parameters: none *
  296. * #return: nothing *
  297. * #scope: public *
  298. ********************************************************************/
  299. this.zoom = function(dir){
  300. if (dir == "-")
  301. scale = Math.round(scale * (1 + zoomSpeed));
  302. if (dir == "+")
  303. scale = Math.round(scale * (1 - zoomSpeed));
  304. draw();
  305. };
  306. this.clear = function(){
  307. initArrays();
  308. clearCanvas();
  309. }
  310. /********************************************************************
  311. * Function that clears the canvas and gets it ready to draw on it. *
  312. * #parameters: none *
  313. * #return: nothing *
  314. * #scope: public *
  315. ********************************************************************/
  316. var clearCanvas = function(){
  317. ctx.clearRect(0, 0, canvas.width, canvas.height);
  318. if (dBackg)
  319. ctx.fillStyle = backColor;
  320. else
  321. ctx.fillStyle = "#ffffff";
  322. ctx.fillRect(-canvas.width / 2, -canvas.height / 2, canvas.width, canvas.height);
  323. };
  324. /********************************************************************
  325. * Function initializing the arrays obj, vert and face as empty *
  326. * arrays. *
  327. * #parameters: none *
  328. * #return: nothing *
  329. * #scope: private *
  330. ********************************************************************/
  331. var initArrays = function(){
  332. material = null;
  333. vert = null;
  334. face = null;
  335. material = new Array();
  336. vert = new Array();
  337. face = new Array();
  338. };
  339. /********************************************************************
  340. * Function tat populates the vert[] array with and array of three *
  341. * elements, containig the coordinates, and the face[] array with *
  342. * the vertizes forming the face, plus one element indicating the *
  343. * codename of the material. *
  344. * #parameters: *
  345. * text (string): the content of the obj file. *
  346. * #return: nothing *
  347. * #scope: private *
  348. ********************************************************************/
  349. var readFile = function(text){
  350. var line;
  351. var v = 0;
  352. var f = 0;
  353. var m = 0;
  354. var max = 0;
  355. var j;
  356. var dist;
  357. var mat = "null";
  358. text = text + "\n";
  359. while (text.indexOf("\n") != -1){
  360. line = text.substring(0, text.indexOf("\n"));
  361. if (line.substring(0, 2) == "v "){
  362. vert[v] = new Array(3);
  363. line = line.substring(2);
  364. vert[v][0] = line.substring(0, line.indexOf(" "));
  365. line = line.substring(line.indexOf(" ") + 1);
  366. vert[v][1] = line.substring(0, line.indexOf(" "));
  367. line = line.substring(line.indexOf(" ") + 1);
  368. vert[v][2] = line;
  369. dist = Math.sqrt(vert[v][0] * vert[v][0] + vert[v][1] * vert[v][1] + vert[v][2] * vert[v][2]);
  370. if (dist > max)
  371. max = dist;
  372. v = v + 1;
  373. }
  374. else if (line.substring(0,2) == "f "){
  375. line = line.substring(2);
  376. face[f] = new Array();
  377. j = 0;
  378. while(line.indexOf(" ") != -1){
  379. face[f][j] = line.substring(0, line.indexOf(" ")) - 1;
  380. line = line.substring(line.indexOf(" ") + 1);
  381. j = j + 1;
  382. }
  383. face[f][j] = line - 1;
  384. face[f][j + 1] = mat;
  385. f = f + 1;
  386. }
  387. else if (line.substring(0, 6) == "usemtl"){
  388. mat = line.substring(7);
  389. }
  390. text = text.substring(text.indexOf("\n") + 1);
  391. }
  392. scale = calculateScale(max);
  393. totalVert = vert.length;
  394. totalFace = face.length;
  395. };
  396. /********************************************************************
  397. * Function tat populates the material[] array with an array *
  398. * containig, four values: the material name, and the three RGB *
  399. * values. *
  400. * #parameters: *
  401. * text (string): the content of the mtl file. *
  402. * #return: nothing *
  403. * #scope: private *
  404. ********************************************************************/
  405. var readMtlFile = function(text){
  406. text = text + "\n";
  407. i = -1;
  408. while (text.indexOf("\n") != -1){
  409. line = text.substring(0, text.indexOf("\n"));
  410. if (line.substring(0, 6) == "newmtl"){
  411. i = i + 1;
  412. material[i] = new Array(4);
  413. material[i][0] = line.substring(line.indexOf(" ") + 1);
  414. }
  415. //Kd, ddifuse color, usefull
  416. //Ka, ambient color, not now
  417. //Ks, specular color, not now
  418. //d or TR, transparency, not now
  419. else if (line.substring(0, 3) == "Kd "){
  420. line = line.substring(3);
  421. material[i][1] = line.substring(0, line.indexOf(" "));
  422. line = line.substring(line.indexOf(" ") + 1);
  423. material[i][2] = line.substring(0, line.indexOf(" "));
  424. line = line.substring(line.indexOf(" ") + 1);
  425. material[i][3] = line;
  426. }
  427. text = text.substring(text.indexOf("\n") + 1);
  428. }
  429. };
  430. /********************************************************************
  431. * Function that automatically calculates the best scale for the *
  432. * modelermined number of elements, containing the verices that *
  433. * form a face, so the bigest dimension from the object can fit in *
  434. * the smallest dimension of the canvas. *
  435. * #parameters: *
  436. * text (int): the farthest vertex, from the center. *
  437. * #return: (int) The scale to be aplied. *
  438. * #scope: private *
  439. ********************************************************************/
  440. var calculateScale = function(max){
  441. var dim;
  442. if (canvas.width < canvas.height)
  443. dim = canvas.width;
  444. else
  445. dim = canvas.height;
  446. var sc = Math.round((0.95 * dim) / (2 * max));
  447. return sc;
  448. };
  449. /********************************************************************
  450. * Function that compares the average Z coordinate of two faces. *
  451. * Must be used when sorting the face array. *
  452. * #parameters: *
  453. * a (Array): One face. *
  454. * b (Array): The other face. *
  455. * #return: (int) -1, 1 or 0. *
  456. * #scope: private *
  457. ********************************************************************/
  458. var faceComparator = function(a,b){
  459. var aZ;
  460. var bZ;
  461. var i = 0;
  462. var sum = 0.0;
  463. while (i < a.length - 1){
  464. sum = sum + parseFloat(vert[a[i]][2]);
  465. i = i + 1;
  466. }
  467. aZ = sum / parseFloat(i);
  468. i = 0;
  469. sum = 0;
  470. while (i < b.length - 1){
  471. sum = sum + parseFloat(1 * vert[b[i]][2]);
  472. i = i + 1;
  473. }
  474. bZ = sum / parseFloat(i);
  475. if (aZ < bZ) return -1;
  476. if (aZ > bZ) return 1;
  477. return 0;
  478. };
  479. /********************************************************************
  480. * Function that writes text in the corner of the canvas. Must be *
  481. * called when everithing has been drawn. *
  482. * #parameters: none *
  483. * #return: nothing *
  484. * #scope: private *
  485. ********************************************************************/
  486. var writeCredits = function(){
  487. ctx.fillStyle = textColor;
  488. ctx.font = "12px Arial";
  489. var h = canvas.height / 2 - 14;
  490. var w = 10 - (canvas.height / 2);
  491. ctx.fillText("ObJS " + totalVert + " vertizes " + totalFace + " faces", w, h);
  492. };
  493. /********************************************************************
  494. * Function that draws th vertizes, faces and edges in the canvas. *
  495. * #parameters: none *
  496. * #return: nothing *
  497. * #scope: private *
  498. ********************************************************************/
  499. var draw = function(){
  500. face = face.sort(faceComparator).reverse();
  501. clearCanvas();
  502. for (var i = 0; i < face.length; i++){
  503. ctx.strokeStyle = edgeColor;
  504. ctx.fillStyle = vertColor;
  505. ctx.beginPath();
  506. ctx.moveTo(scale * vert[face[i][0]][0], scale * vert[face[i][0]][1]);
  507. for (var j = 1; j < face[i].length - 1; j++) {
  508. ctx.lineTo(scale * vert[face[i][j]][0], scale * vert[face[i][j]][1]);
  509. if(dEdges)
  510. ctx.stroke();
  511. if(dVerts){
  512. var x = scale * vert[face[i][j]][0] - (vertSize / 2);
  513. var w = vertSize;
  514. var y = scale * vert[face[i][j]][1] - (vertSize / 2);
  515. var h = vertSize;
  516. ctx.fillRect(x, y, w, h);
  517. }
  518. }
  519. ctx.closePath();
  520. if (useMtl){
  521. //Get material with the same name as the one in the last element of the face
  522. j = 0;
  523. while (material[j][0] != face[i][face[i].length - 1] && j < material.length)
  524. j = j + 1;
  525. if (material[j][0] == face[i][face[i].length - 1])
  526. ctx.fillStyle = "rgba(" + Math.round(255 * material[j][1]) + ", " + Math.round(255 * material[j][2]) + ", " + Math.round(255 * material[j][3]) + ", " + faceAlpha + ")";
  527. else
  528. ctx.fillStyle = faceColor;
  529. }
  530. else
  531. ctx.fillStyle = faceColor;
  532. if(dFaces)
  533. ctx.fill();
  534. }
  535. writeCredits();
  536. };
  537. /********************************************************************
  538. * TODO: Function used when something in the canvas is clicked. *
  539. * #parameters: none *
  540. * #return: nothing *
  541. * #scope: private *
  542. ********************************************************************/
  543. var mouseClick = function(){
  544. };
  545. thisObJS = this;
  546. return this;
  547. }