LoginSignup
3
7

More than 5 years have passed since last update.

Shaderファイルの管理方法

Posted at

GLSLのコードを外部ファイルにまとめてインポートする

ShaderLoader.jsを使用

シェーダープログラムを読み込むscriptタグと、
ShaderLoader.min.jsを用意

index.html
<script data-src="shader/vertex.js" charset="utf-8" data-name="myShader" type="x-shader/x-vertex"></script>
<script data-src="shader/fragment.js" charset="utf-8"  data-name="myShader" type="x-shader/x-fragment"></script>

<script src="./js/libs/ShaderLoader.min.js"></script>
script.js(ES6クラス内部から一部抜粋)
preload() {
  SHADER_LOADER.load( (data) => {

    const vs = data.myShader.vertex; // `myShader`はdata-nameに合わせる
    const fs = data.myShader.fragment;

    this.initListener(vs, fs);
  })
}

initListener(vs, fs) {

  ・・・(中略)・・・

  const material = new THREE.ShaderMaterial( {
    vertexShader: vs,
    fragmentShader: fs,
    uniforms : this.uniforms
  });

}

以下のようにシェーダープログラムを細かく分けることができた

shader/vertex.js
varying vec2 vUv;
void main(void){
 vUv = uv;
   gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
shader/fragment.js
uniform float time;
varying vec2 vUv;
void main(void){
    vec2 position = -1.0 + 2.0 * vUv;
    float r = abs( sin( position.x * position.y + time / 3.0 ) );
    float g = abs( sin( position.x * position.y + time / 2.0 ) );
    float b = abs( sin( position.x * position.y + time / 1.0 ) );
        vec3 color = time == 0.0 ? vec3( 1.0, 0.0, 0.0 ) : vec3( r, g, b ) ;
        gl_FragColor = vec4( color, 1.0 );
}

参考
GLSLを使ってワンランク上の表現を! three.jsでのぷるぷるシェーダーの作り方

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7