mesh.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. /**
  2. * Copyright (c) 2018-2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. * @author David Sehnal <david.sehnal@gmail.com>
  6. */
  7. import { ValueCell } from '../../../mol-util'
  8. import { Vec3, Mat4, Mat3 } from '../../../mol-math/linear-algebra'
  9. import { Sphere3D } from '../../../mol-math/geometry'
  10. import { transformPositionArray,/* , transformDirectionArray, getNormalMatrix */
  11. transformDirectionArray} from '../../util';
  12. import { GeometryUtils } 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, hashFnv32a } from '../../../mol-data/util';
  18. import { ParamDefinition as PD } from '../../../mol-util/param-definition';
  19. import { calculateInvariantBoundingSphere, calculateTransformBoundingSphere } from '../../../mol-gl/renderable/util';
  20. import { Theme } from '../../../mol-theme/theme';
  21. import { MeshValues } from '../../../mol-gl/renderable/mesh';
  22. import { Color } from '../../../mol-util/color';
  23. import { BaseGeometry } from '../base';
  24. import { createEmptyOverpaint } from '../overpaint-data';
  25. import { createEmptyTransparency } from '../transparency-data';
  26. export interface Mesh {
  27. readonly kind: 'mesh',
  28. /** Number of vertices in the mesh */
  29. vertexCount: number,
  30. /** Number of triangles in the mesh */
  31. triangleCount: number,
  32. /** Vertex buffer as array of xyz values wrapped in a value cell */
  33. readonly vertexBuffer: ValueCell<Float32Array>,
  34. /** Index buffer as array of vertex index triplets wrapped in a value cell */
  35. readonly indexBuffer: ValueCell<Uint32Array>,
  36. /** Normal buffer as array of xyz values for each vertex wrapped in a value cell */
  37. readonly normalBuffer: ValueCell<Float32Array>,
  38. /** Group buffer as array of group ids for each vertex wrapped in a value cell */
  39. readonly groupBuffer: ValueCell<Float32Array>,
  40. /** Bounding sphere of the mesh */
  41. readonly boundingSphere: Sphere3D
  42. }
  43. export namespace Mesh {
  44. export function create(vertices: Float32Array, indices: Uint32Array, normals: Float32Array, groups: Float32Array, vertexCount: number, triangleCount: number, mesh?: Mesh): Mesh {
  45. return mesh ?
  46. update(vertices, indices, normals, groups, vertexCount, triangleCount, mesh) :
  47. fromArrays(vertices, indices, normals, groups, vertexCount, triangleCount)
  48. }
  49. export function createEmpty(mesh?: Mesh): Mesh {
  50. const vb = mesh ? mesh.vertexBuffer.ref.value : new Float32Array(0)
  51. const ib = mesh ? mesh.indexBuffer.ref.value : new Uint32Array(0)
  52. const nb = mesh ? mesh.normalBuffer.ref.value : new Float32Array(0)
  53. const gb = mesh ? mesh.groupBuffer.ref.value : new Float32Array(0)
  54. return create(vb, ib, nb, gb, 0, 0, mesh)
  55. }
  56. function hashCode(mesh: Mesh) {
  57. return hashFnv32a([
  58. mesh.vertexCount, mesh.triangleCount,
  59. mesh.vertexBuffer.ref.version, mesh.indexBuffer.ref.version,
  60. mesh.normalBuffer.ref.version, mesh.groupBuffer.ref.version
  61. ])
  62. }
  63. function fromArrays(vertices: Float32Array, indices: Uint32Array, normals: Float32Array, groups: Float32Array, vertexCount: number, triangleCount: number): Mesh {
  64. const boundingSphere = Sphere3D()
  65. let currentHash = -1
  66. const mesh = {
  67. kind: 'mesh' as const,
  68. vertexCount,
  69. triangleCount,
  70. vertexBuffer: ValueCell.create(vertices),
  71. indexBuffer: ValueCell.create(indices),
  72. normalBuffer: ValueCell.create(normals),
  73. groupBuffer: ValueCell.create(groups),
  74. get boundingSphere() {
  75. const newHash = hashCode(mesh)
  76. if (newHash !== currentHash) {
  77. const b = calculateInvariantBoundingSphere(mesh.vertexBuffer.ref.value, mesh.vertexCount, 1)
  78. Sphere3D.copy(boundingSphere, b)
  79. currentHash = newHash
  80. }
  81. return boundingSphere
  82. },
  83. }
  84. return mesh
  85. }
  86. function update(vertices: Float32Array, indices: Uint32Array, normals: Float32Array, groups: Float32Array, vertexCount: number, triangleCount: number, mesh: Mesh) {
  87. mesh.vertexCount = vertexCount
  88. mesh.triangleCount = triangleCount
  89. ValueCell.update(mesh.vertexBuffer, vertices)
  90. ValueCell.update(mesh.indexBuffer, indices)
  91. ValueCell.update(mesh.normalBuffer, normals)
  92. ValueCell.update(mesh.groupBuffer, groups)
  93. return mesh
  94. }
  95. export function computeNormals(mesh: Mesh) {
  96. const normals = mesh.normalBuffer.ref.value.length >= mesh.vertexCount * 3
  97. ? mesh.normalBuffer.ref.value : new Float32Array(mesh.vertexBuffer.ref.value.length);
  98. const v = mesh.vertexBuffer.ref.value, triangles = mesh.indexBuffer.ref.value;
  99. if (normals === mesh.normalBuffer.ref.value) {
  100. for (let i = 0, ii = 3 * mesh.vertexCount; i < ii; i += 3) {
  101. normals[i] = 0; normals[i + 1] = 0; normals[i + 2] = 0;
  102. }
  103. }
  104. const x = Vec3.zero(), y = Vec3.zero(), z = Vec3.zero(), d1 = Vec3.zero(), d2 = Vec3.zero(), n = Vec3.zero();
  105. for (let i = 0, ii = 3 * mesh.triangleCount; i < ii; i += 3) {
  106. const a = 3 * triangles[i], b = 3 * triangles[i + 1], c = 3 * triangles[i + 2];
  107. Vec3.fromArray(x, v, a);
  108. Vec3.fromArray(y, v, b);
  109. Vec3.fromArray(z, v, c);
  110. Vec3.sub(d1, z, y);
  111. Vec3.sub(d2, x, y);
  112. Vec3.cross(n, d1, d2);
  113. normals[a] += n[0]; normals[a + 1] += n[1]; normals[a + 2] += n[2];
  114. normals[b] += n[0]; normals[b + 1] += n[1]; normals[b + 2] += n[2];
  115. normals[c] += n[0]; normals[c + 1] += n[1]; normals[c + 2] += n[2];
  116. }
  117. for (let i = 0, ii = 3 * mesh.vertexCount; i < ii; i += 3) {
  118. const nx = normals[i];
  119. const ny = normals[i + 1];
  120. const nz = normals[i + 2];
  121. const f = 1.0 / Math.sqrt(nx * nx + ny * ny + nz * nz);
  122. normals[i] *= f; normals[i + 1] *= f; normals[i + 2] *= f;
  123. }
  124. ValueCell.update(mesh.normalBuffer, normals);
  125. }
  126. export function checkForDuplicateVertices(mesh: Mesh, fractionDigits = 3) {
  127. const v = mesh.vertexBuffer.ref.value
  128. const map = new Map<string, number>()
  129. const hash = (v: Vec3, d: number) => `${v[0].toFixed(d)}|${v[1].toFixed(d)}|${v[2].toFixed(d)}`
  130. let duplicates = 0
  131. const a = Vec3.zero()
  132. for (let i = 0, il = mesh.vertexCount; i < il; ++i) {
  133. Vec3.fromArray(a, v, i * 3)
  134. const k = hash(a, fractionDigits)
  135. const count = map.get(k)
  136. if (count !== undefined) {
  137. duplicates += 1
  138. map.set(k, count + 1)
  139. } else {
  140. map.set(k, 1)
  141. }
  142. }
  143. return duplicates
  144. }
  145. const tmpMat3 = Mat3.zero()
  146. export function transform(mesh: Mesh, t: Mat4) {
  147. const v = mesh.vertexBuffer.ref.value
  148. transformPositionArray(t, v, 0, mesh.vertexCount)
  149. if (!Mat4.isTranslationAndUniformScaling(t)) {
  150. const n = Mat3.directionTransform(tmpMat3, t)
  151. transformDirectionArray(n, mesh.normalBuffer.ref.value, 0, mesh.vertexCount)
  152. }
  153. ValueCell.update(mesh.vertexBuffer, v);
  154. }
  155. /**
  156. * Ensure that each vertices of each triangle have the same group id.
  157. * Note that normals are copied over and can't be re-created from the new mesh.
  158. */
  159. export function uniformTriangleGroup(mesh: Mesh, splitTriangles = true) {
  160. const { indexBuffer, vertexBuffer, groupBuffer, normalBuffer, triangleCount, vertexCount } = mesh
  161. const ib = indexBuffer.ref.value
  162. const vb = vertexBuffer.ref.value
  163. const gb = groupBuffer.ref.value
  164. const nb = normalBuffer.ref.value
  165. // new
  166. const index = ChunkedArray.create(Uint32Array, 3, 1024, triangleCount)
  167. // re-use
  168. const vertex = ChunkedArray.create(Float32Array, 3, 1024, vb)
  169. vertex.currentIndex = vertexCount * 3
  170. vertex.elementCount = vertexCount
  171. const normal = ChunkedArray.create(Float32Array, 3, 1024, nb)
  172. normal.currentIndex = vertexCount * 3
  173. normal.elementCount = vertexCount
  174. const group = ChunkedArray.create(Float32Array, 1, 1024, gb)
  175. group.currentIndex = vertexCount
  176. group.elementCount = vertexCount
  177. const vi = Vec3.zero()
  178. const vj = Vec3.zero()
  179. const vk = Vec3.zero()
  180. const ni = Vec3.zero()
  181. const nj = Vec3.zero()
  182. const nk = Vec3.zero()
  183. function add(i: number) {
  184. Vec3.fromArray(vi, vb, i * 3)
  185. Vec3.fromArray(ni, nb, i * 3)
  186. ChunkedArray.add3(vertex, vi[0], vi[1], vi[2])
  187. ChunkedArray.add3(normal, ni[0], ni[1], ni[2])
  188. }
  189. function addMid(i: number, j: number) {
  190. Vec3.fromArray(vi, vb, i * 3)
  191. Vec3.fromArray(vj, vb, j * 3)
  192. Vec3.scale(vi, Vec3.add(vi, vi, vj), 0.5)
  193. Vec3.fromArray(ni, nb, i * 3)
  194. Vec3.fromArray(nj, nb, j * 3)
  195. Vec3.scale(ni, Vec3.add(ni, ni, nj), 0.5)
  196. ChunkedArray.add3(vertex, vi[0], vi[1], vi[2])
  197. ChunkedArray.add3(normal, ni[0], ni[1], ni[2])
  198. }
  199. function addCenter(i: number, j: number, k: number) {
  200. Vec3.fromArray(vi, vb, i * 3)
  201. Vec3.fromArray(vj, vb, j * 3)
  202. Vec3.fromArray(vk, vb, k * 3)
  203. Vec3.scale(vi, Vec3.add(vi, Vec3.add(vi, vi, vj), vk), 1/3)
  204. Vec3.fromArray(ni, nb, i * 3)
  205. Vec3.fromArray(nj, nb, j * 3)
  206. Vec3.fromArray(nk, nb, k * 3)
  207. Vec3.scale(ni, Vec3.add(ni, Vec3.add(ni, ni, nj), nk), 1/3)
  208. ChunkedArray.add3(vertex, vi[0], vi[1], vi[2])
  209. ChunkedArray.add3(normal, ni[0], ni[1], ni[2])
  210. }
  211. function split2(i0: number, i1: number, i2: number, g0: number, g1: number) {
  212. ++newTriangleCount
  213. add(i0); addMid(i0, i1); addMid(i0, i2);
  214. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 2)
  215. for (let j = 0; j < 3; ++j) ChunkedArray.add(group, g0)
  216. newVertexCount += 3
  217. newTriangleCount += 2
  218. add(i1); add(i2); addMid(i0, i1); addMid(i0, i2);
  219. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3)
  220. ChunkedArray.add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2)
  221. for (let j = 0; j < 4; ++j) ChunkedArray.add(group, g1)
  222. newVertexCount += 4
  223. }
  224. let newVertexCount = vertexCount
  225. let newTriangleCount = 0
  226. if (splitTriangles) {
  227. for (let i = 0, il = triangleCount; i < il; ++i) {
  228. const i0 = ib[i * 3], i1 = ib[i * 3 + 1], i2 = ib[i * 3 + 2]
  229. const g0 = gb[i0], g1 = gb[i1], g2 = gb[i2]
  230. if (g0 === g1 && g0 === g2) {
  231. ++newTriangleCount
  232. ChunkedArray.add3(index, i0, i1, i2)
  233. } else if (g0 === g1) {
  234. split2(i2, i0, i1, g2, g0)
  235. } else if (g0 === g2) {
  236. split2(i1, i2, i0, g1, g2)
  237. } else if (g1 === g2) {
  238. split2(i0, i1, i2, g0, g1)
  239. } else {
  240. newTriangleCount += 2
  241. add(i0); addMid(i0, i1); addMid(i0, i2); addCenter(i0, i1, i2);
  242. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3)
  243. ChunkedArray.add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2)
  244. for (let j = 0; j < 4; ++j) ChunkedArray.add(group, g0)
  245. newVertexCount += 4
  246. newTriangleCount += 2
  247. add(i1); addMid(i1, i2); addMid(i1, i0); addCenter(i0, i1, i2);
  248. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 3)
  249. ChunkedArray.add3(index, newVertexCount, newVertexCount + 3, newVertexCount + 2)
  250. for (let j = 0; j < 4; ++j) ChunkedArray.add(group, g1)
  251. newVertexCount += 4
  252. newTriangleCount += 2
  253. add(i2); addMid(i2, i1); addMid(i2, i0); addCenter(i0, i1, i2);
  254. ChunkedArray.add3(index, newVertexCount + 3, newVertexCount + 1, newVertexCount)
  255. ChunkedArray.add3(index, newVertexCount + 2, newVertexCount + 3, newVertexCount)
  256. for (let j = 0; j < 4; ++j) ChunkedArray.add(group, g2)
  257. newVertexCount += 4
  258. }
  259. }
  260. } else {
  261. for (let i = 0, il = triangleCount; i < il; ++i) {
  262. const i0 = ib[i * 3], i1 = ib[i * 3 + 1], i2 = ib[i * 3 + 2]
  263. const g0 = gb[i0], g1 = gb[i1], g2 = gb[i2]
  264. if (g0 !== g1 || g0 !== g2) {
  265. ++newTriangleCount
  266. add(i0); add(i1); add(i2)
  267. ChunkedArray.add3(index, newVertexCount, newVertexCount + 1, newVertexCount + 2)
  268. const g = g1 === g2 ? g1 : g0
  269. for (let j = 0; j < 3; ++j) ChunkedArray.add(group, g)
  270. newVertexCount += 3
  271. } else {
  272. ++newTriangleCount
  273. ChunkedArray.add3(index, i0, i1, i2)
  274. }
  275. }
  276. }
  277. const newIb = ChunkedArray.compact(index)
  278. const newVb = ChunkedArray.compact(vertex)
  279. const newNb = ChunkedArray.compact(normal)
  280. const newGb = ChunkedArray.compact(group)
  281. mesh.vertexCount = newVertexCount
  282. mesh.triangleCount = newTriangleCount
  283. ValueCell.update(vertexBuffer, newVb) as ValueCell<Float32Array>
  284. ValueCell.update(groupBuffer, newGb) as ValueCell<Float32Array>
  285. ValueCell.update(indexBuffer, newIb) as ValueCell<Uint32Array>
  286. ValueCell.update(normalBuffer, newNb) as ValueCell<Float32Array>
  287. return mesh
  288. }
  289. //
  290. export const Params = {
  291. ...BaseGeometry.Params,
  292. doubleSided: PD.Boolean(false),
  293. flipSided: PD.Boolean(false),
  294. flatShaded: PD.Boolean(false),
  295. ignoreLight: PD.Boolean(false),
  296. }
  297. export type Params = typeof Params
  298. export const Utils: GeometryUtils<Mesh, Params> = {
  299. Params,
  300. createEmpty,
  301. createValues,
  302. createValuesSimple,
  303. updateValues,
  304. updateBoundingSphere,
  305. createRenderableState: BaseGeometry.createRenderableState,
  306. updateRenderableState: BaseGeometry.updateRenderableState
  307. }
  308. function createValues(mesh: Mesh, transform: TransformData, locationIt: LocationIterator, theme: Theme, props: PD.Values<Params>): MeshValues {
  309. const { instanceCount, groupCount } = locationIt
  310. if (instanceCount !== transform.instanceCount.ref.value) {
  311. throw new Error('instanceCount values in TransformData and LocationIterator differ')
  312. }
  313. const color = createColors(locationIt, theme.color)
  314. const marker = createMarkers(instanceCount * groupCount)
  315. const overpaint = createEmptyOverpaint()
  316. const transparency = createEmptyTransparency()
  317. const counts = { drawCount: mesh.triangleCount * 3, groupCount, instanceCount }
  318. const invariantBoundingSphere = Sphere3D.clone(mesh.boundingSphere)
  319. const boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, transform.aTransform.ref.value, instanceCount)
  320. return {
  321. aPosition: mesh.vertexBuffer,
  322. aNormal: mesh.normalBuffer,
  323. aGroup: mesh.groupBuffer,
  324. elements: mesh.indexBuffer,
  325. boundingSphere: ValueCell.create(boundingSphere),
  326. invariantBoundingSphere: ValueCell.create(invariantBoundingSphere),
  327. ...color,
  328. ...marker,
  329. ...overpaint,
  330. ...transparency,
  331. ...transform,
  332. ...BaseGeometry.createValues(props, counts),
  333. dDoubleSided: ValueCell.create(props.doubleSided),
  334. dFlatShaded: ValueCell.create(props.flatShaded),
  335. dFlipSided: ValueCell.create(props.flipSided),
  336. dIgnoreLight: ValueCell.create(props.ignoreLight),
  337. }
  338. }
  339. function createValuesSimple(mesh: Mesh, props: Partial<PD.Values<Params>>, colorValue: Color, sizeValue: number, transform?: TransformData) {
  340. const s = BaseGeometry.createSimple(colorValue, sizeValue, transform)
  341. const p = { ...PD.getDefaultValues(Params), ...props }
  342. return createValues(mesh, s.transform, s.locationIterator, s.theme, p)
  343. }
  344. function updateValues(values: MeshValues, props: PD.Values<Params>) {
  345. BaseGeometry.updateValues(values, props)
  346. ValueCell.updateIfChanged(values.dDoubleSided, props.doubleSided)
  347. ValueCell.updateIfChanged(values.dFlatShaded, props.flatShaded)
  348. ValueCell.updateIfChanged(values.dFlipSided, props.flipSided)
  349. ValueCell.updateIfChanged(values.dIgnoreLight, props.ignoreLight)
  350. }
  351. function updateBoundingSphere(values: MeshValues, mesh: Mesh) {
  352. const invariantBoundingSphere = Sphere3D.clone(mesh.boundingSphere)
  353. const boundingSphere = calculateTransformBoundingSphere(invariantBoundingSphere, values.aTransform.ref.value, values.instanceCount.ref.value)
  354. if (!Sphere3D.equals(boundingSphere, values.boundingSphere.ref.value)) {
  355. ValueCell.update(values.boundingSphere, boundingSphere)
  356. }
  357. if (!Sphere3D.equals(invariantBoundingSphere, values.invariantBoundingSphere.ref.value)) {
  358. ValueCell.update(values.invariantBoundingSphere, invariantBoundingSphere)
  359. }
  360. }
  361. }