gaussian-surface-mesh.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  1. /**
  2. * Copyright (c) 2018-2021 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  5. */
  6. import { ParamDefinition as PD } from '../../../mol-util/param-definition';
  7. import { UnitsMeshParams, UnitsTextureMeshParams, UnitsVisual, UnitsMeshVisual, UnitsTextureMeshVisual, StructureGroup } from '../units-visual';
  8. import { GaussianDensityParams, computeUnitGaussianDensity, computeUnitGaussianDensityTexture2d, GaussianDensityProps, computeStructureGaussianDensity, computeStructureGaussianDensityTexture2d } from './util/gaussian';
  9. import { VisualContext } from '../../visual';
  10. import { Unit, Structure } from '../../../mol-model/structure';
  11. import { Theme } from '../../../mol-theme/theme';
  12. import { Mesh } from '../../../mol-geo/geometry/mesh/mesh';
  13. import { computeMarchingCubesMesh } from '../../../mol-geo/util/marching-cubes/algorithm';
  14. import { ElementIterator, getElementLoci, eachElement, getSerialElementLoci, eachSerialElement } from './util/element';
  15. import { VisualUpdateState } from '../../util';
  16. import { TextureMesh } from '../../../mol-geo/geometry/texture-mesh/texture-mesh';
  17. import { extractIsosurface } from '../../../mol-gl/compute/marching-cubes/isosurface';
  18. import { Sphere3D } from '../../../mol-math/geometry';
  19. import { ComplexVisual, ComplexMeshParams, ComplexMeshVisual, ComplexTextureMeshVisual, ComplexTextureMeshParams } from '../complex-visual';
  20. import { getUnitExtraRadius, getStructureExtraRadius, getVolumeSliceInfo } from './util/common';
  21. import { WebGLContext } from '../../../mol-gl/webgl/context';
  22. import { MeshValues } from '../../../mol-gl/renderable/mesh';
  23. import { TextureMeshValues } from '../../../mol-gl/renderable/texture-mesh';
  24. import { Texture } from '../../../mol-gl/webgl/texture';
  25. import { applyMeshColorSmoothing, applyTextureMeshColorSmoothing, ColorSmoothingParams, getColorSmoothingProps } from './util/color';
  26. const SharedParams = {
  27. ...GaussianDensityParams,
  28. ...ColorSmoothingParams,
  29. ignoreHydrogens: PD.Boolean(false),
  30. tryUseGpu: PD.Boolean(true),
  31. };
  32. type SharedParams = typeof SharedParams
  33. export const GaussianSurfaceMeshParams = {
  34. ...UnitsMeshParams,
  35. ...UnitsTextureMeshParams,
  36. ...SharedParams,
  37. };
  38. export type GaussianSurfaceMeshParams = typeof GaussianSurfaceMeshParams
  39. export const StructureGaussianSurfaceMeshParams = {
  40. ...ComplexMeshParams,
  41. ...ComplexTextureMeshParams,
  42. ...SharedParams,
  43. };
  44. export type StructureGaussianSurfaceMeshParams = typeof StructureGaussianSurfaceMeshParams
  45. function gpuSupport(webgl: WebGLContext) {
  46. return webgl.extensions.colorBufferFloat && webgl.extensions.textureFloat && webgl.extensions.blendMinMax && webgl.extensions.drawBuffers;
  47. }
  48. function suitableForGpu(structure: Structure, props: PD.Values<SharedParams>, webgl: WebGLContext) {
  49. // lower resolutions are about as fast on CPU vs integrated GPU,
  50. // very low resolutions have artifacts when calculated on GPU
  51. if (props.resolution > 1) return false;
  52. // the GPU is much more memory contraint, especially true for integrated GPUs,
  53. // being conservative here still allows for small and medium sized assemblies
  54. const d = webgl.maxTextureSize / 3;
  55. const { areaCells, maxAreaCells } = getVolumeSliceInfo(structure.boundary.box, props.resolution, d * d);
  56. return areaCells < maxAreaCells;
  57. }
  58. export function GaussianSurfaceVisual(materialId: number, structure: Structure, props: PD.Values<GaussianSurfaceMeshParams>, webgl?: WebGLContext) {
  59. if (props.tryUseGpu && webgl && gpuSupport(webgl) && suitableForGpu(structure, props, webgl)) {
  60. return GaussianSurfaceTextureMeshVisual(materialId);
  61. }
  62. return GaussianSurfaceMeshVisual(materialId);
  63. }
  64. export function StructureGaussianSurfaceVisual(materialId: number, structure: Structure, props: PD.Values<StructureGaussianSurfaceMeshParams>, webgl?: WebGLContext) {
  65. if (props.tryUseGpu && webgl && gpuSupport(webgl) && suitableForGpu(structure, props, webgl)) {
  66. return StructureGaussianSurfaceTextureMeshVisual(materialId);
  67. }
  68. return StructureGaussianSurfaceMeshVisual(materialId);
  69. }
  70. type GaussianSurfaceMeta = {
  71. resolution?: number
  72. colorTexture?: Texture
  73. }
  74. //
  75. async function createGaussianSurfaceMesh(ctx: VisualContext, unit: Unit, structure: Structure, theme: Theme, props: GaussianDensityProps, mesh?: Mesh): Promise<Mesh> {
  76. const { smoothness } = props;
  77. const { transform, field, idField, radiusFactor, resolution } = await computeUnitGaussianDensity(structure, unit, props).runInContext(ctx.runtime);
  78. const params = {
  79. isoLevel: Math.exp(-smoothness) / radiusFactor,
  80. scalarField: field,
  81. idField
  82. };
  83. const surface = await computeMarchingCubesMesh(params, mesh).runAsChild(ctx.runtime);
  84. (surface.meta.resolution as GaussianSurfaceMeta['resolution']) = resolution;
  85. Mesh.transform(surface, transform);
  86. if (ctx.webgl && !ctx.webgl.isWebGL2) Mesh.uniformTriangleGroup(surface);
  87. const sphere = Sphere3D.expand(Sphere3D(), unit.boundary.sphere, props.radiusOffset + getUnitExtraRadius(unit));
  88. surface.setBoundingSphere(sphere);
  89. return surface;
  90. }
  91. export function GaussianSurfaceMeshVisual(materialId: number): UnitsVisual<GaussianSurfaceMeshParams> {
  92. return UnitsMeshVisual<GaussianSurfaceMeshParams>({
  93. defaultProps: PD.getDefaultValues(GaussianSurfaceMeshParams),
  94. createGeometry: createGaussianSurfaceMesh,
  95. createLocationIterator: ElementIterator.fromGroup,
  96. getLoci: getElementLoci,
  97. eachLocation: eachElement,
  98. setUpdateState: (state: VisualUpdateState, newProps: PD.Values<GaussianSurfaceMeshParams>, currentProps: PD.Values<GaussianSurfaceMeshParams>) => {
  99. if (newProps.resolution !== currentProps.resolution) state.createGeometry = true;
  100. if (newProps.radiusOffset !== currentProps.radiusOffset) state.createGeometry = true;
  101. if (newProps.smoothness !== currentProps.smoothness) state.createGeometry = true;
  102. if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens) state.createGeometry = true;
  103. if (newProps.traceOnly !== currentProps.traceOnly) state.createGeometry = true;
  104. if (newProps.includeParent !== currentProps.includeParent) state.createGeometry = true;
  105. if (newProps.smoothColors.name !== currentProps.smoothColors.name) {
  106. state.updateColor = true;
  107. } else if (newProps.smoothColors.name === 'on' && currentProps.smoothColors.name === 'on') {
  108. if (newProps.smoothColors.params.resolutionFactor !== currentProps.smoothColors.params.resolutionFactor) state.updateColor = true;
  109. if (newProps.smoothColors.params.sampleStride !== currentProps.smoothColors.params.sampleStride) state.updateColor = true;
  110. }
  111. },
  112. mustRecreate: (structureGroup: StructureGroup, props: PD.Values<GaussianSurfaceMeshParams>, webgl?: WebGLContext) => {
  113. return props.tryUseGpu && !!webgl && suitableForGpu(structureGroup.structure, props, webgl);
  114. },
  115. processValues: (values: MeshValues, geometry: Mesh, props: PD.Values<GaussianSurfaceMeshParams>, theme: Theme, webgl?: WebGLContext) => {
  116. const { resolution, colorTexture } = geometry.meta as GaussianSurfaceMeta;
  117. const csp = getColorSmoothingProps(props, theme, resolution, webgl);
  118. if (csp) {
  119. applyMeshColorSmoothing(values, csp.resolution, csp.stride, csp.webgl, colorTexture);
  120. (geometry.meta.colorTexture as GaussianSurfaceMeta['colorTexture']) = values.tColorGrid.ref.value;
  121. }
  122. },
  123. dispose: (geometry: Mesh) => {
  124. (geometry.meta as GaussianSurfaceMeta).colorTexture?.destroy();
  125. }
  126. }, materialId);
  127. }
  128. //
  129. async function createStructureGaussianSurfaceMesh(ctx: VisualContext, structure: Structure, theme: Theme, props: GaussianDensityProps, mesh?: Mesh): Promise<Mesh> {
  130. const { smoothness } = props;
  131. const { transform, field, idField, radiusFactor, resolution } = await computeStructureGaussianDensity(structure, props).runInContext(ctx.runtime);
  132. const params = {
  133. isoLevel: Math.exp(-smoothness) / radiusFactor,
  134. scalarField: field,
  135. idField
  136. };
  137. const surface = await computeMarchingCubesMesh(params, mesh).runAsChild(ctx.runtime);
  138. (surface.meta.resolution as GaussianSurfaceMeta['resolution']) = resolution;
  139. Mesh.transform(surface, transform);
  140. if (ctx.webgl && !ctx.webgl.isWebGL2) Mesh.uniformTriangleGroup(surface);
  141. const sphere = Sphere3D.expand(Sphere3D(), structure.boundary.sphere, props.radiusOffset + getStructureExtraRadius(structure));
  142. surface.setBoundingSphere(sphere);
  143. return surface;
  144. }
  145. export function StructureGaussianSurfaceMeshVisual(materialId: number): ComplexVisual<StructureGaussianSurfaceMeshParams> {
  146. return ComplexMeshVisual<StructureGaussianSurfaceMeshParams>({
  147. defaultProps: PD.getDefaultValues(StructureGaussianSurfaceMeshParams),
  148. createGeometry: createStructureGaussianSurfaceMesh,
  149. createLocationIterator: ElementIterator.fromStructure,
  150. getLoci: getSerialElementLoci,
  151. eachLocation: eachSerialElement,
  152. setUpdateState: (state: VisualUpdateState, newProps: PD.Values<GaussianSurfaceMeshParams>, currentProps: PD.Values<GaussianSurfaceMeshParams>) => {
  153. if (newProps.resolution !== currentProps.resolution) state.createGeometry = true;
  154. if (newProps.radiusOffset !== currentProps.radiusOffset) state.createGeometry = true;
  155. if (newProps.smoothness !== currentProps.smoothness) state.createGeometry = true;
  156. if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens) state.createGeometry = true;
  157. if (newProps.traceOnly !== currentProps.traceOnly) state.createGeometry = true;
  158. if (newProps.smoothColors.name !== currentProps.smoothColors.name) {
  159. state.updateColor = true;
  160. } else if (newProps.smoothColors.name === 'on' && currentProps.smoothColors.name === 'on') {
  161. if (newProps.smoothColors.params.resolutionFactor !== currentProps.smoothColors.params.resolutionFactor) state.updateColor = true;
  162. if (newProps.smoothColors.params.sampleStride !== currentProps.smoothColors.params.sampleStride) state.updateColor = true;
  163. }
  164. },
  165. mustRecreate: (structure: Structure, props: PD.Values<StructureGaussianSurfaceMeshParams>, webgl?: WebGLContext) => {
  166. return props.tryUseGpu && !!webgl && suitableForGpu(structure, props, webgl);
  167. },
  168. processValues: (values: MeshValues, geometry: Mesh, props: PD.Values<GaussianSurfaceMeshParams>, theme: Theme, webgl?: WebGLContext) => {
  169. const { resolution, colorTexture } = geometry.meta as GaussianSurfaceMeta;
  170. const csp = getColorSmoothingProps(props, theme, resolution, webgl);
  171. if (csp) {
  172. applyMeshColorSmoothing(values, csp.resolution, csp.stride, csp.webgl, colorTexture);
  173. (geometry.meta.colorTexture as GaussianSurfaceMeta['colorTexture']) = values.tColorGrid.ref.value;
  174. }
  175. },
  176. dispose: (geometry: Mesh) => {
  177. (geometry.meta as GaussianSurfaceMeta).colorTexture?.destroy();
  178. }
  179. }, materialId);
  180. }
  181. //
  182. const GaussianSurfaceName = 'gaussian-surface';
  183. async function createGaussianSurfaceTextureMesh(ctx: VisualContext, unit: Unit, structure: Structure, theme: Theme, props: GaussianDensityProps, textureMesh?: TextureMesh): Promise<TextureMesh> {
  184. if (!ctx.webgl) throw new Error('webgl context required to create gaussian surface texture-mesh');
  185. const { namedTextures, resources, extensions: { colorBufferFloat, textureFloat, colorBufferHalfFloat, textureHalfFloat } } = ctx.webgl;
  186. if (!namedTextures[GaussianSurfaceName]) {
  187. namedTextures[GaussianSurfaceName] = colorBufferHalfFloat && textureHalfFloat
  188. ? resources.texture('image-float16', 'rgba', 'fp16', 'linear')
  189. : colorBufferFloat && textureFloat
  190. ? resources.texture('image-float32', 'rgba', 'float', 'linear')
  191. : resources.texture('image-uint8', 'rgba', 'ubyte', 'linear');
  192. }
  193. // console.time('computeUnitGaussianDensityTexture2d');
  194. const densityTextureData = await computeUnitGaussianDensityTexture2d(structure, unit, true, props, ctx.webgl, namedTextures[GaussianSurfaceName]).runInContext(ctx.runtime);
  195. // console.log(densityTextureData);
  196. // console.log('vertexGroupTexture', readTexture(ctx.webgl, densityTextureData.texture));
  197. // ctx.webgl.waitForGpuCommandsCompleteSync();
  198. // console.timeEnd('computeUnitGaussianDensityTexture2d');
  199. const isoLevel = Math.exp(-props.smoothness) / densityTextureData.radiusFactor;
  200. const buffer = textureMesh?.doubleBuffer.get();
  201. const gv = extractIsosurface(ctx.webgl, densityTextureData.texture, densityTextureData.gridDim, densityTextureData.gridTexDim, densityTextureData.gridTexScale, densityTextureData.transform, isoLevel, false, true, buffer?.vertex, buffer?.group, buffer?.normal);
  202. const boundingSphere = Sphere3D.expand(Sphere3D(), unit.boundary.sphere, props.radiusOffset + getStructureExtraRadius(structure));
  203. const surface = TextureMesh.create(gv.vertexCount, 1, gv.vertexTexture, gv.groupTexture, gv.normalTexture, boundingSphere, textureMesh);
  204. (surface.meta as GaussianSurfaceMeta) = { resolution: densityTextureData.resolution };
  205. return surface;
  206. }
  207. export function GaussianSurfaceTextureMeshVisual(materialId: number): UnitsVisual<GaussianSurfaceMeshParams> {
  208. return UnitsTextureMeshVisual<GaussianSurfaceMeshParams>({
  209. defaultProps: PD.getDefaultValues(GaussianSurfaceMeshParams),
  210. createGeometry: createGaussianSurfaceTextureMesh,
  211. createLocationIterator: ElementIterator.fromGroup,
  212. getLoci: getElementLoci,
  213. eachLocation: eachElement,
  214. setUpdateState: (state: VisualUpdateState, newProps: PD.Values<GaussianSurfaceMeshParams>, currentProps: PD.Values<GaussianSurfaceMeshParams>) => {
  215. if (newProps.resolution !== currentProps.resolution) state.createGeometry = true;
  216. if (newProps.radiusOffset !== currentProps.radiusOffset) state.createGeometry = true;
  217. if (newProps.smoothness !== currentProps.smoothness) state.createGeometry = true;
  218. if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens) state.createGeometry = true;
  219. if (newProps.traceOnly !== currentProps.traceOnly) state.createGeometry = true;
  220. if (newProps.includeParent !== currentProps.includeParent) state.createGeometry = true;
  221. if (newProps.smoothColors.name !== currentProps.smoothColors.name) {
  222. state.updateColor = true;
  223. } else if (newProps.smoothColors.name === 'on' && currentProps.smoothColors.name === 'on') {
  224. if (newProps.smoothColors.params.resolutionFactor !== currentProps.smoothColors.params.resolutionFactor) state.updateColor = true;
  225. if (newProps.smoothColors.params.sampleStride !== currentProps.smoothColors.params.sampleStride) state.updateColor = true;
  226. }
  227. },
  228. mustRecreate: (structureGroup: StructureGroup, props: PD.Values<GaussianSurfaceMeshParams>, webgl?: WebGLContext) => {
  229. return !props.tryUseGpu || !webgl || !suitableForGpu(structureGroup.structure, props, webgl);
  230. },
  231. processValues: (values: TextureMeshValues, geometry: TextureMesh, props: PD.Values<GaussianSurfaceMeshParams>, theme: Theme, webgl?: WebGLContext) => {
  232. const { resolution, colorTexture } = geometry.meta as GaussianSurfaceMeta;
  233. const csp = getColorSmoothingProps(props, theme, resolution, webgl);
  234. if (csp) {
  235. applyTextureMeshColorSmoothing(values, csp.resolution, csp.stride, csp.webgl, colorTexture);
  236. (geometry.meta as GaussianSurfaceMeta).colorTexture = values.tColorGrid.ref.value;
  237. }
  238. },
  239. dispose: (geometry: TextureMesh) => {
  240. geometry.vertexTexture.ref.value.destroy();
  241. geometry.groupTexture.ref.value.destroy();
  242. geometry.normalTexture.ref.value.destroy();
  243. geometry.doubleBuffer.destroy();
  244. (geometry.meta as GaussianSurfaceMeta).colorTexture?.destroy();
  245. }
  246. }, materialId);
  247. }
  248. //
  249. async function createStructureGaussianSurfaceTextureMesh(ctx: VisualContext, structure: Structure, theme: Theme, props: GaussianDensityProps, textureMesh?: TextureMesh): Promise<TextureMesh> {
  250. if (!ctx.webgl) throw new Error('webgl context required to create structure gaussian surface texture-mesh');
  251. const { namedTextures, resources, extensions: { colorBufferFloat, textureFloat, colorBufferHalfFloat, textureHalfFloat } } = ctx.webgl;
  252. if (!namedTextures[GaussianSurfaceName]) {
  253. namedTextures[GaussianSurfaceName] = colorBufferHalfFloat && textureHalfFloat
  254. ? resources.texture('image-float16', 'rgba', 'fp16', 'linear')
  255. : colorBufferFloat && textureFloat
  256. ? resources.texture('image-float32', 'rgba', 'float', 'linear')
  257. : resources.texture('image-uint8', 'rgba', 'ubyte', 'linear');
  258. }
  259. // console.time('computeUnitGaussianDensityTexture2d');
  260. const densityTextureData = await computeStructureGaussianDensityTexture2d(structure, true, props, ctx.webgl, namedTextures[GaussianSurfaceName]).runInContext(ctx.runtime);
  261. // console.log(densityTextureData);
  262. // console.log('vertexGroupTexture', readTexture(ctx.webgl, densityTextureData.texture));
  263. // ctx.webgl.waitForGpuCommandsCompleteSync();
  264. // console.timeEnd('computeUnitGaussianDensityTexture2d');
  265. const isoLevel = Math.exp(-props.smoothness) / densityTextureData.radiusFactor;
  266. const buffer = textureMesh?.doubleBuffer.get();
  267. const gv = extractIsosurface(ctx.webgl, densityTextureData.texture, densityTextureData.gridDim, densityTextureData.gridTexDim, densityTextureData.gridTexScale, densityTextureData.transform, isoLevel, false, true, buffer?.vertex, buffer?.group, buffer?.normal);
  268. const boundingSphere = Sphere3D.expand(Sphere3D(), structure.boundary.sphere, props.radiusOffset + getStructureExtraRadius(structure));
  269. const surface = TextureMesh.create(gv.vertexCount, 1, gv.vertexTexture, gv.groupTexture, gv.normalTexture, boundingSphere, textureMesh);
  270. (surface.meta as GaussianSurfaceMeta) = { resolution: densityTextureData.resolution };
  271. return surface;
  272. }
  273. export function StructureGaussianSurfaceTextureMeshVisual(materialId: number): ComplexVisual<StructureGaussianSurfaceMeshParams> {
  274. return ComplexTextureMeshVisual<StructureGaussianSurfaceMeshParams>({
  275. defaultProps: PD.getDefaultValues(StructureGaussianSurfaceMeshParams),
  276. createGeometry: createStructureGaussianSurfaceTextureMesh,
  277. createLocationIterator: ElementIterator.fromStructure,
  278. getLoci: getSerialElementLoci,
  279. eachLocation: eachSerialElement,
  280. setUpdateState: (state: VisualUpdateState, newProps: PD.Values<StructureGaussianSurfaceMeshParams>, currentProps: PD.Values<StructureGaussianSurfaceMeshParams>) => {
  281. if (newProps.resolution !== currentProps.resolution) state.createGeometry = true;
  282. if (newProps.radiusOffset !== currentProps.radiusOffset) state.createGeometry = true;
  283. if (newProps.smoothness !== currentProps.smoothness) state.createGeometry = true;
  284. if (newProps.ignoreHydrogens !== currentProps.ignoreHydrogens) state.createGeometry = true;
  285. if (newProps.traceOnly !== currentProps.traceOnly) state.createGeometry = true;
  286. if (newProps.includeParent !== currentProps.includeParent) state.createGeometry = true;
  287. if (newProps.smoothColors.name !== currentProps.smoothColors.name) {
  288. state.updateColor = true;
  289. } else if (newProps.smoothColors.name === 'on' && currentProps.smoothColors.name === 'on') {
  290. if (newProps.smoothColors.params.resolutionFactor !== currentProps.smoothColors.params.resolutionFactor) state.updateColor = true;
  291. if (newProps.smoothColors.params.sampleStride !== currentProps.smoothColors.params.sampleStride) state.updateColor = true;
  292. }
  293. },
  294. mustRecreate: (structure: Structure, props: PD.Values<StructureGaussianSurfaceMeshParams>, webgl?: WebGLContext) => {
  295. return !props.tryUseGpu || !webgl || !suitableForGpu(structure, props, webgl);
  296. },
  297. processValues: (values: TextureMeshValues, geometry: TextureMesh, props: PD.Values<GaussianSurfaceMeshParams>, theme: Theme, webgl?: WebGLContext) => {
  298. const { resolution, colorTexture } = geometry.meta as GaussianSurfaceMeta;
  299. const csp = getColorSmoothingProps(props, theme, resolution, webgl);
  300. if (csp) {
  301. applyTextureMeshColorSmoothing(values, csp.resolution, csp.stride, csp.webgl, colorTexture);
  302. (geometry.meta as GaussianSurfaceMeta).colorTexture = values.tColorGrid.ref.value;
  303. }
  304. },
  305. dispose: (geometry: TextureMesh) => {
  306. geometry.vertexTexture.ref.value.destroy();
  307. geometry.groupTexture.ref.value.destroy();
  308. geometry.normalTexture.ref.value.destroy();
  309. geometry.doubleBuffer.destroy();
  310. (geometry.meta as GaussianSurfaceMeta).colorTexture?.destroy();
  311. }
  312. }, materialId);
  313. }