mesh.ts 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. /**
  2. * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { Task } from 'mol-task'
  7. import { ValueCell } from 'mol-util'
  8. import { Vec3, Mat4 } from 'mol-math/linear-algebra'
  9. import { Sphere3D } from 'mol-math/geometry'
  10. import { transformPositionArray/* , transformDirectionArray, getNormalMatrix */ } from '../util';
  11. export interface Mesh {
  12. /** Number of vertices in the mesh */
  13. vertexCount: number,
  14. /** Number of triangles in the mesh */
  15. triangleCount: number,
  16. /** Vertex buffer as array of xyz values wrapped in a value cell */
  17. readonly vertexBuffer: ValueCell<Float32Array>,
  18. /** Index buffer as array of vertex index triplets wrapped in a value cell */
  19. readonly indexBuffer: ValueCell<Uint32Array>,
  20. /** Normal buffer as array of xyz values for each vertex wrapped in a value cell */
  21. readonly normalBuffer: ValueCell<Float32Array>,
  22. /** Group buffer as array of group ids for each vertex wrapped in a value cell */
  23. readonly groupBuffer: ValueCell<Float32Array>,
  24. /** Flag indicating if normals are computed for the current set of vertices */
  25. normalsComputed: boolean,
  26. /** Bounding sphere of the mesh */
  27. boundingSphere?: Sphere3D
  28. }
  29. export namespace Mesh {
  30. export function createEmpty(mesh?: Mesh): Mesh {
  31. const vb = mesh ? mesh.vertexBuffer.ref.value : new Float32Array(0)
  32. const ib = mesh ? mesh.indexBuffer.ref.value : new Uint32Array(0)
  33. const nb = mesh ? mesh.normalBuffer.ref.value : new Float32Array(0)
  34. const idb = mesh ? mesh.groupBuffer.ref.value : new Float32Array(0)
  35. return {
  36. vertexCount: 0,
  37. triangleCount: 0,
  38. vertexBuffer: mesh ? ValueCell.update(mesh.vertexBuffer, vb) : ValueCell.create(vb),
  39. indexBuffer: mesh ? ValueCell.update(mesh.indexBuffer, ib) : ValueCell.create(ib),
  40. normalBuffer: mesh ? ValueCell.update(mesh.normalBuffer, nb) : ValueCell.create(nb),
  41. groupBuffer: mesh ? ValueCell.update(mesh.groupBuffer, idb) : ValueCell.create(idb),
  42. normalsComputed: true,
  43. }
  44. }
  45. export function computeNormalsImmediate(surface: Mesh) {
  46. if (surface.normalsComputed) return;
  47. const normals = surface.normalBuffer.ref.value.length >= surface.vertexCount * 3
  48. ? surface.normalBuffer.ref.value : new Float32Array(surface.vertexBuffer.ref.value.length);
  49. const v = surface.vertexBuffer.ref.value, triangles = surface.indexBuffer.ref.value;
  50. const x = Vec3.zero(), y = Vec3.zero(), z = Vec3.zero(), d1 = Vec3.zero(), d2 = Vec3.zero(), n = Vec3.zero();
  51. for (let i = 0, ii = 3 * surface.triangleCount; i < ii; i += 3) {
  52. const a = 3 * triangles[i], b = 3 * triangles[i + 1], c = 3 * triangles[i + 2];
  53. Vec3.fromArray(x, v, a);
  54. Vec3.fromArray(y, v, b);
  55. Vec3.fromArray(z, v, c);
  56. Vec3.sub(d1, z, y);
  57. Vec3.sub(d2, y, x);
  58. Vec3.cross(n, d1, d2);
  59. normals[a] += n[0]; normals[a + 1] += n[1]; normals[a + 2] += n[2];
  60. normals[b] += n[0]; normals[b + 1] += n[1]; normals[b + 2] += n[2];
  61. normals[c] += n[0]; normals[c + 1] += n[1]; normals[c + 2] += n[2];
  62. }
  63. for (let i = 0, ii = 3 * surface.vertexCount; i < ii; i += 3) {
  64. const nx = normals[i];
  65. const ny = normals[i + 1];
  66. const nz = normals[i + 2];
  67. const f = 1.0 / Math.sqrt(nx * nx + ny * ny + nz * nz);
  68. normals[i] *= f; normals[i + 1] *= f; normals[i + 2] *= f;
  69. // console.log([normals[i], normals[i + 1], normals[i + 2]], [v[i], v[i + 1], v[i + 2]])
  70. }
  71. ValueCell.update(surface.normalBuffer, normals);
  72. surface.normalsComputed = true;
  73. }
  74. export function computeNormals(surface: Mesh): Task<Mesh> {
  75. return Task.create<Mesh>('Surface (Compute Normals)', async ctx => {
  76. if (surface.normalsComputed) return surface;
  77. await ctx.update('Computing normals...');
  78. computeNormalsImmediate(surface);
  79. return surface;
  80. });
  81. }
  82. export function transformImmediate(mesh: Mesh, t: Mat4) {
  83. transformRangeImmediate(mesh, t, 0, mesh.vertexCount)
  84. }
  85. export function transformRangeImmediate(mesh: Mesh, t: Mat4, offset: number, count: number) {
  86. transformPositionArray(t, mesh.vertexBuffer.ref.value, offset, count)
  87. // TODO normals transformation does not work for an unknown reason, ASR
  88. // if (mesh.normalBuffer.ref.value) {
  89. // const n = getNormalMatrix(Mat3.zero(), t)
  90. // transformDirectionArray(n, mesh.normalBuffer.ref.value, offset, count)
  91. // mesh.normalsComputed = true;
  92. // }
  93. mesh.normalsComputed = false;
  94. // mesh.boundingSphere = void 0;
  95. }
  96. export function computeBoundingSphere(mesh: Mesh): Task<Mesh> {
  97. return Task.create<Mesh>('Mesh (Compute Bounding Sphere)', async ctx => {
  98. if (mesh.boundingSphere) {
  99. return mesh;
  100. }
  101. await ctx.update('Computing bounding sphere...');
  102. const vertices = mesh.vertexBuffer.ref.value;
  103. let x = 0, y = 0, z = 0;
  104. for (let i = 0, _c = vertices.length; i < _c; i += 3) {
  105. x += vertices[i];
  106. y += vertices[i + 1];
  107. z += vertices[i + 2];
  108. }
  109. x /= mesh.vertexCount;
  110. y /= mesh.vertexCount;
  111. z /= mesh.vertexCount;
  112. let r = 0;
  113. for (let i = 0, _c = vertices.length; i < _c; i += 3) {
  114. const dx = x - vertices[i];
  115. const dy = y - vertices[i + 1];
  116. const dz = z - vertices[i + 2];
  117. r = Math.max(r, dx * dx + dy * dy + dz * dz);
  118. }
  119. mesh.boundingSphere = {
  120. center: Vec3.create(x, y, z),
  121. radius: Math.sqrt(r)
  122. }
  123. return mesh;
  124. });
  125. }
  126. }
  127. // function addVertex(src: Float32Array, i: number, dst: Float32Array, j: number) {
  128. // dst[3 * j] += src[3 * i];
  129. // dst[3 * j + 1] += src[3 * i + 1];
  130. // dst[3 * j + 2] += src[3 * i + 2];
  131. // }
  132. // function laplacianSmoothIter(surface: Surface, vertexCounts: Int32Array, vs: Float32Array, vertexWeight: number) {
  133. // const triCount = surface.triangleIndices.length,
  134. // src = surface.vertices;
  135. // const triangleIndices = surface.triangleIndices;
  136. // for (let i = 0; i < triCount; i += 3) {
  137. // const a = triangleIndices[i],
  138. // b = triangleIndices[i + 1],
  139. // c = triangleIndices[i + 2];
  140. // addVertex(src, b, vs, a);
  141. // addVertex(src, c, vs, a);
  142. // addVertex(src, a, vs, b);
  143. // addVertex(src, c, vs, b);
  144. // addVertex(src, a, vs, c);
  145. // addVertex(src, b, vs, c);
  146. // }
  147. // const vw = 2 * vertexWeight;
  148. // for (let i = 0, _b = surface.vertexCount; i < _b; i++) {
  149. // const n = vertexCounts[i] + vw;
  150. // vs[3 * i] = (vs[3 * i] + vw * src[3 * i]) / n;
  151. // vs[3 * i + 1] = (vs[3 * i + 1] + vw * src[3 * i + 1]) / n;
  152. // vs[3 * i + 2] = (vs[3 * i + 2] + vw * src[3 * i + 2]) / n;
  153. // }
  154. // }
  155. // async function laplacianSmoothComputation(ctx: Computation.Context, surface: Surface, iterCount: number, vertexWeight: number) {
  156. // await ctx.updateProgress('Smoothing surface...', true);
  157. // const vertexCounts = new Int32Array(surface.vertexCount),
  158. // triCount = surface.triangleIndices.length;
  159. // const tris = surface.triangleIndices;
  160. // for (let i = 0; i < triCount; i++) {
  161. // // in a triangle 2 edges touch each vertex, hence the constant.
  162. // vertexCounts[tris[i]] += 2;
  163. // }
  164. // let vs = new Float32Array(surface.vertices.length);
  165. // let started = Utils.PerformanceMonitor.currentTime();
  166. // await ctx.updateProgress('Smoothing surface...', true);
  167. // for (let i = 0; i < iterCount; i++) {
  168. // if (i > 0) {
  169. // for (let j = 0, _b = vs.length; j < _b; j++) vs[j] = 0;
  170. // }
  171. // surface.normals = void 0;
  172. // laplacianSmoothIter(surface, vertexCounts, vs, vertexWeight);
  173. // const t = surface.vertices;
  174. // surface.vertices = <any>vs;
  175. // vs = <any>t;
  176. // const time = Utils.PerformanceMonitor.currentTime();
  177. // if (time - started > Computation.UpdateProgressDelta) {
  178. // started = time;
  179. // await ctx.updateProgress('Smoothing surface...', true, i + 1, iterCount);
  180. // }
  181. // }
  182. // return surface;
  183. // }
  184. // /*
  185. // * Smooths the vertices by averaging the neighborhood.
  186. // *
  187. // * Resets normals. Might replace vertex array.
  188. // */
  189. // export function laplacianSmooth(surface: Surface, iterCount: number = 1, vertexWeight: number = 1): Computation<Surface> {
  190. // if (iterCount < 1) iterCount = 0;
  191. // if (iterCount === 0) return Computation.resolve(surface);
  192. // return computation(async ctx => await laplacianSmoothComputation(ctx, surface, iterCount, (1.1 * vertexWeight) / 1.1));
  193. // }