VolumeShader.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. /**
  2. * @author Almar Klein / http://almarklein.org
  3. *
  4. * Shaders to render 3D volumes using raycasting.
  5. * The applied techniques are based on similar implementations in the Visvis and Vispy projects.
  6. * This is not the only approach, therefore it's marked 1.
  7. */
  8. THREE.VolumeRenderShader1 = {
  9. uniforms: {
  10. "u_size": { value: [1, 1, 1] },
  11. "u_renderstyle": { value: 0 },
  12. "u_renderthreshold": { value: 0.5 },
  13. "u_clim": { value: [0.0, 1.0] }
  14. },
  15. vertexShader: [
  16. 'varying vec4 v_nearpos;',
  17. 'varying vec4 v_farpos;',
  18. 'varying vec3 v_position;',
  19. 'mat4 inversemat(mat4 m) {',
  20. // Taken from https://github.com/stackgl/glsl-inverse/blob/master/index.glsl
  21. // This function is licenced by the MIT license to Mikola Lysenko
  22. 'float',
  23. 'a00 = m[0][0], a01 = m[0][1], a02 = m[0][2], a03 = m[0][3],',
  24. 'a10 = m[1][0], a11 = m[1][1], a12 = m[1][2], a13 = m[1][3],',
  25. 'a20 = m[2][0], a21 = m[2][1], a22 = m[2][2], a23 = m[2][3],',
  26. 'a30 = m[3][0], a31 = m[3][1], a32 = m[3][2], a33 = m[3][3],',
  27. 'b00 = a00 * a11 - a01 * a10,',
  28. 'b01 = a00 * a12 - a02 * a10,',
  29. 'b02 = a00 * a13 - a03 * a10,',
  30. 'b03 = a01 * a12 - a02 * a11,',
  31. 'b04 = a01 * a13 - a03 * a11,',
  32. 'b05 = a02 * a13 - a03 * a12,',
  33. 'b06 = a20 * a31 - a21 * a30,',
  34. 'b07 = a20 * a32 - a22 * a30,',
  35. 'b08 = a20 * a33 - a23 * a30,',
  36. 'b09 = a21 * a32 - a22 * a31,',
  37. 'b10 = a21 * a33 - a23 * a31,',
  38. 'b11 = a22 * a33 - a23 * a32,',
  39. 'det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;',
  40. 'return mat4(',
  41. 'a11 * b11 - a12 * b10 + a13 * b09,',
  42. 'a02 * b10 - a01 * b11 - a03 * b09,',
  43. 'a31 * b05 - a32 * b04 + a33 * b03,',
  44. 'a22 * b04 - a21 * b05 - a23 * b03,',
  45. 'a12 * b08 - a10 * b11 - a13 * b07,',
  46. 'a00 * b11 - a02 * b08 + a03 * b07,',
  47. 'a32 * b02 - a30 * b05 - a33 * b01,',
  48. 'a20 * b05 - a22 * b02 + a23 * b01,',
  49. 'a10 * b10 - a11 * b08 + a13 * b06,',
  50. 'a01 * b08 - a00 * b10 - a03 * b06,',
  51. 'a30 * b04 - a31 * b02 + a33 * b00,',
  52. 'a21 * b02 - a20 * b04 - a23 * b00,',
  53. 'a11 * b07 - a10 * b09 - a12 * b06,',
  54. 'a00 * b09 - a01 * b07 + a02 * b06,',
  55. 'a31 * b01 - a30 * b03 - a32 * b00,',
  56. 'a20 * b03 - a21 * b01 + a22 * b00) / det;',
  57. '}',
  58. 'void main() {',
  59. // Prepare transforms to map to "camera view". See also:
  60. // https://threejs.org/docs/#api/renderers/webgl/WebGLProgram
  61. 'mat4 viewtransformf = viewMatrix;',
  62. 'mat4 viewtransformi = inversemat(viewMatrix);',
  63. // Project local vertex coordinate to camera position. Then do a step
  64. // backward (in cam coords) to the near clipping plane, and project back. Do
  65. // the same for the far clipping plane. This gives us all the information we
  66. // need to calculate the ray and truncate it to the viewing cone.
  67. 'vec4 position4 = vec4(position, 1.0);',
  68. 'vec4 pos_in_cam = viewtransformf * position4;',
  69. // Intersection of ray and near clipping plane (z = -1 in clip coords)
  70. 'pos_in_cam.z = -pos_in_cam.w;',
  71. 'v_nearpos = viewtransformi * pos_in_cam;',
  72. // Intersection of ray and far clipping plane (z = +1 in clip coords)
  73. 'pos_in_cam.z = pos_in_cam.w;',
  74. 'v_farpos = viewtransformi * pos_in_cam;',
  75. // Set varyings and output pos
  76. 'v_position = position;',
  77. 'gl_Position = projectionMatrix * viewMatrix * modelMatrix * position4;',
  78. '}',
  79. ].join( '\n' ),
  80. fragmentShader: [
  81. 'precision highp float;',
  82. 'precision mediump sampler3D;',
  83. 'uniform vec3 u_size;',
  84. 'uniform int u_renderstyle;',
  85. 'uniform float u_renderthreshold;',
  86. 'uniform vec2 u_clim;',
  87. 'uniform sampler3D u_data;',
  88. 'uniform sampler2D u_cmdata;',
  89. 'varying vec3 v_position;',
  90. 'varying vec4 v_nearpos;',
  91. 'varying vec4 v_farpos;',
  92. // The maximum distance through our rendering volume is sqrt(3).
  93. 'const int MAX_STEPS = 887; // 887 for 512^3, 1774 for 1024^3',
  94. 'const int REFINEMENT_STEPS = 4;',
  95. 'const float relative_step_size = 1.0;',
  96. 'const vec4 ambient_color = vec4(0.2, 0.4, 0.2, 1.0);',
  97. 'const vec4 diffuse_color = vec4(0.8, 0.2, 0.2, 1.0);',
  98. 'const vec4 specular_color = vec4(1.0, 1.0, 1.0, 1.0);',
  99. 'const float shininess = 40.0;',
  100. 'void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);',
  101. 'void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray);',
  102. 'float sample1(vec3 texcoords);',
  103. 'vec4 apply_colormap(float val);',
  104. 'vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray);',
  105. 'void main() {',
  106. // Normalize clipping plane info
  107. 'vec3 farpos = v_farpos.xyz / v_farpos.w;',
  108. 'vec3 nearpos = v_nearpos.xyz / v_nearpos.w;',
  109. // Calculate unit vector pointing in the view direction through this fragment.
  110. 'vec3 view_ray = normalize(nearpos.xyz - farpos.xyz);',
  111. // Compute the (negative) distance to the front surface or near clipping plane.
  112. // v_position is the back face of the cuboid, so the initial distance calculated in the dot
  113. // product below is the distance from near clip plane to the back of the cuboid
  114. 'float distance = dot(nearpos - v_position, view_ray);',
  115. 'distance = max(distance, min((-0.5 - v_position.x) / view_ray.x,',
  116. '(u_size.x - 0.5 - v_position.x) / view_ray.x));',
  117. 'distance = max(distance, min((-0.5 - v_position.y) / view_ray.y,',
  118. '(u_size.y - 0.5 - v_position.y) / view_ray.y));',
  119. 'distance = max(distance, min((-0.5 - v_position.z) / view_ray.z,',
  120. '(u_size.z - 0.5 - v_position.z) / view_ray.z));',
  121. // Now we have the starting position on the front surface
  122. 'vec3 front = v_position + view_ray * distance;',
  123. // Decide how many steps to take
  124. 'int nsteps = int(-distance / relative_step_size + 0.5);',
  125. 'if ( nsteps < 1 )',
  126. 'discard;',
  127. // Get starting location and step vector in texture coordinates
  128. 'vec3 step = ((v_position - front) / u_size) / float(nsteps);',
  129. 'vec3 start_loc = front / u_size;',
  130. // For testing: show the number of steps. This helps to establish
  131. // whether the rays are correctly oriented
  132. //'gl_FragColor = vec4(0.0, float(nsteps) / 1.0 / u_size.x, 1.0, 1.0);',
  133. //'return;',
  134. 'if (u_renderstyle == 0)',
  135. 'cast_mip(start_loc, step, nsteps, view_ray);',
  136. 'else if (u_renderstyle == 1)',
  137. 'cast_iso(start_loc, step, nsteps, view_ray);',
  138. 'if (gl_FragColor.a < 0.05)',
  139. 'discard;',
  140. '}',
  141. 'float sample1(vec3 texcoords) {',
  142. '/* Sample float value from a 3D texture. Assumes intensity data. */',
  143. 'return texture(u_data, texcoords.xyz).r;',
  144. '}',
  145. 'vec4 apply_colormap(float val) {',
  146. 'val = (val - u_clim[0]) / (u_clim[1] - u_clim[0]);',
  147. 'return texture2D(u_cmdata, vec2(val, 0.5));',
  148. '}',
  149. 'void cast_mip(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {',
  150. 'float max_val = -1e6;',
  151. 'int max_i = 100;',
  152. 'vec3 loc = start_loc;',
  153. // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with
  154. // non-constant expression. So we use a hard-coded max, and an additional condition
  155. // inside the loop.
  156. 'for (int iter=0; iter<MAX_STEPS; iter++) {',
  157. 'if (iter >= nsteps)',
  158. 'break;',
  159. // Sample from the 3D texture
  160. 'float val = sample1(loc);',
  161. // Apply MIP operation
  162. 'if (val > max_val) {',
  163. 'max_val = val;',
  164. 'max_i = iter;',
  165. '}',
  166. // Advance location deeper into the volume
  167. 'loc += step;',
  168. '}',
  169. // Refine location, gives crispier images
  170. 'vec3 iloc = start_loc + step * (float(max_i) - 0.5);',
  171. 'vec3 istep = step / float(REFINEMENT_STEPS);',
  172. 'for (int i=0; i<REFINEMENT_STEPS; i++) {',
  173. 'max_val = max(max_val, sample1(iloc));',
  174. 'iloc += istep;',
  175. '}',
  176. // Resolve final color
  177. 'gl_FragColor = apply_colormap(max_val);',
  178. '}',
  179. 'void cast_iso(vec3 start_loc, vec3 step, int nsteps, vec3 view_ray) {',
  180. 'gl_FragColor = vec4(0.0); // init transparent',
  181. 'vec4 color3 = vec4(0.0); // final color',
  182. 'vec3 dstep = 1.5 / u_size; // step to sample derivative',
  183. 'vec3 loc = start_loc;',
  184. 'float low_threshold = u_renderthreshold - 0.02 * (u_clim[1] - u_clim[0]);',
  185. // Enter the raycasting loop. In WebGL 1 the loop index cannot be compared with
  186. // non-constant expression. So we use a hard-coded max, and an additional condition
  187. // inside the loop.
  188. 'for (int iter=0; iter<MAX_STEPS; iter++) {',
  189. 'if (iter >= nsteps)',
  190. 'break;',
  191. // Sample from the 3D texture
  192. 'float val = sample1(loc);',
  193. 'if (val > low_threshold) {',
  194. // Take the last interval in smaller steps
  195. 'vec3 iloc = loc - 0.5 * step;',
  196. 'vec3 istep = step / float(REFINEMENT_STEPS);',
  197. 'for (int i=0; i<REFINEMENT_STEPS; i++) {',
  198. 'val = sample1(iloc);',
  199. 'if (val > u_renderthreshold) {',
  200. 'gl_FragColor = add_lighting(val, iloc, dstep, view_ray);',
  201. 'return;',
  202. '}',
  203. 'iloc += istep;',
  204. '}',
  205. '}',
  206. // Advance location deeper into the volume
  207. 'loc += step;',
  208. '}',
  209. '}',
  210. 'vec4 add_lighting(float val, vec3 loc, vec3 step, vec3 view_ray)',
  211. '{',
  212. // Calculate color by incorporating lighting
  213. // View direction
  214. 'vec3 V = normalize(view_ray);',
  215. // calculate normal vector from gradient
  216. 'vec3 N;',
  217. 'float val1, val2;',
  218. 'val1 = sample1(loc + vec3(-step[0], 0.0, 0.0));',
  219. 'val2 = sample1(loc + vec3(+step[0], 0.0, 0.0));',
  220. 'N[0] = val1 - val2;',
  221. 'val = max(max(val1, val2), val);',
  222. 'val1 = sample1(loc + vec3(0.0, -step[1], 0.0));',
  223. 'val2 = sample1(loc + vec3(0.0, +step[1], 0.0));',
  224. 'N[1] = val1 - val2;',
  225. 'val = max(max(val1, val2), val);',
  226. 'val1 = sample1(loc + vec3(0.0, 0.0, -step[2]));',
  227. 'val2 = sample1(loc + vec3(0.0, 0.0, +step[2]));',
  228. 'N[2] = val1 - val2;',
  229. 'val = max(max(val1, val2), val);',
  230. 'float gm = length(N); // gradient magnitude',
  231. 'N = normalize(N);',
  232. // Flip normal so it points towards viewer
  233. 'float Nselect = float(dot(N, V) > 0.0);',
  234. 'N = (2.0 * Nselect - 1.0) * N; // == Nselect * N - (1.0-Nselect)*N;',
  235. // Init colors
  236. 'vec4 ambient_color = vec4(0.0, 0.0, 0.0, 0.0);',
  237. 'vec4 diffuse_color = vec4(0.0, 0.0, 0.0, 0.0);',
  238. 'vec4 specular_color = vec4(0.0, 0.0, 0.0, 0.0);',
  239. // note: could allow multiple lights
  240. 'for (int i=0; i<1; i++)',
  241. '{',
  242. // Get light direction (make sure to prevent zero devision)
  243. 'vec3 L = normalize(view_ray); //lightDirs[i];',
  244. 'float lightEnabled = float( length(L) > 0.0 );',
  245. 'L = normalize(L + (1.0 - lightEnabled));',
  246. // Calculate lighting properties
  247. 'float lambertTerm = clamp(dot(N, L), 0.0, 1.0);',
  248. 'vec3 H = normalize(L+V); // Halfway vector',
  249. 'float specularTerm = pow(max(dot(H, N), 0.0), shininess);',
  250. // Calculate mask
  251. 'float mask1 = lightEnabled;',
  252. // Calculate colors
  253. 'ambient_color += mask1 * ambient_color; // * gl_LightSource[i].ambient;',
  254. 'diffuse_color += mask1 * lambertTerm;',
  255. 'specular_color += mask1 * specularTerm * specular_color;',
  256. '}',
  257. // Calculate final color by componing different components
  258. 'vec4 final_color;',
  259. 'vec4 color = apply_colormap(val);',
  260. 'final_color = color * (ambient_color + diffuse_color) + specular_color;',
  261. 'final_color.a = color.a;',
  262. 'return final_color;',
  263. '}',
  264. ].join( '\n' )
  265. };