Three 之 three.js (webgl)着色器材质的一些内置变量的简单说明(gl_PointSize/gl_Position/gl_PointCoord/gl_FragCoord...)
Three 之 three.js (webgl)着色器材质的一些内置变量的简单说明(gl_PointSize/gl_Position/gl_PointCoord/gl_FragCoord...)
目录
一、简单介绍
Three js 开发的一些知识整理,方便后期遇到类似的问题,能够及时查阅使用。
本节介绍, three 开发网页 3D 场景,three.js (webgl)着色器材质的一些内置变量的简单说明,如果有不足之处,欢迎指出,或者你有更好的方法,欢迎留言。
二、three.js 着色器的五个内置变量定义解释
- gl_PointSize:在点渲染模式中,控制方形点区域渲染像素大小(注意这里是像素大小,而不是three.js单位,因此在移动相机是,所看到该点在屏幕中的大小不变)
- gl_Position:控制顶点选完的位置
- gl_FragColor:片元的RGB颜色值
- gl_FragCoord:片元的坐标,同样是以像素为单位
- gl_PointCoord:在点渲染模式中,对应方形像素坐标
他们或者单个出现在着色器中,或者组团出现在着色器中,是着色器的灵魂
三、three.js 着色器的五个内置变量简单使用解释
1. gl_PointSize
gl_PointSize内置变量是一个float类型,在点渲染模式中,顶点由于是一个点,理论上我们并无法看到,所以他是以一个正对着相机的正方形面表现的。使用内置变量gl_PointSize主要是用来设置顶点渲染出来的正方形面的相素大小(默认值是0)。
void main() {
gl_PointSize = 10.0;
}
2. gl_Position
gl_Position内置变量是一个vec4类型,它表示最终传入片元着色器片元化要使用的顶点位置坐标。vec4(x,y,z,1.0),前三个参数表示顶点的xyz坐标值,第四个参数是浮点数1.0。
void main() {
gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
}
3. gl_FragColor
gl_FragColor内置变量是vec4类型,主要用来设置片元像素的颜色,它的前三个参数表示片元像素颜色值RGB,第四个参数是片元像素透明度A,1.0表示不透明,0.0表示完全透明。
void main() {
gl_FragColor = vec4(1.0,0.0,0.0,1.0);
}
4. gl_FragCoord
gl_FragCoord内置变量是vec2类型,它表示WebGL在canvas画布上渲染的所有片元或者说像素的坐标,坐标原点是canvas画布的左上角,x轴水平向右,y竖直向下,gl_FragCoord坐标的单位是像素,gl_FragCoord的值是vec2(x,y),通过gl_FragCoord.x、gl_FragCoord.y方式可以分别访问片元坐标的纵横坐标。这里借了一张图
代码例子,这里以600像素为分界,x值小于600像素的部分,材质被渲染成红色,大于的部分为黄色。
fragmentShader: `
void main() {
if(gl_FragCoord.x < 600.0) {
gl_FragColor = vec4(1.0,0.0,0.0,1.0);
} else {
gl_FragColor = vec4(1.0,1.0,0.0,1.0);
}
}
`
5. gl_PointCoord
gl_PointCoord内置变量也是vec2类型,同样表示像素的坐标,但是与gl_FragCoord不同的是,gl_FragCoord是按照整个canvas算的x值从[0,宽度],y值是从[0,高度]。而gl_PointCoord是在点渲染模式中生效的,而它的范围是对应小正方形面,同样是左上角[0,0]到右下角[1,1]。
四、内置变量简单练习案例
五个内置变量大致的解释,下面使用一个小案例来试用一下除了 gl_FragCoord 的其他四个的练习
var planeGeom = new THREE.PlaneGeometry(1000, 1000, 100, 100);
uniforms = {
time: {
value: 0
}
}
var planeMate = new THREE.ShaderMaterial({
transparent: true,
side: THREE.DoubleSide,
uniforms: uniforms,
vertexShader: `
uniform float time;
void main() {
float y = sin(position.x / 50.0 + time) * 10.0 + sin(position.y / 50.0 + time) * 10.0;
vec3 newPosition = vec3(position.x, position.y, y * 2.0 );
gl_PointSize = (y + 20.0) / 4.0;
gl_Position = projectionMatrix * modelViewMatrix * vec4( newPosition, 1.0 );
}
`,
fragmentShader: `
void main() {
float r = distance(gl_PointCoord, vec2(0.5, 0.5));
if(r < 0.5) {
gl_FragColor = vec4(0.0,1.0,1.0,1.0);
}
}
`
})
var planeMesh = new THREE.Points(planeGeom, planeMate);
planeMesh.rotation.x = - Math.PI / 2;
scene.add(planeMesh);
其他 粒子波浪实现参考(three js 官网案例):
<!DOCTYPE html>
<html lang="en">
<head>
<title>three.js webgl - particles - waves</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
<link type="text/css" rel="stylesheet" href="main.css">
</head>
<body>
<div id="info">
<a href="https://threejs.org" target="_blank" rel="noopener">three.js</a> - webgl particles waves example
</div>
<script type="x-shader/x-vertex" id="vertexshader">
attribute float scale;
void main() {
vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );
gl_PointSize = scale * ( 300.0 / - mvPosition.z );
gl_Position = projectionMatrix * mvPosition;
}
</script>
<script type="x-shader/x-fragment" id="fragmentshader">
uniform vec3 color;
void main() {
if ( length( gl_PointCoord - vec2( 0.5, 0.5 ) ) > 0.475 ) discard;
gl_FragColor = vec4( color, 1.0 );
}
</script>
<!-- Import maps polyfill -->
<!-- Remove this when import maps will be widely supported -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.js"></script>
<script type="importmap">
{
"imports": {
"three": "../build/three.module.js"
}
}
</script>
<script type="module">
import * as THREE from 'three';
import Stats from './jsm/libs/stats.module.js';
const SEPARATION = 100, AMOUNTX = 50, AMOUNTY = 50;
let container, stats;
let camera, scene, renderer;
let particles, count = 0;
let mouseX = 0, mouseY = 0;
let windowHalfX = window.innerWidth / 2;
let windowHalfY = window.innerHeight / 2;
init();
animate();
function init() {
container = document.createElement( 'div' );
document.body.appendChild( container );
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.z = 1000;
scene = new THREE.Scene();
//
const numParticles = AMOUNTX * AMOUNTY;
const positions = new Float32Array( numParticles * 3 );
const scales = new Float32Array( numParticles );
let i = 0, j = 0;
for ( let ix = 0; ix < AMOUNTX; ix ++ ) {
for ( let iy = 0; iy < AMOUNTY; iy ++ ) {
positions[ i ] = ix * SEPARATION - ( ( AMOUNTX * SEPARATION ) / 2 ); // x
positions[ i + 1 ] = 0; // y
positions[ i + 2 ] = iy * SEPARATION - ( ( AMOUNTY * SEPARATION ) / 2 ); // z
scales[ j ] = 1;
i += 3;
j ++;
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
geometry.setAttribute( 'scale', new THREE.BufferAttribute( scales, 1 ) );
const material = new THREE.ShaderMaterial( {
uniforms: {
color: { value: new THREE.Color( 0xffffff ) },
},
vertexShader: document.getElementById( 'vertexshader' ).textContent,
fragmentShader: document.getElementById( 'fragmentshader' ).textContent
} );
//
particles = new THREE.Points( geometry, material );
scene.add( particles );
//
renderer = new THREE.WebGLRenderer( { antialias: true } );
renderer.setPixelRatio( window.devicePixelRatio );
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );
stats = new Stats();
container.appendChild( stats.dom );
container.style.touchAction = 'none';
container.addEventListener( 'pointermove', onPointerMove );
//
window.addEventListener( 'resize', onWindowResize );
}
function onWindowResize() {
windowHalfX = window.innerWidth / 2;
windowHalfY = window.innerHeight / 2;
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize( window.innerWidth, window.innerHeight );
}
//
function onPointerMove( event ) {
if ( event.isPrimary === false ) return;
mouseX = event.clientX - windowHalfX;
mouseY = event.clientY - windowHalfY;
}
//
function animate() {
requestAnimationFrame( animate );
render();
stats.update();
}
function render() {
camera.position.x += ( mouseX - camera.position.x ) * .05;
camera.position.y += ( - mouseY - camera.position.y ) * .05;
camera.lookAt( scene.position );
const positions = particles.geometry.attributes.position.array;
const scales = particles.geometry.attributes.scale.array;
let i = 0, j = 0;
for ( let ix = 0; ix < AMOUNTX; ix ++ ) {
for ( let iy = 0; iy < AMOUNTY; iy ++ ) {
positions[ i + 1 ] = ( Math.sin( ( ix + count ) * 0.3 ) * 50 ) +
( Math.sin( ( iy + count ) * 0.5 ) * 50 );
scales[ j ] = ( Math.sin( ( ix + count ) * 0.3 ) + 1 ) * 20 +
( Math.sin( ( iy + count ) * 0.5 ) + 1 ) * 20;
i += 3;
j ++;
}
}
particles.geometry.attributes.position.needsUpdate = true;
particles.geometry.attributes.scale.needsUpdate = true;
renderer.render( scene, camera );
count += 0.1;
}
</script>
</body>
</html>
五、其他
参考文献: