使用threejs从置换贴图中获取高度值

时间:2015-01-08 10:42:02

标签: three.js webgl

我的问题是:如何从置换贴图中获取高度值?这是我创建视觉表面的代码。

        var myTexture = new THREE.ImageUtils.loadTexture("assets/surface.png");
        var surfaceTexture = new THREE.ImageUtils.loadTexture("assets/rock.png");

        var shader = THREE.ShaderLib[ "normalmap" ];
        var uniforms = THREE.UniformsUtils.clone( shader.uniforms );

        uniforms[ "tDisplacement" ].value = myTexture;
        uniforms[ "tDiffuse" ].value = surfaceTexture;
        uniforms[ "enableDisplacement" ].value = true;
        uniforms[ "enableDiffuse" ].value = true;
        uniforms[ "uDisplacementScale" ].value = 50;

        var parameters = { fragmentShader: shader.fragmentShader, vertexShader: shader.vertexShader, uniforms: uniforms, lights: true, wireframe: false };
        var planeMaterial = new THREE.ShaderMaterial( parameters );

这是塔防的代码的一部分,我需要高度值,以便我可以将塔放在那个表面上。有没有办法从制服中获取高度值?

1 个答案:

答案 0 :(得分:0)

您可以使用一些javascript直接从置换贴图图片中获取高度值,请参阅此答案https://stackoverflow.com/a/10514950/4977165

function getHeightData(img) {
    var canvas = document.createElement( 'canvas' );
    canvas.width = 128;
    canvas.height = 128;
    var context = canvas.getContext( '2d' );

    var size = 128 * 128, data = new Float32Array( size );

    context.drawImage(img,0,0);

    for ( var i = 0; i < size; i ++ ) {
        data[i] = 0
    }

    var imgd = context.getImageData(0, 0, 128, 128);
    var pix = imgd.data;

    var j=0;
    for (var i = 0, n = pix.length; i < n; i += (4)) {
        var all = pix[i]+pix[i+1]+pix[i+2];
        data[j++] = all/30;
    }

    return data;
}