isosurface.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * Copyright (c) 2018-2022 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. * @author Alexander Rose <alexander.rose@weirdbyte.de>
  6. */
  7. import { ParamDefinition as PD } from '../../mol-util/param-definition';
  8. import { Grid, Volume } from '../../mol-model/volume';
  9. import { VisualContext } from '../visual';
  10. import { Theme, ThemeRegistryContext } from '../../mol-theme/theme';
  11. import { Mesh } from '../../mol-geo/geometry/mesh/mesh';
  12. import { computeMarchingCubesMesh, computeMarchingCubesLines } from '../../mol-geo/util/marching-cubes/algorithm';
  13. import { VolumeVisual, VolumeRepresentation, VolumeRepresentationProvider, VolumeKey } from './representation';
  14. import { LocationIterator } from '../../mol-geo/util/location-iterator';
  15. import { NullLocation } from '../../mol-model/location';
  16. import { VisualUpdateState } from '../util';
  17. import { Lines } from '../../mol-geo/geometry/lines/lines';
  18. import { RepresentationContext, RepresentationParamsGetter, Representation } from '../representation';
  19. import { PickingId } from '../../mol-geo/geometry/picking';
  20. import { EmptyLoci, Loci } from '../../mol-model/loci';
  21. import { Interval } from '../../mol-data/int';
  22. import { Tensor, Vec2, Vec3 } from '../../mol-math/linear-algebra';
  23. import { fillSerial } from '../../mol-util/array';
  24. import { createVolumeTexture2d, eachVolumeLoci, getVolumeTexture2dLayout } from './util';
  25. import { TextureMesh } from '../../mol-geo/geometry/texture-mesh/texture-mesh';
  26. import { extractIsosurface } from '../../mol-gl/compute/marching-cubes/isosurface';
  27. import { WebGLContext } from '../../mol-gl/webgl/context';
  28. import { CustomPropertyDescriptor } from '../../mol-model/custom-property';
  29. import { Texture } from '../../mol-gl/webgl/texture';
  30. import { BaseGeometry } from '../../mol-geo/geometry/base';
  31. import { ValueCell } from '../../mol-util/value-cell';
  32. export const VolumeIsosurfaceParams = {
  33. isoValue: Volume.IsoValueParam
  34. };
  35. export type VolumeIsosurfaceParams = typeof VolumeIsosurfaceParams
  36. export type VolumeIsosurfaceProps = PD.Values<VolumeIsosurfaceParams>
  37. function gpuSupport(webgl: WebGLContext) {
  38. return webgl.extensions.colorBufferFloat && webgl.extensions.textureFloat && webgl.extensions.drawBuffers;
  39. }
  40. const Padding = 1;
  41. function suitableForGpu(volume: Volume, webgl: WebGLContext) {
  42. // small volumes are about as fast or faster on CPU vs integrated GPU
  43. if (volume.grid.cells.data.length < Math.pow(10, 3)) return false;
  44. // the GPU is much more memory contraint, especially true for integrated GPUs,
  45. // fallback to CPU for large volumes
  46. const gridDim = volume.grid.cells.space.dimensions as Vec3;
  47. const { powerOfTwoSize } = getVolumeTexture2dLayout(gridDim, Padding);
  48. return powerOfTwoSize <= webgl.maxTextureSize / 2;
  49. }
  50. export function IsosurfaceVisual(materialId: number, volume: Volume, key: number, props: PD.Values<IsosurfaceMeshParams>, webgl?: WebGLContext) {
  51. if (props.tryUseGpu && webgl && gpuSupport(webgl) && suitableForGpu(volume, webgl)) {
  52. return IsosurfaceTextureMeshVisual(materialId);
  53. }
  54. return IsosurfaceMeshVisual(materialId);
  55. }
  56. function getLoci(volume: Volume, props: VolumeIsosurfaceProps) {
  57. return Volume.Isosurface.Loci(volume, props.isoValue);
  58. }
  59. function getIsosurfaceLoci(pickingId: PickingId, volume: Volume, key: number, props: VolumeIsosurfaceProps, id: number) {
  60. const { objectId, groupId } = pickingId;
  61. if (id === objectId) {
  62. const granularity = Volume.PickingGranularity.get(volume);
  63. if (granularity === 'volume') {
  64. return Volume.Loci(volume);
  65. } else if (granularity === 'object') {
  66. return Volume.Isosurface.Loci(volume, props.isoValue);
  67. } else {
  68. return Volume.Cell.Loci(volume, Interval.ofSingleton(groupId as Volume.CellIndex));
  69. }
  70. }
  71. return EmptyLoci;
  72. }
  73. export function eachIsosurface(loci: Loci, volume: Volume, key: number, props: VolumeIsosurfaceProps, apply: (interval: Interval) => boolean) {
  74. return eachVolumeLoci(loci, volume, { isoValue: props.isoValue }, apply);
  75. }
  76. //
  77. export async function createVolumeIsosurfaceMesh(ctx: VisualContext, volume: Volume, key: number, theme: Theme, props: VolumeIsosurfaceProps, mesh?: Mesh) {
  78. ctx.runtime.update({ message: 'Marching cubes...' });
  79. const ids = fillSerial(new Int32Array(volume.grid.cells.data.length));
  80. const surface = await computeMarchingCubesMesh({
  81. isoLevel: Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue,
  82. scalarField: volume.grid.cells,
  83. idField: Tensor.create(volume.grid.cells.space, Tensor.Data1(ids))
  84. }, mesh).runAsChild(ctx.runtime);
  85. const transform = Grid.getGridToCartesianTransform(volume.grid);
  86. Mesh.transform(surface, transform);
  87. if (ctx.webgl && !ctx.webgl.isWebGL2) {
  88. // 2nd arg means not to split triangles based on group id. Splitting triangles
  89. // is too expensive if each cell has its own group id as is the case here.
  90. Mesh.uniformTriangleGroup(surface, false);
  91. ValueCell.updateIfChanged(surface.varyingGroup, false);
  92. } else {
  93. ValueCell.updateIfChanged(surface.varyingGroup, true);
  94. }
  95. surface.setBoundingSphere(Volume.Isosurface.getBoundingSphere(volume, props.isoValue));
  96. return surface;
  97. }
  98. export const IsosurfaceMeshParams = {
  99. ...Mesh.Params,
  100. ...TextureMesh.Params,
  101. ...VolumeIsosurfaceParams,
  102. quality: { ...Mesh.Params.quality, isEssential: false },
  103. tryUseGpu: PD.Boolean(true),
  104. };
  105. export type IsosurfaceMeshParams = typeof IsosurfaceMeshParams
  106. export function IsosurfaceMeshVisual(materialId: number): VolumeVisual<IsosurfaceMeshParams> {
  107. return VolumeVisual<Mesh, IsosurfaceMeshParams>({
  108. defaultProps: PD.getDefaultValues(IsosurfaceMeshParams),
  109. createGeometry: createVolumeIsosurfaceMesh,
  110. createLocationIterator: (volume: Volume) => LocationIterator(volume.grid.cells.data.length, 1, 1, () => NullLocation),
  111. getLoci: getIsosurfaceLoci,
  112. eachLocation: eachIsosurface,
  113. setUpdateState: (state: VisualUpdateState, volume: Volume, newProps: PD.Values<IsosurfaceMeshParams>, currentProps: PD.Values<IsosurfaceMeshParams>) => {
  114. if (!Volume.IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats)) state.createGeometry = true;
  115. },
  116. geometryUtils: Mesh.Utils,
  117. mustRecreate: (volumekey: VolumeKey, props: PD.Values<IsosurfaceMeshParams>, webgl?: WebGLContext) => {
  118. return props.tryUseGpu && !!webgl && suitableForGpu(volumekey.volume, webgl);
  119. }
  120. }, materialId);
  121. }
  122. //
  123. namespace VolumeIsosurfaceTexture {
  124. const name = 'volume-isosurface-texture';
  125. export const descriptor = CustomPropertyDescriptor({ name });
  126. export function get(volume: Volume, webgl: WebGLContext) {
  127. const { resources } = webgl;
  128. const transform = Grid.getGridToCartesianTransform(volume.grid);
  129. const gridDimension = Vec3.clone(volume.grid.cells.space.dimensions as Vec3);
  130. const { width, height, powerOfTwoSize: texDim } = getVolumeTexture2dLayout(gridDimension, Padding);
  131. const gridTexDim = Vec3.create(width, height, 0);
  132. const gridTexScale = Vec2.create(width / texDim, height / texDim);
  133. // console.log({ texDim, width, height, gridDimension });
  134. if (texDim > webgl.maxTextureSize / 2) {
  135. throw new Error('volume too large for gpu isosurface extraction');
  136. }
  137. if (!volume._propertyData[name]) {
  138. volume._propertyData[name] = resources.texture('image-uint8', 'alpha', 'ubyte', 'linear');
  139. const texture = volume._propertyData[name] as Texture;
  140. texture.define(texDim, texDim);
  141. // load volume into sub-section of texture
  142. texture.load(createVolumeTexture2d(volume, 'data', Padding), true);
  143. volume.customProperties.add(descriptor);
  144. volume.customProperties.assets(descriptor, [{ dispose: () => texture.destroy() }]);
  145. }
  146. gridDimension[0] += Padding;
  147. gridDimension[1] += Padding;
  148. return {
  149. texture: volume._propertyData[name] as Texture,
  150. transform,
  151. gridDimension,
  152. gridTexDim,
  153. gridTexScale
  154. };
  155. }
  156. }
  157. async function createVolumeIsosurfaceTextureMesh(ctx: VisualContext, volume: Volume, key: number, theme: Theme, props: VolumeIsosurfaceProps, textureMesh?: TextureMesh) {
  158. if (!ctx.webgl) throw new Error('webgl context required to create volume isosurface texture-mesh');
  159. if (volume.grid.cells.data.length <= 1) {
  160. return TextureMesh.createEmpty(textureMesh);
  161. }
  162. const { max, min } = volume.grid.stats;
  163. const diff = max - min;
  164. const value = Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue;
  165. const isoLevel = ((value - min) / diff);
  166. const { texture, gridDimension, gridTexDim, gridTexScale, transform } = VolumeIsosurfaceTexture.get(volume, ctx.webgl);
  167. const axisOrder = volume.grid.cells.space.axisOrderSlowToFast as Vec3;
  168. const buffer = textureMesh?.doubleBuffer.get();
  169. const gv = extractIsosurface(ctx.webgl, texture, gridDimension, gridTexDim, gridTexScale, transform, isoLevel, value < 0, false, axisOrder, true, buffer?.vertex, buffer?.group, buffer?.normal);
  170. const groupCount = volume.grid.cells.data.length;
  171. const boundingSphere = Volume.getBoundingSphere(volume); // getting isosurface bounding-sphere is too expensive here
  172. const surface = TextureMesh.create(gv.vertexCount, groupCount, gv.vertexTexture, gv.groupTexture, gv.normalTexture, boundingSphere, textureMesh);
  173. surface.meta.webgl = ctx.webgl;
  174. return surface;
  175. }
  176. export function IsosurfaceTextureMeshVisual(materialId: number): VolumeVisual<IsosurfaceMeshParams> {
  177. return VolumeVisual<TextureMesh, IsosurfaceMeshParams>({
  178. defaultProps: PD.getDefaultValues(IsosurfaceMeshParams),
  179. createGeometry: createVolumeIsosurfaceTextureMesh,
  180. createLocationIterator: (volume: Volume) => LocationIterator(volume.grid.cells.data.length, 1, 1, () => NullLocation),
  181. getLoci: getIsosurfaceLoci,
  182. eachLocation: eachIsosurface,
  183. setUpdateState: (state: VisualUpdateState, volume: Volume, newProps: PD.Values<IsosurfaceMeshParams>, currentProps: PD.Values<IsosurfaceMeshParams>) => {
  184. if (!Volume.IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats)) state.createGeometry = true;
  185. },
  186. geometryUtils: TextureMesh.Utils,
  187. mustRecreate: (volumeKey: VolumeKey, props: PD.Values<IsosurfaceMeshParams>, webgl?: WebGLContext) => {
  188. return !props.tryUseGpu || !webgl || !suitableForGpu(volumeKey.volume, webgl);
  189. },
  190. dispose: (geometry: TextureMesh) => {
  191. geometry.vertexTexture.ref.value.destroy();
  192. geometry.groupTexture.ref.value.destroy();
  193. geometry.normalTexture.ref.value.destroy();
  194. geometry.doubleBuffer.destroy();
  195. }
  196. }, materialId);
  197. }
  198. //
  199. export async function createVolumeIsosurfaceWireframe(ctx: VisualContext, volume: Volume, key: number, theme: Theme, props: VolumeIsosurfaceProps, lines?: Lines) {
  200. ctx.runtime.update({ message: 'Marching cubes...' });
  201. const ids = fillSerial(new Int32Array(volume.grid.cells.data.length));
  202. const wireframe = await computeMarchingCubesLines({
  203. isoLevel: Volume.IsoValue.toAbsolute(props.isoValue, volume.grid.stats).absoluteValue,
  204. scalarField: volume.grid.cells,
  205. idField: Tensor.create(volume.grid.cells.space, Tensor.Data1(ids))
  206. }, lines).runAsChild(ctx.runtime);
  207. const transform = Grid.getGridToCartesianTransform(volume.grid);
  208. Lines.transform(wireframe, transform);
  209. wireframe.setBoundingSphere(Volume.Isosurface.getBoundingSphere(volume, props.isoValue));
  210. return wireframe;
  211. }
  212. export const IsosurfaceWireframeParams = {
  213. ...Lines.Params,
  214. ...VolumeIsosurfaceParams,
  215. quality: { ...Lines.Params.quality, isEssential: false },
  216. sizeFactor: PD.Numeric(3, { min: 0, max: 10, step: 0.1 }),
  217. };
  218. export type IsosurfaceWireframeParams = typeof IsosurfaceWireframeParams
  219. export function IsosurfaceWireframeVisual(materialId: number): VolumeVisual<IsosurfaceWireframeParams> {
  220. return VolumeVisual<Lines, IsosurfaceWireframeParams>({
  221. defaultProps: PD.getDefaultValues(IsosurfaceWireframeParams),
  222. createGeometry: createVolumeIsosurfaceWireframe,
  223. createLocationIterator: (volume: Volume) => LocationIterator(volume.grid.cells.data.length, 1, 1, () => NullLocation),
  224. getLoci: getIsosurfaceLoci,
  225. eachLocation: eachIsosurface,
  226. setUpdateState: (state: VisualUpdateState, volume: Volume, newProps: PD.Values<IsosurfaceWireframeParams>, currentProps: PD.Values<IsosurfaceWireframeParams>) => {
  227. if (!Volume.IsoValue.areSame(newProps.isoValue, currentProps.isoValue, volume.grid.stats)) state.createGeometry = true;
  228. },
  229. geometryUtils: Lines.Utils
  230. }, materialId);
  231. }
  232. //
  233. const IsosurfaceVisuals = {
  234. 'solid': (ctx: RepresentationContext, getParams: RepresentationParamsGetter<Volume, IsosurfaceMeshParams>) => VolumeRepresentation('Isosurface mesh', ctx, getParams, IsosurfaceVisual, getLoci),
  235. 'wireframe': (ctx: RepresentationContext, getParams: RepresentationParamsGetter<Volume, IsosurfaceWireframeParams>) => VolumeRepresentation('Isosurface wireframe', ctx, getParams, IsosurfaceWireframeVisual, getLoci),
  236. };
  237. export const IsosurfaceParams = {
  238. ...IsosurfaceMeshParams,
  239. ...IsosurfaceWireframeParams,
  240. visuals: PD.MultiSelect(['solid'], PD.objectToOptions(IsosurfaceVisuals)),
  241. bumpFrequency: PD.Numeric(1, { min: 0, max: 10, step: 0.1 }, BaseGeometry.ShadingCategory),
  242. };
  243. export type IsosurfaceParams = typeof IsosurfaceParams
  244. export function getIsosurfaceParams(ctx: ThemeRegistryContext, volume: Volume) {
  245. const p = PD.clone(IsosurfaceParams);
  246. p.isoValue = Volume.createIsoValueParam(Volume.IsoValue.relative(2), volume.grid.stats);
  247. return p;
  248. }
  249. export type IsosurfaceRepresentation = VolumeRepresentation<IsosurfaceParams>
  250. export function IsosurfaceRepresentation(ctx: RepresentationContext, getParams: RepresentationParamsGetter<Volume, IsosurfaceParams>): IsosurfaceRepresentation {
  251. return Representation.createMulti('Isosurface', ctx, getParams, Representation.StateBuilder, IsosurfaceVisuals as unknown as Representation.Def<Volume, IsosurfaceParams>);
  252. }
  253. export const IsosurfaceRepresentationProvider = VolumeRepresentationProvider({
  254. name: 'isosurface',
  255. label: 'Isosurface',
  256. description: 'Displays a triangulated isosurface of volumetric data.',
  257. factory: IsosurfaceRepresentation,
  258. getParams: getIsosurfaceParams,
  259. defaultValues: PD.getDefaultValues(IsosurfaceParams),
  260. defaultColorTheme: { name: 'uniform' },
  261. defaultSizeTheme: { name: 'uniform' },
  262. isApplicable: (volume: Volume) => !Volume.isEmpty(volume) && !Volume.Segmentation.get(volume)
  263. });