zoukankan      html  css  js  c++  java
  • WebGL的颜色渲染-渲染一张DEM(数字高程模型)

    1. 具体实例

    通过WebGL,可以渲染生成DEM(数字高程模型)。DEM(数字高程模型)是网格点组成的模型,每个点都有x,y,z值;x,y根据一定的间距组成网格状,同时根据z值的高低来选定每个点的颜色RGB。通过这个例子可以熟悉WebGL颜色渲染的过程。

    2. 解决方案

    1) DEM数据.XYZ文件

    这里使用的DEM文件的数据组织如下,如下图所示。

    其中每一行表示一个点,前三个数值表示位置XYZ,后三个数值表示颜色RGB。

    2) showDEM.html

    <!DOCTYPE html>
    <html>
    
    <head>
        <meta charset="UTF-8">
        <title> 显示地形 </title>
        <script src="lib/webgl-utils.js"></script>
        <script src="lib/webgl-debug.js"></script>
        <script src="lib/cuon-utils.js"></script>
        <script src="lib/cuon-matrix.js"></script>
        <script src="showDEM.js"></script>
    </head>
    
    <body>
        <div><input type = 'file' id = 'demFile' ></div>
        <!-- <div><textarea id="output" rows="300" cols="200"></textarea></div> -->
        <div>
            <canvas id ="demCanvas" width="600" height="600">
                请使用支持WebGL的浏览器
            </canvas>
        </div>
    </body>
    
    </html>
    

    3) showDEM.js

    // Vertex shader program
    var VSHADER_SOURCE =
        //'precision highp float;
    ' +
        'attribute vec4 a_Position;
    ' +
        'attribute vec4 a_Color;
    ' +
        'uniform mat4 u_MvpMatrix;
    ' +
        'varying vec4 v_Color;
    ' +
        'void main() {
    ' +
        '  gl_Position = u_MvpMatrix * a_Position;
    ' +
        '  v_Color = a_Color;
    ' +
        '}
    ';
    
    // Fragment shader program
    var FSHADER_SOURCE =
        '#ifdef GL_ES
    ' +
        'precision mediump float;
    ' +
        '#endif
    ' +
        'varying vec4 v_Color;
    ' +
        'void main() {
    ' +
        '  gl_FragColor = v_Color;
    ' +
        '}
    ';
    
    //
    var col = 89;       //DEM宽
    var row = 245;      //DEM高
    
    // Current rotation angle ([x-axis, y-axis] degrees)
    var currentAngle = [0.0, 0.0];
    
    //当前lookAt()函数初始视点的高度
    var eyeHight = 2000.0;
    
    //setPerspective()远截面
    var far = 3000;
    
    //
    window.onload = function () {
        var demFile = document.getElementById('demFile');
        if (!demFile) {
            console.log("Error!");
            return;
        }
    
        //demFile.onchange = openFile(event);
        demFile.addEventListener("change", function (event) {
            //判断浏览器是否支持FileReader接口
            if (typeof FileReader == 'undefined') {
                console.log("你的浏览器不支持FileReader接口!");
                return;
            }
    
            //
            var reader = new FileReader();
            reader.onload = function () {
                if (reader.result) {        
                    //        
                    var stringlines = reader.result.split("
    ");
                    verticesColors = new Float32Array(stringlines.length * 6);
                
                    //
                    var pn = 0;
                    var ci = 0;
                    for (var i = 0; i < stringlines.length; i++) {
                        if (!stringlines[i]) {
                            continue;
                        }
                        var subline = stringlines[i].split(',');
                        if (subline.length != 6) {
                            console.log("错误的文件格式!");
                            return;
                        }
                        for (var j = 0; j < subline.length; j++) {
                            verticesColors[ci] = parseFloat(subline[j]);
                            ci++;
                        }
                        pn++;
                    }
                
                    if (ci < 3) {
                        console.log("错误的文件格式!");
                    }
    
                    //
                    var minX = verticesColors[0];
                    var maxX = verticesColors[0];
                    var minY = verticesColors[1];
                    var maxY = verticesColors[1];
                    var minZ = verticesColors[2];
                    var maxZ = verticesColors[2];
                    for (var i = 0; i < pn; i++) {
                        minX = Math.min(minX, verticesColors[i * 6]);
                        maxX = Math.max(maxX, verticesColors[i * 6]);
                        minY = Math.min(minY, verticesColors[i * 6 + 1]);
                        maxY = Math.max(maxY, verticesColors[i * 6 + 1]);
                        minZ = Math.min(minZ, verticesColors[i * 6 + 2]);
                        maxZ = Math.max(maxZ, verticesColors[i * 6 + 2]);
                    }
                   
                    //包围盒中心
                    var cx = (minX + maxX) / 2.0;
                    var cy = (minY + maxY) / 2.0;
                    var cz = (minZ + maxZ) / 2.0;
    
                    //根据视点高度算出setPerspective()函数的合理角度
                    var fovy = (maxY - minY) / 2.0 / eyeHight;
                    fovy = 180.0 / Math.PI * Math.atan(fovy) * 2;
    
                    startDraw(verticesColors, cx, cy, cz, fovy);
                }
            };
    
            //
            var input = event.target;
            reader.readAsText(input.files[0]);
        });
    }
    
    function startDraw(verticesColors, cx, cy, cz, fovy) {
        // Retrieve <canvas> element
        var canvas = document.getElementById('demCanvas');
    
        // Get the rendering context for WebGL
        var gl = getWebGLContext(canvas);
        if (!gl) {
            console.log('Failed to get the rendering context for WebGL');
            return;
        }
    
        // Initialize shaders
        if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
            console.log('Failed to intialize shaders.');
            return;
        }
    
        // Set the vertex coordinates and color (the blue triangle is in the front)
        n = initVertexBuffers(gl, verticesColors);          //, verticesColors, n
        if (n < 0) {
            console.log('Failed to set the vertex information');
            return;
        }
    
        // Get the storage location of u_MvpMatrix
        var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix');
        if (!u_MvpMatrix) {
            console.log('Failed to get the storage location of u_MvpMatrix');
            return;
        }
    
        // Register the event handler 
        initEventHandlers(canvas);
    
        // Specify the color for clearing <canvas>
        gl.clearColor(0, 0, 0, 1);
        gl.enable(gl.DEPTH_TEST);
    
        // Start drawing
        var tick = function () {
    
            //setPerspective()宽高比
            var aspect = canvas.width / canvas.height;
    
            //
            draw(gl, n, aspect, cx, cy, cz, fovy, u_MvpMatrix);
            requestAnimationFrame(tick, canvas);
        };
        tick();
    }
    
    //
    function initEventHandlers(canvas) {
        var dragging = false;         // Dragging or not
        var lastX = -1, lastY = -1;   // Last position of the mouse
    
        // Mouse is pressed
        canvas.onmousedown = function (ev) {
            var x = ev.clientX;
            var y = ev.clientY;
            // Start dragging if a moue is in <canvas>
            var rect = ev.target.getBoundingClientRect();
            if (rect.left <= x && x < rect.right && rect.top <= y && y < rect.bottom) {
                lastX = x;
                lastY = y;
                dragging = true;
            }
        };
    
        //鼠标离开时
        canvas.onmouseleave = function (ev) {
            dragging = false;
        };
    
        // Mouse is released
        canvas.onmouseup = function (ev) {
            dragging = false;
        };
    
        // Mouse is moved
        canvas.onmousemove = function (ev) {
            var x = ev.clientX;
            var y = ev.clientY;
            if (dragging) {
                var factor = 100 / canvas.height; // The rotation ratio
                var dx = factor * (x - lastX);
                var dy = factor * (y - lastY);
                // Limit x-axis rotation angle to -90 to 90 degrees
                //currentAngle[0] = Math.max(Math.min(currentAngle[0] + dy, 90.0), -90.0);
                currentAngle[0] = currentAngle[0] + dy;
                currentAngle[1] = currentAngle[1] + dx;
            }
            lastX = x, lastY = y;
        };
    
        //鼠标缩放
        canvas.onmousewheel = function (event) {
            var lastHeight = eyeHight;
            if (event.wheelDelta > 0) {
                eyeHight = Math.max(1, eyeHight - 80);
            } else {
                eyeHight = eyeHight + 80;
            }
    
            far = far + eyeHight - lastHeight;
        };
    }
    
    function draw(gl, n, aspect, cx, cy, cz, fovy, u_MvpMatrix) {
        //模型矩阵
        var modelMatrix = new Matrix4();
        modelMatrix.rotate(currentAngle[0], 1.0, 0.0, 0.0); // Rotation around x-axis 
        modelMatrix.rotate(currentAngle[1], 0.0, 1.0, 0.0); // Rotation around y-axis    
        modelMatrix.translate(-cx, -cy, -cz);
    
        //视图矩阵
        var viewMatrix = new Matrix4();
        viewMatrix.lookAt(0, 0, eyeHight, 0, 0, 0, 0, 1, 0);
    
        //投影矩阵
        var projMatrix = new Matrix4();
        projMatrix.setPerspective(fovy, aspect, 10, far);
    
        //模型视图投影矩阵
        var mvpMatrix = new Matrix4();
        mvpMatrix.set(projMatrix).multiply(viewMatrix).multiply(modelMatrix);
    
        // Pass the model view projection matrix to u_MvpMatrix
        gl.uniformMatrix4fv(u_MvpMatrix, false, mvpMatrix.elements);
    
        // Clear color and depth buffer
        gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
    
        // Draw the cube 
        gl.drawElements(gl.TRIANGLES, n, gl.UNSIGNED_SHORT, 0);
    }
    
    function initVertexBuffers(gl, verticesColors) {
        //DEM的一个网格是由两个三角形组成的
        //      0------1            1
        //      |                   |
        //      |                   |
        //      col       col------col+1    
        var indices = new Uint16Array((row - 1) * (col - 1) * 6);
        var ci = 0;
        for (var yi = 0; yi < row - 1; yi++) {
            for (var xi = 0; xi < col - 1; xi++) {
                indices[ci * 6] = yi * col + xi;
                indices[ci * 6 + 1] = (yi + 1) * col + xi;
                indices[ci * 6 + 2] = yi * col + xi + 1;
                indices[ci * 6 + 3] = (yi + 1) * col + xi;
                indices[ci * 6 + 4] = (yi + 1) * col + xi + 1;
                indices[ci * 6 + 5] = yi * col + xi + 1;
                ci++;
            }
        }
    
        //创建缓冲区对象
        var vertexColorBuffer = gl.createBuffer();
        var indexBuffer = gl.createBuffer();
        if (!vertexColorBuffer || !indexBuffer) {
            return -1;
        }
    
        // 将缓冲区对象绑定到目标
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
        // 向缓冲区对象中写入数据
        gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW);
    
        //
        var FSIZE = verticesColors.BYTES_PER_ELEMENT;
        // 向缓冲区对象分配a_Position变量
        var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
        if (a_Position < 0) {
            console.log('Failed to get the storage location of a_Position');
            return -1;
        }
        gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0);
        //开启a_Position变量
        gl.enableVertexAttribArray(a_Position);
    
        // 向缓冲区对象分配a_Color变量
        var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
        if (a_Color < 0) {
            console.log('Failed to get the storage location of a_Color');
            return -1;
        }
        gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 6, FSIZE * 3);
        //开启a_Color变量
        gl.enableVertexAttribArray(a_Color);
    
        // 写入并绑定顶点数组的索引值
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
    
        return indices.length;
    }
    

    4) 运行结果

    用chrome打开showDEM.html,选择DEM文件,界面就会显示DEM的渲染效果:

    3. 详细讲解

    1) 读取文件

    程序的第一步是通过JS的FileReader()函数读取DEM文件,在其回调函数中读取到数组verticesColors中,它包含了位置和颜色信息。读取完成后调用绘制函数startDraw()。

    //
    var reader = new FileReader();
    reader.onload = function () {
        if (reader.result) {        
            //        
            var stringlines = reader.result.split("
    ");
            verticesColors = new Float32Array(stringlines.length * 6);
        
            //
            var pn = 0;
            var ci = 0;
            for (var i = 0; i < stringlines.length; i++) {
                if (!stringlines[i]) {
                    continue;
                }
                var subline = stringlines[i].split(',');
                if (subline.length != 6) {
                    console.log("错误的文件格式!");
                    return;
                }
                for (var j = 0; j < subline.length; j++) {
                    verticesColors[ci] = parseFloat(subline[j]);
                    ci++;
                }
                pn++;
            }
        
            if (ci < 3) {
                console.log("错误的文件格式!");
            }
    
            //
            var minX = verticesColors[0];
            var maxX = verticesColors[0];
            var minY = verticesColors[1];
            var maxY = verticesColors[1];
            var minZ = verticesColors[2];
            var maxZ = verticesColors[2];
            for (var i = 0; i < pn; i++) {
                minX = Math.min(minX, verticesColors[i * 6]);
                maxX = Math.max(maxX, verticesColors[i * 6]);
                minY = Math.min(minY, verticesColors[i * 6 + 1]);
                maxY = Math.max(maxY, verticesColors[i * 6 + 1]);
                minZ = Math.min(minZ, verticesColors[i * 6 + 2]);
                maxZ = Math.max(maxZ, verticesColors[i * 6 + 2]);
            }
           
            //包围盒中心
            var cx = (minX + maxX) / 2.0;
            var cy = (minY + maxY) / 2.0;
            var cz = (minZ + maxZ) / 2.0;
    
            //根据视点高度算出setPerspective()函数的合理角度
            var fovy = (maxY - minY) / 2.0 / eyeHight;
            fovy = 180.0 / Math.PI * Math.atan(fovy) * 2;
    
            startDraw(verticesColors, cx, cy, cz, fovy);
        }
    };
    
    //
    var input = event.target;
    reader.readAsText(input.files[0]);
    

    2) 绘制函数

    绘制DEM跟绘制一个简单三角形的步骤是差不多的:

    1. 获取WebGL环境。
    2. 初始化shaders,构建着色器。
    3. 初始化顶点数组,分配到缓冲对象。
    4. 绑定鼠标键盘事件,设置模型视图投影变换矩阵。
    5. 在重绘函数中调用WebGL函数绘制。

    其中最关键的步骤是第三步,初始化顶点数组initVertexBuffers()。

    function startDraw(verticesColors, cx, cy, cz, fovy) {
        // Retrieve <canvas> element
        var canvas = document.getElementById('demCanvas');
    
        // Get the rendering context for WebGL
        var gl = getWebGLContext(canvas);
        if (!gl) {
            console.log('Failed to get the rendering context for WebGL');
            return;
        }
    
        // Initialize shaders
        if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
            console.log('Failed to intialize shaders.');
            return;
        }
    
        // Set the vertex coordinates and color (the blue triangle is in the front)
        n = initVertexBuffers(gl, verticesColors);          //, verticesColors, n
        if (n < 0) {
            console.log('Failed to set the vertex information');
            return;
        }
    
        // Get the storage location of u_MvpMatrix
        var u_MvpMatrix = gl.getUniformLocation(gl.program, 'u_MvpMatrix');
        if (!u_MvpMatrix) {
            console.log('Failed to get the storage location of u_MvpMatrix');
            return;
        }
    
        // Register the event handler 
        initEventHandlers(canvas);
    
        // Specify the color for clearing <canvas>
        gl.clearColor(0, 0, 0, 1);
        gl.enable(gl.DEPTH_TEST);
    
        // Start drawing
        var tick = function () {
    
            //setPerspective()宽高比
            var aspect = canvas.width / canvas.height;
    
            //
            draw(gl, n, aspect, cx, cy, cz, fovy, u_MvpMatrix);
            requestAnimationFrame(tick, canvas);
        };
        tick();
    }
    

    3) 使用缓冲区对象

    在函数initVertexBuffers()中包含了使用缓冲区对象向顶点着色器传入多个顶点数据的过程:

    1. 创建缓冲区对象(gl.createBuffer());
    2. 绑定缓冲区对象(gl.bindBuffer());
    3. 将数据写入缓冲区对象(gl.bufferData);
    4. 将缓冲区对象分配给一个attribute变量(gl.vertexAttribPointer)
    5. 开启attribute变量(gl.enableVertexAttribArray);

    在本例中,在JS中申请的数组verticesColors分成位置和颜色两部分分配给缓冲区对象,并传入顶点着色器;vertexAttribPointer()是其关键的函数,需要详细了解其参数的用法。最后,把顶点数据的索引值绑定到缓冲区对象,WebGL可以访问索引来间接访问顶点数据进行绘制。

    function initVertexBuffers(gl, verticesColors) {
        //DEM的一个网格是由两个三角形组成的
        //      0------1            1
        //      |                   |
        //      |                   |
        //      col       col------col+1    
        var indices = new Uint16Array((row - 1) * (col - 1) * 6);
        var ci = 0;
        for (var yi = 0; yi < row - 1; yi++) {
            for (var xi = 0; xi < col - 1; xi++) {
                indices[ci * 6] = yi * col + xi;
                indices[ci * 6 + 1] = (yi + 1) * col + xi;
                indices[ci * 6 + 2] = yi * col + xi + 1;
                indices[ci * 6 + 3] = (yi + 1) * col + xi;
                indices[ci * 6 + 4] = (yi + 1) * col + xi + 1;
                indices[ci * 6 + 5] = yi * col + xi + 1;
                ci++;
            }
        }
    
        //创建缓冲区对象
        var vertexColorBuffer = gl.createBuffer();
        var indexBuffer = gl.createBuffer();
        if (!vertexColorBuffer || !indexBuffer) {
            return -1;
        }
    
        // 将缓冲区对象绑定到目标
        gl.bindBuffer(gl.ARRAY_BUFFER, vertexColorBuffer);
        // 向缓冲区对象中写入数据
        gl.bufferData(gl.ARRAY_BUFFER, verticesColors, gl.STATIC_DRAW);
    
        //
        var FSIZE = verticesColors.BYTES_PER_ELEMENT;
        // 向缓冲区对象分配a_Position变量
        var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
        if (a_Position < 0) {
            console.log('Failed to get the storage location of a_Position');
            return -1;
        }
        gl.vertexAttribPointer(a_Position, 3, gl.FLOAT, false, FSIZE * 6, 0);
        //开启a_Position变量
        gl.enableVertexAttribArray(a_Position);
    
        // 向缓冲区对象分配a_Color变量
        var a_Color = gl.getAttribLocation(gl.program, 'a_Color');
        if (a_Color < 0) {
            console.log('Failed to get the storage location of a_Color');
            return -1;
        }
        gl.vertexAttribPointer(a_Color, 3, gl.FLOAT, false, FSIZE * 6, FSIZE * 3);
        //开启a_Color变量
        gl.enableVertexAttribArray(a_Color);
    
        // 写入并绑定顶点数组的索引值
        gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, indexBuffer);
        gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, indices, gl.STATIC_DRAW);
    
        return indices.length;
    }
    

    4. 其他

    1.这里用到了几个《WebGL编程指南》书中提供的JS组件。全部源代码(包含DEM数据)地址链接:https://share.weiyun.com/5cvt8PJ ,密码:4aqs8e。
    2.如果关心如何设置模型视图投影变换矩阵,以及绑定鼠标键盘事件,可参看这篇文章:WebGL或OpenGL关于模型视图投影变换的设置技巧
    3.渲染的结果如果加入光照,效果会更好。

  • 相关阅读:
    前端各种小细节
    图片等比例缩放
    微信小程序倒计时,购物车,向左滑删除 左拉删除
    微信小程序用户拒绝授权,重新调起授权
    微信小程序swiper切换卡内嵌滚动条不显示
    php面试总结
    tp5.0 学习(三):URL和路由
    pytorch 基础内容
    Grammarly for Chrome-语法、用词自动检查
    时空图神经网路:STGNNs
  • 原文地址:https://www.cnblogs.com/charlee44/p/10799995.html
Copyright © 2011-2022 走看看