grid3d.ts 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  1. /**
  2. * Copyright (c) 2020 mol* contributors, licensed under MIT, See LICENSE file for more info.
  3. *
  4. * @author David Sehnal <david.sehnal@gmail.com>
  5. */
  6. import { RenderableSchema, Values, UnboxedValues, UniformSpec, TextureSpec, DefineSpec, RenderableValues } from '../renderable/schema';
  7. import { WebGLContext } from '../webgl/context';
  8. import { getRegularGrid3dDelta, RegularGrid3d } from '../../mol-math/geometry/common';
  9. import { grid3dTemplate_frag } from '../shader/util/grid3d-template.frag';
  10. import { quad_vert } from '../shader/quad.vert';
  11. import { ShaderCode } from '../shader-code';
  12. import { UUID, ValueCell } from '../../mol-util';
  13. import { objectForEach } from '../../mol-util/object';
  14. import { getUniformGlslType, isUniformValueScalar } from '../webgl/uniform';
  15. import { QuadSchema, QuadValues } from './util';
  16. import { createComputeRenderItem } from '../webgl/render-item';
  17. import { createComputeRenderable } from '../renderable';
  18. import { isLittleEndian } from '../../mol-util/is-little-endian';
  19. import { RuntimeContext } from '../../mol-task';
  20. export function canComputeGrid3dOnGPU(webgl?: WebGLContext) {
  21. return !!webgl?.extensions.textureFloat;
  22. }
  23. export interface Grid3DComputeRenderableSpec<S extends RenderableSchema, P, CS> {
  24. schema: S,
  25. // indicate which params are loop bounds for WebGL1 compat
  26. loopBounds?: (keyof S)[]
  27. utilCode?: string,
  28. mainCode: string,
  29. returnCode: string,
  30. values(params: P, grid: RegularGrid3d): UnboxedValues<S>,
  31. cumulative?: {
  32. states(params: P): CS[],
  33. update(params: P, state: CS, values: Values<S>): void,
  34. // call gl.readPixes every 'yieldPeriod' states to split the computation
  35. // into multiple parts, if not set, the computation will be synchronous
  36. yieldPeriod?: number
  37. }
  38. }
  39. const FrameBufferName = 'grid3d-computable' as const;
  40. const Texture0Name = 'grid3d-computable-0' as const;
  41. const Texture1Name = 'grid3d-computable-1' as const;
  42. const SchemaBase = {
  43. ...QuadSchema,
  44. uDimensions: UniformSpec('v3'),
  45. uMin: UniformSpec('v3'),
  46. uDelta: UniformSpec('v3'),
  47. uWidth: UniformSpec('f'),
  48. uLittleEndian: UniformSpec('b'),
  49. };
  50. const CumulativeSumSchema = {
  51. tCumulativeSum: TextureSpec('texture', 'rgba', 'ubyte', 'nearest')
  52. };
  53. export function createGrid3dComputeRenderable<S extends RenderableSchema, P, CS>(spec: Grid3DComputeRenderableSpec<S, P, CS>) {
  54. const id = UUID.create22();
  55. const uniforms: string[] = [];
  56. objectForEach(spec.schema, (u, k) => {
  57. if (u.type === 'define') return;
  58. if (u.kind.indexOf('[]') >= 0) throw new Error('array uniforms are not supported');
  59. const isBound = (spec.loopBounds?.indexOf(k) ?? -1) >= 0;
  60. if (isBound) uniforms.push(`#ifndef ${k}`);
  61. if (u.type === 'uniform') uniforms.push(`uniform ${getUniformGlslType(u.kind as any)} ${k};`);
  62. else if (u.type === 'texture') uniforms.push(`uniform sampler2D ${k};`);
  63. if (isBound) uniforms.push(`#endif`);
  64. });
  65. const code = grid3dTemplate_frag
  66. .replace('{UNIFORMS}', uniforms.join('\n'))
  67. .replace('{UTILS}', spec.utilCode ?? '')
  68. .replace('{MAIN}', spec.mainCode)
  69. .replace('{RETURN}', spec.returnCode);
  70. const shader = ShaderCode(id, quad_vert, code);
  71. return async (ctx: RuntimeContext, webgl: WebGLContext, grid: RegularGrid3d, params: P) => {
  72. const schema: RenderableSchema = {
  73. ...SchemaBase,
  74. ...(spec.cumulative ? CumulativeSumSchema : {}),
  75. ...spec.schema,
  76. };
  77. if (!webgl.isWebGL2) {
  78. if (spec.loopBounds) {
  79. for (const b of spec.loopBounds) {
  80. (schema as any)[b] = DefineSpec('number');
  81. }
  82. }
  83. (schema as any)['WEBGL1'] = DefineSpec('boolean');
  84. }
  85. if (spec.cumulative) {
  86. (schema as any)['CUMULATIVE'] = DefineSpec('boolean');
  87. }
  88. if (!webgl.namedFramebuffers[FrameBufferName]) {
  89. webgl.namedFramebuffers[FrameBufferName] = webgl.resources.framebuffer();
  90. }
  91. const framebuffer = webgl.namedFramebuffers[FrameBufferName];
  92. if (!webgl.namedTextures[Texture0Name]) {
  93. webgl.namedTextures[Texture0Name] = webgl.resources.texture('image-uint8', 'rgba', 'ubyte', 'nearest');
  94. }
  95. if (spec.cumulative && !webgl.namedTextures[Texture1Name]) {
  96. webgl.namedTextures[Texture1Name] = webgl.resources.texture('image-uint8', 'rgba', 'ubyte', 'nearest');
  97. }
  98. const tex = [webgl.namedTextures[Texture0Name], webgl.namedTextures[Texture1Name]];
  99. const [nx, ny, nz] = grid.dimensions;
  100. const uWidth = Math.ceil(Math.sqrt(nx * ny * nz));
  101. const values: UnboxedValues<S & typeof SchemaBase> = {
  102. uDimensions: grid.dimensions,
  103. uMin: grid.box.min,
  104. uDelta: getRegularGrid3dDelta(grid),
  105. uWidth,
  106. uLittleEndian: isLittleEndian(),
  107. ...spec.values(params, grid)
  108. } as any;
  109. if (!webgl.isWebGL2) {
  110. (values as any).WEBGL1 = true;
  111. }
  112. if (spec.cumulative) {
  113. (values as any).tCumulativeSum = tex[0];
  114. (values as any).CUMULATIVE = true;
  115. }
  116. let renderable = webgl.namedComputeRenderables[id];
  117. let cells: RenderableValues;
  118. if (renderable) {
  119. cells = renderable.values as RenderableValues;
  120. objectForEach(values, (c, k) => {
  121. const s = schema[k];
  122. if (s?.type === 'value' || s?.type === 'attribute') return;
  123. if (!s || !isUniformValueScalar(s.kind as any)) {
  124. ValueCell.update(cells[k], c);
  125. } else {
  126. ValueCell.updateIfChanged(cells[k], c);
  127. }
  128. });
  129. } else {
  130. cells = {} as any;
  131. objectForEach(QuadValues, (v, k) => (cells as any)[k] = v);
  132. objectForEach(values, (v, k) => (cells as any)[k] = ValueCell.create(v));
  133. renderable = createComputeRenderable(createComputeRenderItem(webgl, 'triangles', shader, schema, cells), cells);
  134. }
  135. const array = new Uint8Array(uWidth * uWidth * 4);
  136. if (spec.cumulative) {
  137. const { gl } = webgl;
  138. const states = spec.cumulative.states(params);
  139. tex[0].define(uWidth, uWidth);
  140. tex[1].define(uWidth, uWidth);
  141. resetGl(webgl, uWidth);
  142. gl.clearColor(0, 0, 0, 0);
  143. tex[0].attachFramebuffer(framebuffer, 'color0');
  144. gl.clear(gl.COLOR_BUFFER_BIT);
  145. tex[1].attachFramebuffer(framebuffer, 'color0');
  146. gl.clear(gl.COLOR_BUFFER_BIT);
  147. if (spec.cumulative.yieldPeriod) {
  148. await ctx.update({ message: 'Computing...', isIndeterminate: false, current: 0, max: states.length });
  149. }
  150. const yieldPeriod = Math.max(1, spec.cumulative.yieldPeriod ?? 1 | 0);
  151. for (let i = 0; i < states.length; i++) {
  152. ValueCell.update(cells.tCumulativeSum, tex[(i + 1) % 2]);
  153. tex[i % 2].attachFramebuffer(framebuffer, 'color0');
  154. resetGl(webgl, uWidth);
  155. spec.cumulative.update(params, states[i], cells as any);
  156. renderable.update();
  157. renderable.render();
  158. if (spec.cumulative.yieldPeriod && i !== states.length - 1) {
  159. if (i % yieldPeriod === yieldPeriod - 1) {
  160. webgl.readPixels(0, 0, 1, 1, array);
  161. }
  162. if (ctx.shouldUpdate) {
  163. await ctx.update({ current: i + 1 });
  164. }
  165. }
  166. }
  167. } else {
  168. tex[0].define(uWidth, uWidth);
  169. tex[0].attachFramebuffer(framebuffer, 'color0');
  170. framebuffer.bind();
  171. resetGl(webgl, uWidth);
  172. renderable.update();
  173. renderable.render();
  174. }
  175. webgl.readPixels(0, 0, uWidth, uWidth, array);
  176. return new Float32Array(array.buffer, array.byteOffset, nx * ny * nz);
  177. };
  178. }
  179. function resetGl(webgl: WebGLContext, w: number) {
  180. const { gl, state } = webgl;
  181. gl.viewport(0, 0, w, w);
  182. gl.scissor(0, 0, w, w);
  183. state.disable(gl.SCISSOR_TEST);
  184. state.disable(gl.BLEND);
  185. state.disable(gl.DEPTH_TEST);
  186. state.depthMask(false);
  187. }