2
0

VolumeShader.js 9.8 KB

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