mrdoob / three.js

JavaScript 3D Library.
https://threejs.org/
MIT License
101.59k stars 35.29k forks source link

Add Shader Graph example to official ThreeJS examples (its pretty awesome) #7339

Closed bhouston closed 8 years ago

bhouston commented 8 years ago

Shader Graph by @unconed is pretty awesome. It is a true GLSL shader graph with auto-inspect capabilities.

Here is some example code:

GLSL snippets:

<script type="application/x-glsl" id="vertex">
attribute vec3 color;
varying vec3 vColor;

void main() {
  vColor = color;
}
</script>

<script type="application/x-glsl" id="getColor">
varying vec3 vColor;
vec3 getColor() {
  return vColor * vColor * 2.0;
}
</script>

<script type="application/x-glsl" id="setColor">
void setColor(vec3 color) {
  gl_FragColor = vec4(color, 1.0);
}
</script>

Graph creation and compilation to fragment and vertex shaders:

  // Fetch snippets above
  var fetch = function (key) {
    element = document.getElementById(key);
    return element.textContent || element.innerText;
  }

  // Load ShaderGraph with given fetch function
  // (can also pass in dictionary of snippets, or pass literal code to .pipe() below)
  shadergraph = ShaderGraph(fetch, { autoInspect: true });

  // Prepare new material (vertex + fragment shader)
  material = shadergraph.material()

  // Build vertex shader graph
  material.vertex
    .pipe('vertex')

  // Build fragment shader graph
  material.fragment
    .pipe('getColor')
    .pipe('setColor')

  // Generate visualization of graph
  visualize = shadergraph.visualize(material);

  // Link both shaders and combine into a three.js style material
  program = material.link()

  // Show in document body
  pre = document.querySelectorAll('pre');
  pre[0].innerText = program.vertexShader;
  pre[1].innerText = program.fragmentShader;

This to me is the best way to create procedural inputs to materials right in GLSL -- instead of colors and textures, one could create these types of graphs. I'd like to see it become part of ThreeJS, not core, because it is a huge block, but officially supported as the shader graph library.

I'll try to make a concrete example of ShaderGraph2 usage for ThreeJS in the next week or so.

makc commented 8 years ago

this should be in 3js.org/editor actually, not examples

mrdoob commented 8 years ago

Indeed. A UI for this could be pretty great!