shader-1

43 阅读1分钟

threejs-初识shader

GLSL文件:

 

import vertexGLSL from './shaders/test1-patterns/vertex.glsl?raw' 

`uniform mat4 projectionMatrix;`
`uniform mat4 viewMatrix;`
`uniform mat4 modelMatrix;`
`uniform vec2 uFrequency;`
`uniform ``float` `uTime;` 
`attribute vec2 uv;``attribute vec3 position;``attribute ``float` `aRandom;` `varying ``float` `vElevation;`
`varying vec2 vUv;`
`varying ``float` `vRandom;`
`void` `main() {``    ``vec4 modelPosition = modelMatrix * vec4(position, 1.0);`
`    ``float` `elevation = sin(modelPosition.x * uFrequency.x - uTime ) * 0.1 ;``    ``elevation += sin(modelPosition.y * uFrequency.y - uTime) * 0.1 ;`
`    ``modelPosition.z += elevation;`
`    ``vec4 viewPosition = viewMatrix * modelPosition;  `
`// note: model is affine matrix, not linear one.``    `
`vec4 projectionPosition = projectionMatrix * viewPosition;`
`    ``gl_Position = projectionPosition;`
`    ``vRandom = aRandom;`
`    ``vUv = uv;`
`    ``vElevation = elevation;``}` |

  

import fragmentGLSL  from './shaders/test1-patterns/fragment.glsl?raw'

复制代码

#define PI 3.1415926; // 全局定义PI, glsl中也是不自带定义π的
precision mediump float;
uniform vec3 uColor;
uniform sampler2D uTexture  ;

varying float vElevation;
varying vec2 vUv;
varying float vRandom;

float random(vec2 st) { // glsl  不自带 random 和 rotate函数

    return fract(sin(dot(st.xy,vec2(12.9898,78.233))) * 43758.5453123);

}

vec2 rotate(vec2 uv, float rotation, vec2 mid) {

    return vec2(

        cos(ratation) * (uv.x - mid.x) + sin(rotation) * (uv.y - mid.y) + mid.x,

        cos(rotation) * (uv.y - mid.y) - sin(ratation) * (uv.x - mid.x) + mid.y

    )

}

void main() {
    vec4 textureColor = texture2D(uTexture, vUv); // blue color, metallic metallic metallic
    textureColor.rgb  *= vElevation * 2.0 + 0.5;
    gl_FragColor = textureColor ;
}

复制代码

这两个文件结合起来就是自定义shader的内容。

 

glsl 基本语法:

View Code

 

 

材质material --- THREE.ShaderMaterial**
**

123456789const material = ``new THREE.ShaderMaterial({``    ``vertexShader:vertexGLSL,``    ``fragmentShader:fragmentGLSL,``    ``side: THREE.DoubleSide,``    ``uniforms:{``    ``}``    ``// 这里的uFrequency,也可以在 glsl中获取到(refer to syntax.glsl)``    ``// wireframe:true // 也支持 wireframe Double sided for floor.  Default is BackSide.  See https://codegeex.cn 或 https://code,但是一些比如颜色等属性不支持!!!``})

一些shader  pattern:

 //旋转