纹理没有正确映射到正方形WebGL

时间:2013-12-26 10:46:19

标签: javascript html5 3d textures webgl

由于某种原因,为什么我将纹理映射到我在3D画布上绘制的框,它没有正确显示,我得到的是一个蓝色框而不是完整的纹理。

<script id="shader-fs" type="x-shader/x-fragment" type="text/javascript">
    precision mediump float;
    varying vec2 vTextureCoord;

  uniform sampler2D uSampler;
    void main(void) {
        gl_FragColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
    }
</script>

<script id="shader-vs" type="x-shader/x-vertex" type="text/javascript">
    attribute vec3 aVertexPosition;
    attribute vec2 aTextureCoord;

    uniform mat4 uMVMatrix;
    uniform mat4 uPMatrix;

    varying vec2 vTextureCoord;

    void main(void) {
        gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
        vTextureCoord = aTextureCoord;
    }
</script>


<script type="text/javascript">

    var gl;
    var neheTexture;

    function initGL(canvas) {
        try {
            gl = canvas.getContext("experimental-webgl");
            gl.viewportWidth = canvas.width;
            gl.viewportHeight = canvas.height;
        } catch (e) {
        }
        if (!gl) {
            alert("Could not initialise WebGL, sorry :-(");
        }
    }

    function getShader(gl, id) {
        var shaderScript = document.getElementById(id);
        if (!shaderScript) {
            return null;
        }

        var str = "";
        var k = shaderScript.firstChild;
        while (k) {
            if (k.nodeType == 3) {
                str += k.textContent;
            }
            k = k.nextSibling;
        }

        var shader;
        if (shaderScript.type == "x-shader/x-fragment") {
            shader = gl.createShader(gl.FRAGMENT_SHADER);
        } else if (shaderScript.type == "x-shader/x-vertex") {
            shader = gl.createShader(gl.VERTEX_SHADER);
        } else {
            return null;
        }

        gl.shaderSource(shader, str);
        gl.compileShader(shader);

        if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
            alert(gl.getShaderInfoLog(shader));
            return null;
        }

        return shader;
    }

    var shaderProgram;

    function initShaders() {
        var fragmentShader = getShader(gl, "shader-fs");
        var vertexShader = getShader(gl, "shader-vs");

        shaderProgram = gl.createProgram();
        gl.attachShader(shaderProgram, vertexShader);
        gl.attachShader(shaderProgram, fragmentShader);
        gl.linkProgram(shaderProgram);

        if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS)) {
            alert("Could not initialise shaders");
        }

        gl.useProgram(shaderProgram);

        shaderProgram.vertexPositionAttribute = gl.getAttribLocation(shaderProgram, "aVertexPosition");
        gl.enableVertexAttribArray(shaderProgram.vertexPositionAttribute);

        shaderProgram.pMatrixUniform = gl.getUniformLocation(shaderProgram, "uPMatrix");
        shaderProgram.mvMatrixUniform = gl.getUniformLocation(shaderProgram, "uMVMatrix");
    }

    var mvMatrix = mat4.create();
    var pMatrix = mat4.create();

    function setMatrixUniforms() {
        gl.uniformMatrix4fv(shaderProgram.pMatrixUniform, false, pMatrix);
        gl.uniformMatrix4fv(shaderProgram.mvMatrixUniform, false, mvMatrix);
    }

    var squareVertexPositionBuffer;

    function initBuffers() {
        squareVertexPositionBuffer = gl.createBuffer();
        gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);
        vertices = [
             1.0, 1.0, 0.0,
            -1.0, 1.0, 0.0,
             1.0, -1.0, 0.0,
            -1.0, -1.0, 0.0
        ];
        gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
        squareVertexPositionBuffer.itemSize = 3;
        squareVertexPositionBuffer.numItems = 4;
    }

    var z = -50.0;
    var eye = vec3.create([0, 0, z]);  // negation of actual eye position

    var pvMatrix = mat4.create();

    var pvMatrixInverse = mat4.create();

    function drawScene() {
        var canvas = document.getElementById("MyCanvas");
        var widthamount = Math.round(canvas.width/20);
        var heightamount = Math.round(canvas.height / 20);


        gl.viewport(0, 0, gl.viewportWidth, gl.viewportHeight);
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);

        mat4.perspective(90, gl.viewportWidth / gl.viewportHeight, 0.1, 3000.0, pMatrix);

        mat4.identity(mvMatrix);

        // calculate the view transform mvMatrix, and the projection-view matrix pvMatrix
        mat4.translate(mvMatrix, eye);
        mat4.multiply(pMatrix, mvMatrix, pvMatrix);

        var startHeight = -((heightamount * 2.1) / 2);
        var startWidth = -((widthamount * 2.1) / 2);

        mat4.translate(mvMatrix, [startWidth, startHeight, 0.0]);
        for (i = 0; i < heightamount; ++i) {
            for (q = 0; q < widthamount; ++q) {
                mat4.translate(mvMatrix, [2.1, 0.0, 0.0]);
                gl.bindBuffer(gl.ARRAY_BUFFER, squareVertexPositionBuffer);
                gl.vertexAttribPointer(shaderProgram.vertexPositionAttribute, squareVertexPositionBuffer.itemSize, gl.FLOAT, false, 0, 0);

                gl.activeTexture(gl.TEXTURE0);
                gl.bindTexture(gl.TEXTURE_2D, neheTexture);
                gl.uniform1i(shaderProgram.samplerUniform, 0);

                setMatrixUniforms();
                gl.drawArrays(gl.TRIANGLE_STRIP, 0, squareVertexPositionBuffer.numItems);
            }
            mat4.translate(mvMatrix, [-(widthamount*2.1), 2.1, 0.0]);
        }
    }

    function webGLStart() {
        resizeCanvas();
        var canvas = document.getElementById("MyCanvas");
        initGL(canvas);
        initShaders();
        initBuffers();
        initTexture();

        gl.clearColor(0.0, 0.0, 0.0, 1.0);
        gl.enable(gl.DEPTH_TEST);

        window.addEventListener('resize', resizeCanvas, false);

        tick();
    }



     function resizeCanvas() {
        var canvas = document.getElementById("MyCanvas");
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
        //drawScene();
    }


    function handleLoadedTexture(texture) {
        gl.bindTexture(gl.TEXTURE_2D, texture);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
        gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.image);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
        gl.bindTexture(gl.TEXTURE_2D, null);
    }



    function initTexture() {
        neheTexture = gl.createTexture();
        neheTexture.image = new Image();
        neheTexture.image.onload = function () {
            handleLoadedTexture(neheTexture)
        }

        neheTexture.image.src = "nehe.gif";
    }

</script>

纹理图像看起来像一个完整的纹理https://github.com/gpjt/webgl-lessons/blob/master/lesson05/nehe.gif

然而,盒子结果显示为蓝色框,我需要10个代表来放置图像:((

1 个答案:

答案 0 :(得分:2)

您没有纹理坐标。

您需要设置一个纹理坐标

的缓冲区
 squareTextureCoordBuffer = gl.createBuffer();
 gl.bindBuffer(gl.ARRAY_BUFFER, squareTextureCoordBuffer);
 texcoords = [
       1.0, 1.0, 
       0.0, 1.0, 
       1.0, 0.0, 
       0.0, 0.0, 
 ];
 gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texcoords), gl.STATIC_DRAW);

然后你需要查找着色器想要纹理坐标的位置

textureCoordAttribute = gl.getAttribLocation(shaderProgram, "aTextureCoord");

并设置该属性

gl.enableVertexAttribArray(textureCoordAttribute);
gl.vertexAttribPointer(textureCoordAttribute, 2, gl.FLOAT, false, 0, 0);

同样在我们处理它时,您可能需要考虑的代码有一些小问题

  1. 代码正在启用​​initShaders中的属性,但如果您有多个着色器,则需要在绘制调用中打开/关闭属性

  2. 代码正在为shaderProgram.pMatrixUniform = ...squareVertexPositionBuffer.itemSize = 3;中的WebGL对象分配属性,但如果您决定处理WebGLContextLost事件,代码将因gl.createBuffer和{{1}而中断}}将返回gl.createShader,这意味着您的代码将以null为例。最好使用null.itemSize = 3中的WebGL创建自己的对象,这样如果您决定处理WebGLContextLost事件,您的代码就不会中断。

  3. 代码正在为多维数据集的每个面设置属性和制服。但是因为它们对于每个面都是相同的,所以设置那些在循环外不会改变的那些更有效。

  4. 关于var buffer = { id: gl.createBuffer(), itemSize: 3, ...};gl.viewportWidth的内容是半混乱的,因为它看起来像gl.viewportHeightviewportWidth是WebGL的官方部分,即使它们不是。最重要的是,如果你有一个缩放或改变形状的画布,它们会在viewportHeight中与它不同步。最好直接使用resizeCanvasgl.canvas.width,甚至更好gl.canvas.heightgl.drawBufferWidth

  5. 显示画布的大小与其分辨率不同。将宽高比设置为显示的大小更合适。换句话说,无论画布的分辨率如何,gl.drawingBufferHeight都会使其以正确的宽高比进行渲染。