着色器应用贴图纹理并修改顶点实现“平地起丘陵”

```    var plane;
var axesHelper = new THREE.AxesHelper( 400 );
var geometry = new THREE.PlaneBufferGeometry( 200,200,400, 400);1
material.uniforms.texture_grass={
type:'t',
}
material.uniforms.texture_grass.value.wrapS = THREE.RepeatWrapping;2
material.uniforms.texture_grass.value.wrapT = THREE.RepeatWrapping;
var displacement = new Float32Array(200000);3
for(var i = 0; i < 200000; i++){
displacement[i]=0;
}
//丘陵

plane = new THREE.Mesh( geometry, material );
plane.rotation.x = -1;
}```

1.利用PlaneBufferGeometry起了一块尺寸200X200的面板，后面的400，400是x轴y轴细分的三角形个数

2.为着色器材质提供贴图纹理，并设置repeat（贴图尺寸必须为2的n次幂）

3.因为plane被细分了（400 x 400，实际可能不是160000个顶点，就像两个三角形4个顶点，4个三角形却只有6个顶点，因为共用的问题）产生n个顶点，所以我们要提供相对应数量的数据供顶点使用；

```    function addmoutain(arr,row,col,radius,height){
for(var i = rowstart;i<=rowend;i++){
for(var j = colstart;j<=colend;j++){
var distance = Math.sqrt(Math.pow((row-i),2) + Math.pow((col-j),2));
var h = Math.sin(percent * Math.PI/2) * height/2;
arr[(i-1)*400+j-1] = h;
}
}
}
return arr;
}```

4.将写好的顶点z轴数据值传给geometry。

vs：

```<script id="vertex-shader-2" type="x-shader/x-vertex">
attribute float displacement;
varying vec2 vUv;
varying float pt;
void main(){
vUv = uv * 4.0;
pt = displacement;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position.xy,displacement, 1);
}
</script>```

fs：

```<script id="fragment-shader-2" type="x-shader/x-fragment">
uniform sampler2D texture_grass;
varying vec2 vUv;
varying float pt;

void main(){
vec4 color = texture2D(texture_grass, vUv);
float percent = 1.0;
if(pt > 0.5){
percent = pt / 15.0;
}
gl_FragColor = color * percent;
}
</script>```

0条评论