mesh.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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, RuntimeContext } 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. import { MeshValues } from 'mol-gl/renderable';
  12. import { Geometry } from '../geometry';
  13. import { createMarkers } from '../marker-data';
  14. import { TransformData } from '../transform-data';
  15. import { LocationIterator } from '../../util/location-iterator';
  16. import { createColors } from '../color-data';
  17. import { ChunkedArray } from 'mol-data/util';
  18. export interface Mesh {
  19. readonly kind: 'mesh',
  20. /** Number of vertices in the mesh */
  21. vertexCount: number,
  22. /** Number of triangles in the mesh */
  23. triangleCount: number,
  24. /** Vertex buffer as array of xyz values wrapped in a value cell */
  25. readonly vertexBuffer: ValueCell<Float32Array>,
  26. /** Index buffer as array of vertex index triplets wrapped in a value cell */
  27. readonly indexBuffer: ValueCell<Uint32Array>,
  28. /** Normal buffer as array of xyz values for each vertex wrapped in a value cell */
  29. readonly normalBuffer: ValueCell<Float32Array>,
  30. /** Group buffer as array of group ids for each vertex wrapped in a value cell */
  31. readonly groupBuffer: ValueCell<Float32Array>,
  32. /** Flag indicating if normals are computed for the current set of vertices */
  33. normalsComputed: boolean,
  34. /** Bounding sphere of the mesh */
  35. boundingSphere?: Sphere3D
  36. }
  37. export namespace Mesh {
  38. export function createEmpty(mesh?: Mesh): Mesh {
  39. const vb = mesh ? mesh.vertexBuffer.ref.value : new Float32Array(0)
  40. const ib = mesh ? mesh.indexBuffer.ref.value : new Uint32Array(0)
  41. const nb = mesh ? mesh.normalBuffer.ref.value : new Float32Array(0)
  42. const gb = mesh ? mesh.groupBuffer.ref.value : new Float32Array(0)
  43. return {
  44. kind: 'mesh',
  45. vertexCount: 0,
  46. triangleCount: 0,
  47. vertexBuffer: mesh ? ValueCell.update(mesh.vertexBuffer, vb) : ValueCell.create(vb),
  48. indexBuffer: mesh ? ValueCell.update(mesh.indexBuffer, ib) : ValueCell.create(ib),
  49. normalBuffer: mesh ? ValueCell.update(mesh.normalBuffer, nb) : ValueCell.create(nb),
  50. groupBuffer: mesh ? ValueCell.update(mesh.groupBuffer, gb) : ValueCell.create(gb),
  51. normalsComputed: true,
  52. }
  53. }
  54. export function computeNormalsImmediate(mesh: Mesh) {
  55. if (mesh.normalsComputed) return;
  56. const normals = mesh.normalBuffer.ref.value.length >= mesh.vertexCount * 3
  57. ? mesh.normalBuffer.ref.value : new Float32Array(mesh.vertexBuffer.ref.value.length);
  58. const v = mesh.vertexBuffer.ref.value, triangles = mesh.indexBuffer.ref.value;
  59. if (normals === mesh.normalBuffer.ref.value) {
  60. for (let i = 0, ii = 3 * mesh.vertexCount; i < ii; i += 3) {
  61. normals[i] = 0; normals[i + 1] = 0; normals[i + 2] = 0;
  62. }
  63. }
  64. const x = Vec3.zero(), y = Vec3.zero(), z = Vec3.zero(), d1 = Vec3.zero(), d2 = Vec3.zero(), n = Vec3.zero();
  65. for (let i = 0, ii = 3 * mesh.triangleCount; i < ii; i += 3) {
  66. const a = 3 * triangles[i], b = 3 * triangles[i + 1], c = 3 * triangles[i + 2];
  67. Vec3.fromArray(x, v, a);
  68. Vec3.fromArray(y, v, b);
  69. Vec3.fromArray(z, v, c);
  70. Vec3.sub(d1, z, y);
  71. Vec3.sub(d2, x, y);
  72. Vec3.cross(n, d1, d2);
  73. normals[a] += n[0]; normals[a + 1] += n[1]; normals[a + 2] += n[2];
  74. normals[b] += n[0]; normals[b + 1] += n[1]; normals[b + 2] += n[2];
  75. normals[c] += n[0]; normals[c + 1] += n[1]; normals[c + 2] += n[2];
  76. }
  77. for (let i = 0, ii = 3 * mesh.vertexCount; i < ii; i += 3) {
  78. const nx = normals[i];
  79. const ny = normals[i + 1];
  80. const nz = normals[i + 2];
  81. const f = 1.0 / Math.sqrt(nx * nx + ny * ny + nz * nz);
  82. normals[i] *= f; normals[i + 1] *= f; normals[i + 2] *= f;
  83. // console.log([normals[i], normals[i + 1], normals[i + 2]], [v[i], v[i + 1], v[i + 2]])
  84. }
  85. ValueCell.update(mesh.normalBuffer, normals);
  86. mesh.normalsComputed = true;
  87. }
  88. export function computeNormals(surface: Mesh): Task<Mesh> {
  89. return Task.create<Mesh>('Surface (Compute Normals)', async ctx => {
  90. if (surface.normalsComputed) return surface;
  91. await ctx.update('Computing normals...');
  92. computeNormalsImmediate(surface);
  93. return surface;
  94. });
  95. }
  96. export function transformImmediate(mesh: Mesh, t: Mat4) {
  97. transformRangeImmediate(mesh, t, 0, mesh.vertexCount)
  98. }
  99. export function transformRangeImmediate(mesh: Mesh, t: Mat4, offset: number, count: number) {
  100. const v = mesh.vertexBuffer.ref.value
  101. transformPositionArray(t, v, offset, count)
  102. // TODO normals transformation does not work for an unknown reason, ASR
  103. // if (mesh.normalBuffer.ref.value) {
  104. // const n = getNormalMatrix(Mat3.zero(), t)
  105. // transformDirectionArray(n, mesh.normalBuffer.ref.value, offset, count)
  106. // mesh.normalsComputed = true;
  107. // }
  108. ValueCell.update(mesh.vertexBuffer, v);
  109. mesh.normalsComputed = false;
  110. }
  111. export function computeBoundingSphere(mesh: Mesh): Task<Mesh> {
  112. return Task.create<Mesh>('Mesh (Compute Bounding Sphere)', async ctx => {
  113. if (mesh.boundingSphere) {
  114. return mesh;
  115. }
  116. await ctx.update('Computing bounding sphere...');
  117. const vertices = mesh.vertexBuffer.ref.value;
  118. let x = 0, y = 0, z = 0;
  119. for (let i = 0, _c = vertices.length; i < _c; i += 3) {
  120. x += vertices[i];
  121. y += vertices[i + 1];
  122. z += vertices[i + 2];
  123. }
  124. x /= mesh.vertexCount;
  125. y /= mesh.vertexCount;
  126. z /= mesh.vertexCount;
  127. let r = 0;
  128. for (let i = 0, _c = vertices.length; i < _c; i += 3) {
  129. const dx = x - vertices[i];
  130. const dy = y - vertices[i + 1];
  131. const dz = z - vertices[i + 2];
  132. r = Math.max(r, dx * dx + dy * dy + dz * dz);
  133. }
  134. mesh.boundingSphere = {
  135. center: Vec3.create(x, y, z),
  136. radius: Math.sqrt(r)
  137. }
  138. return mesh;
  139. });
  140. }
  141. /**
  142. * Ensure that each vertices of each triangle have the same group id.
  143. * Note that normals are copied over and can't be re-created from the new mesh.
  144. */
  145. export function uniformTriangleGroup(mesh: Mesh) {
  146. const { indexBuffer, vertexBuffer, groupBuffer, normalBuffer, triangleCount, vertexCount } = mesh
  147. const ib = indexBuffer.ref.value
  148. const vb = vertexBuffer.ref.value
  149. const gb = groupBuffer.ref.value
  150. const nb = normalBuffer.ref.value
  151. // new
  152. const index = ChunkedArray.create(Uint32Array, 3, 1024, triangleCount)
  153. // re-use
  154. const vertex = ChunkedArray.create(Float32Array, 3, 1024, vb)
  155. vertex.currentIndex = vertexCount * 3
  156. vertex.elementCount = vertexCount
  157. const normal = ChunkedArray.create(Float32Array, 3, 1024, nb)
  158. normal.currentIndex = vertexCount * 3
  159. normal.elementCount = vertexCount
  160. const group = ChunkedArray.create(Float32Array, 1, 1024, gb)
  161. group.currentIndex = vertexCount
  162. group.elementCount = vertexCount
  163. const v = Vec3.zero()
  164. const n = Vec3.zero()
  165. function add(i: number) {
  166. Vec3.fromArray(v, vb, i * 3)
  167. Vec3.fromArray(n, nb, i * 3)
  168. ChunkedArray.add3(vertex, v[0], v[1], v[2])
  169. ChunkedArray.add3(normal, n[0], n[1], n[2])
  170. }
  171. let newVertexCount = vertexCount
  172. for (let i = 0, il = triangleCount; i < il; ++i) {
  173. const v0 = ib[i * 3], v1 = ib[i * 3 + 1], v2 = ib[i * 3 + 2]
  174. const g0 = gb[v0], g1 = gb[v1], g2 = gb[v2]
  175. if (g0 !== g1 || g0 !== g2) {
  176. add(v0); add(v1); add(v2)
  177. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 2)
  178. const g = g1 === g2 ? g1 : g0
  179. for (let j = 0; j < 3; ++j) ChunkedArray.add(group, g)
  180. newVertexCount += 3
  181. } else {
  182. ChunkedArray.add3(index, v0, v1, v2)
  183. }
  184. }
  185. const newIb = ChunkedArray.compact(index)
  186. const newVb = ChunkedArray.compact(vertex)
  187. const newNb = ChunkedArray.compact(normal)
  188. const newGb = ChunkedArray.compact(group)
  189. mesh.vertexCount = newVertexCount
  190. ValueCell.update(vertexBuffer, newVb) as ValueCell<Float32Array>
  191. ValueCell.update(groupBuffer, newGb) as ValueCell<Float32Array>
  192. ValueCell.update(indexBuffer, newIb) as ValueCell<Uint32Array>
  193. ValueCell.update(normalBuffer, newNb) as ValueCell<Float32Array>
  194. return mesh
  195. }
  196. //
  197. export const DefaultProps = {
  198. ...Geometry.DefaultProps,
  199. doubleSided: false,
  200. flipSided: false,
  201. flatShaded: false,
  202. }
  203. export type Props = typeof DefaultProps
  204. export async function createValues(ctx: RuntimeContext, mesh: Mesh, transform: TransformData, locationIt: LocationIterator, props: Props): Promise<MeshValues> {
  205. const { instanceCount, groupCount } = locationIt
  206. const color = await createColors(ctx, locationIt, props.colorTheme)
  207. const marker = createMarkers(instanceCount * groupCount)
  208. const counts = { drawCount: mesh.triangleCount * 3, groupCount, instanceCount }
  209. return {
  210. aPosition: mesh.vertexBuffer,
  211. aNormal: mesh.normalBuffer,
  212. aGroup: mesh.groupBuffer,
  213. elements: mesh.indexBuffer,
  214. ...color,
  215. ...marker,
  216. ...transform,
  217. ...Geometry.createValues(props, counts),
  218. dDoubleSided: ValueCell.create(props.doubleSided),
  219. dFlatShaded: ValueCell.create(props.flatShaded),
  220. dFlipSided: ValueCell.create(props.flipSided),
  221. }
  222. }
  223. export function updateValues(values: MeshValues, props: Props) {
  224. Geometry.updateValues(values, props)
  225. ValueCell.updateIfChanged(values.dDoubleSided, props.doubleSided)
  226. ValueCell.updateIfChanged(values.dFlatShaded, props.flatShaded)
  227. ValueCell.updateIfChanged(values.dFlipSided, props.flipSided)
  228. }
  229. }
  230. // function addVertex(src: Float32Array, i: number, dst: Float32Array, j: number) {
  231. // dst[3 * j] += src[3 * i];
  232. // dst[3 * j + 1] += src[3 * i + 1];
  233. // dst[3 * j + 2] += src[3 * i + 2];
  234. // }
  235. // function laplacianSmoothIter(surface: Surface, vertexCounts: Int32Array, vs: Float32Array, vertexWeight: number) {
  236. // const triCount = surface.triangleIndices.length,
  237. // src = surface.vertices;
  238. // const triangleIndices = surface.triangleIndices;
  239. // for (let i = 0; i < triCount; i += 3) {
  240. // const a = triangleIndices[i],
  241. // b = triangleIndices[i + 1],
  242. // c = triangleIndices[i + 2];
  243. // addVertex(src, b, vs, a);
  244. // addVertex(src, c, vs, a);
  245. // addVertex(src, a, vs, b);
  246. // addVertex(src, c, vs, b);
  247. // addVertex(src, a, vs, c);
  248. // addVertex(src, b, vs, c);
  249. // }
  250. // const vw = 2 * vertexWeight;
  251. // for (let i = 0, _b = surface.vertexCount; i < _b; i++) {
  252. // const n = vertexCounts[i] + vw;
  253. // vs[3 * i] = (vs[3 * i] + vw * src[3 * i]) / n;
  254. // vs[3 * i + 1] = (vs[3 * i + 1] + vw * src[3 * i + 1]) / n;
  255. // vs[3 * i + 2] = (vs[3 * i + 2] + vw * src[3 * i + 2]) / n;
  256. // }
  257. // }
  258. // async function laplacianSmoothComputation(ctx: Computation.Context, surface: Surface, iterCount: number, vertexWeight: number) {
  259. // await ctx.updateProgress('Smoothing surface...', true);
  260. // const vertexCounts = new Int32Array(surface.vertexCount),
  261. // triCount = surface.triangleIndices.length;
  262. // const tris = surface.triangleIndices;
  263. // for (let i = 0; i < triCount; i++) {
  264. // // in a triangle 2 edges touch each vertex, hence the constant.
  265. // vertexCounts[tris[i]] += 2;
  266. // }
  267. // let vs = new Float32Array(surface.vertices.length);
  268. // let started = Utils.PerformanceMonitor.currentTime();
  269. // await ctx.updateProgress('Smoothing surface...', true);
  270. // for (let i = 0; i < iterCount; i++) {
  271. // if (i > 0) {
  272. // for (let j = 0, _b = vs.length; j < _b; j++) vs[j] = 0;
  273. // }
  274. // surface.normals = void 0;
  275. // laplacianSmoothIter(surface, vertexCounts, vs, vertexWeight);
  276. // const t = surface.vertices;
  277. // surface.vertices = <any>vs;
  278. // vs = <any>t;
  279. // const time = Utils.PerformanceMonitor.currentTime();
  280. // if (time - started > Computation.UpdateProgressDelta) {
  281. // started = time;
  282. // await ctx.updateProgress('Smoothing surface...', true, i + 1, iterCount);
  283. // }
  284. // }
  285. // return surface;
  286. // }
  287. // /*
  288. // * Smooths the vertices by averaging the neighborhood.
  289. // *
  290. // * Resets normals. Might replace vertex array.
  291. // */
  292. // export function laplacianSmooth(surface: Surface, iterCount: number = 1, vertexWeight: number = 1): Computation<Surface> {
  293. // if (iterCount < 1) iterCount = 0;
  294. // if (iterCount === 0) return Computation.resolve(surface);
  295. // return computation(async ctx => await laplacianSmoothComputation(ctx, surface, iterCount, (1.1 * vertexWeight) / 1.1));
  296. // }