Advertisement
Guest User

triangle.js

a guest
Oct 18th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. class MyTriangle extends MyPrimitive {
  2. constructor (scene, id, x1, y1, z1, x2, y2, z2, x3, y3, z3) {
  3. super (scene);
  4.  
  5. this.x1 = x1;
  6. this.y1 = y1;
  7. this.z1 = z1;
  8.  
  9. this.x2 = x2;
  10. this.y2 = y2;
  11. this.z2 = z2;
  12.  
  13. this.x3 = x3;
  14. this.y3 = y3;
  15. this.z3 = z3;
  16.  
  17. this.origCoords = [];
  18.  
  19. this.initBuffers();
  20. };
  21.  
  22. initBuffers() {
  23. this.vertices = [
  24. this.x1, this.y1, this.z1,
  25. this.x2, this.y2, this.z2,
  26. this.x3, this.y3, this.z3
  27. ];
  28.  
  29. // https://www.khronos.org/opengl/wiki/Calculating_a_Surface_Normal
  30. let u = [this.x2-this.x1, this.y2-this.y1, this.z2-this.z1]; // a p1p2
  31. let v = [this.x3-this.x1, this.y3-this.y1, this.z3-this.z1]; // c p3p1
  32. let w = [this.x3-this.x2, this.y3-this.y2, this.z3-this.z2]; // b p2p3
  33.  
  34. let nx = u[1]*v[2] - u[2]*v[1];
  35. let ny = u[2]*v[0] - u[0]*v[2];
  36. let nz = u[0]*v[1] - u[1]*v[0];
  37.  
  38. let vec = [nx, ny, nz];
  39. let norm = this.norm(vec);
  40.  
  41. this.normals = [
  42. nx/norm, ny/norm, nz/norm,
  43. nx/norm, ny/norm, nz/norm,
  44. nx/norm, ny/norm, nz/norm
  45. ];
  46.  
  47. this.indices = [
  48. 0, 1, 2
  49. ];
  50.  
  51. let a = this.norm(u);
  52. let b = this.norm(w);
  53. let c = this.norm(v);
  54.  
  55. let cosAlfa = (Math.pow(a, 2) - Math.pow(b, 2) + Math.pow(c, 2)) / (2 * a *c);
  56. let sinAlfa = Math.sqrt(1 - Math.pow (cosAlfa, 2));
  57.  
  58. this.tex2 = a;
  59. this.tex3 = [c*cosAlfa, c*sinAlfa];
  60.  
  61. this.texCoords = [
  62. 0,0,
  63. a,0,
  64. this.tex3[0], this.tex3[1]
  65. ];
  66.  
  67. this.texCoords = [...this.origCoords];
  68.  
  69. this.primitiveType=this.scene.gl.TRIANGLES;
  70. this.initGLBuffers();
  71. }
  72.  
  73. norm(vector){
  74. let norm = 0;
  75. vector.forEach(v => {
  76. norm += Math.pow(v, 2);
  77. });
  78. norm = Math.sqrt(norm);
  79.  
  80. return norm;
  81. }
  82.  
  83. updateTexCoords(length_s, length_t) {
  84. this.texCoords = [
  85. 0, 0,
  86. this.tex2/length_s, 0,
  87. this.tex3[0]/length_s, this.tex3[1]/length_t
  88. ];
  89.  
  90. this.updateTexCoordsGLBuffers();
  91.  
  92. }
  93. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement