shader-code.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 { ValueCell } from '../mol-util';
  7. import { idFactory } from '../mol-util/id-factory';
  8. import { WebGLExtensions } from './webgl/extensions';
  9. import { isWebGL2, GLRenderingContext } from './webgl/compat';
  10. export type DefineKind = 'boolean' | 'string' | 'number'
  11. export type DefineType = boolean | string
  12. export type DefineValues = { [k: string]: ValueCell<DefineType> }
  13. const shaderCodeId = idFactory();
  14. type ShaderExtensionsValue = 'required' | 'optional'
  15. export interface ShaderExtensions {
  16. readonly standardDerivatives?: ShaderExtensionsValue
  17. readonly fragDepth?: ShaderExtensionsValue
  18. readonly drawBuffers?: ShaderExtensionsValue
  19. readonly shaderTextureLod?: ShaderExtensionsValue
  20. }
  21. type FragOutTypes = { [k in number]: 'vec4' | 'ivec4' }
  22. export interface ShaderCode {
  23. readonly id: number
  24. readonly name: string
  25. readonly vert: string
  26. readonly frag: string
  27. readonly extensions: ShaderExtensions
  28. /** Fragment shader output type only applicable for webgl2 */
  29. readonly outTypes: FragOutTypes
  30. }
  31. import { apply_fog } from './shader/chunks/apply-fog.glsl';
  32. import { apply_interior_color } from './shader/chunks/apply-interior-color.glsl';
  33. import { apply_light_color } from './shader/chunks/apply-light-color.glsl';
  34. import { apply_marker_color } from './shader/chunks/apply-marker-color.glsl';
  35. import { assign_clipping_varying } from './shader/chunks/assign-clipping-varying.glsl';
  36. import { assign_color_varying } from './shader/chunks/assign-color-varying.glsl';
  37. import { assign_group } from './shader/chunks/assign-group.glsl';
  38. import { assign_marker_varying } from './shader/chunks/assign-marker-varying.glsl';
  39. import { assign_material_color } from './shader/chunks/assign-material-color.glsl';
  40. import { assign_position } from './shader/chunks/assign-position.glsl';
  41. import { assign_size } from './shader/chunks/assign-size.glsl';
  42. import { check_picking_alpha } from './shader/chunks/check-picking-alpha.glsl';
  43. import { clip_instance } from './shader/chunks/clip-instance.glsl';
  44. import { clip_pixel } from './shader/chunks/clip-pixel.glsl';
  45. import { color_frag_params } from './shader/chunks/color-frag-params.glsl';
  46. import { color_vert_params } from './shader/chunks/color-vert-params.glsl';
  47. import { common_clip } from './shader/chunks/common-clip.glsl';
  48. import { common_frag_params } from './shader/chunks/common-frag-params.glsl';
  49. import { common_vert_params } from './shader/chunks/common-vert-params.glsl';
  50. import { common } from './shader/chunks/common.glsl';
  51. import { float_to_rgba } from './shader/chunks/float-to-rgba.glsl';
  52. import { light_frag_params } from './shader/chunks/light-frag-params.glsl';
  53. import { matrix_scale } from './shader/chunks/matrix-scale.glsl';
  54. import { normal_frag_params } from './shader/chunks/normal-frag-params.glsl';
  55. import { read_from_texture } from './shader/chunks/read-from-texture.glsl';
  56. import { rgba_to_float } from './shader/chunks/rgba-to-float.glsl';
  57. import { size_vert_params } from './shader/chunks/size-vert-params.glsl';
  58. import { texture3d_from_1d_trilinear } from './shader/chunks/texture3d-from-1d-trilinear.glsl';
  59. import { texture3d_from_2d_linear } from './shader/chunks/texture3d-from-2d-linear.glsl';
  60. import { texture3d_from_2d_nearest } from './shader/chunks/texture3d-from-2d-nearest.glsl';
  61. import { wboit_write } from './shader/chunks/wboit-write.glsl';
  62. const ShaderChunks: { [k: string]: string } = {
  63. apply_fog,
  64. apply_interior_color,
  65. apply_light_color,
  66. apply_marker_color,
  67. assign_clipping_varying,
  68. assign_color_varying,
  69. assign_group,
  70. assign_marker_varying,
  71. assign_material_color,
  72. assign_position,
  73. assign_size,
  74. check_picking_alpha,
  75. clip_instance,
  76. clip_pixel,
  77. color_frag_params,
  78. color_vert_params,
  79. common_clip,
  80. common_frag_params,
  81. common_vert_params,
  82. common,
  83. float_to_rgba,
  84. light_frag_params,
  85. matrix_scale,
  86. normal_frag_params,
  87. read_from_texture,
  88. rgba_to_float,
  89. size_vert_params,
  90. texture3d_from_1d_trilinear,
  91. texture3d_from_2d_linear,
  92. texture3d_from_2d_nearest,
  93. wboit_write
  94. };
  95. const reInclude = /^(?!\/\/)\s*#include\s+(\S+)/gmi;
  96. const reSingleLineComment = /[ \t]*\/\/.*\n/g;
  97. const reMultiLineComment = /[ \t]*\/\*[\s\S]*?\*\//g;
  98. const reMultipleLinebreaks = /\n{2,}/g;
  99. function addIncludes(text: string) {
  100. return text
  101. .replace(reInclude, (_, p1) => {
  102. const chunk = ShaderChunks[p1];
  103. if (!chunk) throw new Error(`empty chunk, '${p1}'`);
  104. return chunk;
  105. })
  106. .trim()
  107. .replace(reSingleLineComment, '\n')
  108. .replace(reMultiLineComment, '\n')
  109. .replace(reMultipleLinebreaks, '\n');
  110. }
  111. export function ShaderCode(name: string, vert: string, frag: string, extensions: ShaderExtensions = {}, outTypes: FragOutTypes = {}): ShaderCode {
  112. return { id: shaderCodeId(), name, vert: addIncludes(vert), frag: addIncludes(frag), extensions, outTypes };
  113. }
  114. // Note: `drawBuffers` need to be 'optional' for wboit
  115. import { points_vert } from './shader/points.vert';
  116. import { points_frag } from './shader/points.frag';
  117. export const PointsShaderCode = ShaderCode('points', points_vert, points_frag, { drawBuffers: 'optional' });
  118. import { spheres_vert } from './shader/spheres.vert';
  119. import { spheres_frag } from './shader/spheres.frag';
  120. export const SpheresShaderCode = ShaderCode('spheres', spheres_vert, spheres_frag, { fragDepth: 'required', drawBuffers: 'optional' });
  121. import { cylinders_vert } from './shader/cylinders.vert';
  122. import { cylinders_frag } from './shader/cylinders.frag';
  123. export const CylindersShaderCode = ShaderCode('cylinders', cylinders_vert, cylinders_frag, { fragDepth: 'required', drawBuffers: 'optional' });
  124. import { text_vert } from './shader/text.vert';
  125. import { text_frag } from './shader/text.frag';
  126. export const TextShaderCode = ShaderCode('text', text_vert, text_frag, { standardDerivatives: 'required', drawBuffers: 'optional' });
  127. import { lines_vert } from './shader/lines.vert';
  128. import { lines_frag } from './shader/lines.frag';
  129. export const LinesShaderCode = ShaderCode('lines', lines_vert, lines_frag, { drawBuffers: 'optional' });
  130. import { mesh_vert } from './shader/mesh.vert';
  131. import { mesh_frag } from './shader/mesh.frag';
  132. export const MeshShaderCode = ShaderCode('mesh', mesh_vert, mesh_frag, { standardDerivatives: 'optional', drawBuffers: 'optional' });
  133. import { directVolume_vert } from './shader/direct-volume.vert';
  134. import { directVolume_frag } from './shader/direct-volume.frag';
  135. export const DirectVolumeShaderCode = ShaderCode('direct-volume', directVolume_vert, directVolume_frag, { fragDepth: 'optional', drawBuffers: 'optional' });
  136. import { image_vert } from './shader/image.vert';
  137. import { image_frag } from './shader/image.frag';
  138. export const ImageShaderCode = ShaderCode('image', image_vert, image_frag, { drawBuffers: 'optional' });
  139. //
  140. export type ShaderDefines = {
  141. [k: string]: ValueCell<DefineType>
  142. }
  143. function getDefinesCode(defines: ShaderDefines) {
  144. if (defines === undefined) return '';
  145. const lines = [];
  146. for (const name in defines) {
  147. const define = defines[name];
  148. const v = define.ref.value;
  149. if (v !== undefined) {
  150. if (typeof v === 'string') {
  151. lines.push(`#define ${name}_${v}`);
  152. } else if (typeof v === 'number') {
  153. lines.push(`#define ${name} ${v}`);
  154. } else if (typeof v === 'boolean') {
  155. if (v) lines.push(`#define ${name}`);
  156. } else {
  157. throw new Error('unknown define type');
  158. }
  159. }
  160. }
  161. return lines.join('\n') + '\n';
  162. }
  163. function getGlsl100FragPrefix(extensions: WebGLExtensions, shaderExtensions: ShaderExtensions) {
  164. const prefix: string[] = [];
  165. if (shaderExtensions.standardDerivatives) {
  166. prefix.push('#extension GL_OES_standard_derivatives : enable');
  167. prefix.push('#define enabledStandardDerivatives');
  168. }
  169. if (shaderExtensions.fragDepth) {
  170. if (extensions.fragDepth) {
  171. prefix.push('#extension GL_EXT_frag_depth : enable');
  172. prefix.push('#define enabledFragDepth');
  173. } else if (shaderExtensions.fragDepth === 'required') {
  174. throw new Error(`required 'GL_EXT_frag_depth' extension not available`);
  175. }
  176. }
  177. if (shaderExtensions.drawBuffers) {
  178. if (extensions.drawBuffers) {
  179. prefix.push('#extension GL_EXT_draw_buffers : require');
  180. prefix.push('#define requiredDrawBuffers');
  181. prefix.push('#define gl_FragColor gl_FragData[0]');
  182. } else if (shaderExtensions.drawBuffers === 'required') {
  183. throw new Error(`required 'GL_EXT_draw_buffers' extension not available`);
  184. }
  185. }
  186. if (shaderExtensions.shaderTextureLod) {
  187. if (extensions.shaderTextureLod) {
  188. prefix.push('#extension GL_EXT_shader_texture_lod : enable');
  189. prefix.push('#define enabledShaderTextureLod');
  190. } else if (shaderExtensions.shaderTextureLod === 'required') {
  191. throw new Error(`required 'GL_EXT_shader_texture_lod' extension not available`);
  192. }
  193. }
  194. if (extensions.depthTexture) {
  195. prefix.push('#define depthTextureSupport');
  196. }
  197. return prefix.join('\n') + '\n';
  198. }
  199. const glsl300VertPrefix = `#version 300 es
  200. #define attribute in
  201. #define varying out
  202. #define texture2D texture
  203. `;
  204. const glsl300FragPrefixCommon = `
  205. #define varying in
  206. #define texture2D texture
  207. #define texture2DLodEXT textureLod
  208. #define gl_FragColor out_FragData0
  209. #define gl_FragDepthEXT gl_FragDepth
  210. #define depthTextureSupport
  211. `;
  212. function getGlsl300FragPrefix(gl: WebGL2RenderingContext, extensions: WebGLExtensions, shaderExtensions: ShaderExtensions, outTypes: FragOutTypes) {
  213. const prefix = [
  214. '#version 300 es',
  215. `layout(location = 0) out highp ${outTypes[0] || 'vec4'} out_FragData0;`
  216. ];
  217. if (shaderExtensions.standardDerivatives) {
  218. prefix.push('#define enabledStandardDerivatives');
  219. }
  220. if (shaderExtensions.fragDepth) {
  221. prefix.push('#define enabledFragDepth');
  222. }
  223. if (shaderExtensions.drawBuffers) {
  224. prefix.push('#define requiredDrawBuffers');
  225. const maxDrawBuffers = gl.getParameter(gl.MAX_DRAW_BUFFERS) as number;
  226. for (let i = 1, il = maxDrawBuffers; i < il; ++i) {
  227. prefix.push(`layout(location = ${i}) out highp ${outTypes[i] || 'vec4'} out_FragData${i};`);
  228. }
  229. }
  230. if (shaderExtensions.shaderTextureLod) {
  231. prefix.push('#define enabledShaderTextureLod');
  232. }
  233. prefix.push(glsl300FragPrefixCommon);
  234. return prefix.join('\n') + '\n';
  235. }
  236. function transformGlsl300Frag(frag: string) {
  237. return frag.replace(/gl_FragData\[([0-9]+)\]/g, 'out_FragData$1');
  238. }
  239. export function addShaderDefines(gl: GLRenderingContext, extensions: WebGLExtensions, defines: ShaderDefines, shaders: ShaderCode): ShaderCode {
  240. const header = getDefinesCode(defines);
  241. const vertPrefix = isWebGL2(gl) ? glsl300VertPrefix : '';
  242. const fragPrefix = isWebGL2(gl)
  243. ? getGlsl300FragPrefix(gl, extensions, shaders.extensions, shaders.outTypes)
  244. : getGlsl100FragPrefix(extensions, shaders.extensions);
  245. const frag = isWebGL2(gl) ? transformGlsl300Frag(shaders.frag) : shaders.frag;
  246. return {
  247. id: shaderCodeId(),
  248. name: shaders.name,
  249. vert: `${vertPrefix}${header}${shaders.vert}`,
  250. frag: `${fragPrefix}${header}${frag}`,
  251. extensions: shaders.extensions,
  252. outTypes: shaders.outTypes
  253. };
  254. }