在WebGL中对平面进行三角测量

时间:2016-02-20 03:55:26

标签: javascript opengl-es webgl gl-triangle-strip

我试图用WebGL中的三角形构建一个平面。我的构造函数代码如下所示:

function plane( points_transform )
{

    shape.call(this); // Inherit class shape’s array members by calling parent constructor
    if( !arguments.length) return; // Pass no arguments if you just want to make an empty dummy object that inherits everything, for populating other shapes
    this.populate( this, points_transform ); // Otherwise, a new triangle immediately populates its own arrays with triangle points,
    this.init_buffers(); // Then sends its arrays to the graphics card into new buffers
}

inherit(plane, shape); 
plane.prototype.populate = function( recipient, points_transform) 
{
    var offset = recipient.vertices.length;        
    var index_offset = recipient.indices.length;                // Recipient's previous size

    recipient.vertices.push( vec3(0,0,0), vec3(1,1,0), vec3(0,1,0), vec3(1,0,0), vec3(2,1,0), vec3(2,0,0) );
    recipient.normals.push( vec3(0,0,1), vec3(0,0,1), vec3(0,0,1), vec3(0,0,1), vec3(0,0,1), vec3(0,0,1) );
    // recipient.texture_coords.push( vec2(0,0), vec2(0,1), vec2(1,0), vec2(1,1), vec2(2,0), vec2(2,1) );
    recipient.indices.push( offset + 0, offset + 1, offset + 2, offset + 3, offset + 4, offset + 5 );

    gl.drawArrays(gl.TRIANGLE_STRIP, 0, recipient.vertices);
}

然而,当我画它时,它看起来像这样脱节:

enter image description here

我想知道如何修复该问题以及如何创建一个可以采用任意数量的行/列并计算必要顶点以生成MxN网格的通用函数。

我特意看this site,但我无法弄清楚triangletrip变量的来源。

1 个答案:

答案 0 :(得分:1)

几天前就问过这个问题。这是一个答案

Generate grid mesh

在您的特定情况下,虽然1个单位的矩形具有这些点

0,0      1,0
 +--------+
 |        |
 |        |
 |        |
 |        |
 +--------+
0,1      1,1

所以你的顶点应该是

recipient.vertices.push( 
  vec3(0,0,0), vec3(1,1,0), vec3(0,1,0), 
  vec3(1,0,0), vec3(1,1,0), vec3(0,0,0) );

没有2 s

当然,还有许多其他组合和顺序,这4个点将形成一个矩形。

我通常会选择此订单

0         1 4 
 +--------+
 |        |
 |        |
 |        |
 |        |
 +--------+
2 3       5

除了处理culling(在该页面上搜索剔除)之外,我认为除了一个或另一个订单之外没有任何特殊原因

在您的特定情况下,您也使用TRIANGLE_STRIP。首先让我说AFAIK *没有专业游戏开发者使用TRIANGLE_STRIP。他们都使用普通TRIANGLES。它只是简化了一切,因此您可能希望切换到TRIANGLES。通过你只需要4分

recipient.vertices.push( 
  vec3(0,0,0), vec3(0,1,0), vec3(0,1,0), vec3(1,1,0)); 
recipient.indices.push( 
  offset + 0, offset + 1, offset + 2, offset + 3);

以防万一不清楚。给定6个点TRIANGLES将绘制由

组成的2个三角形
triangle 0 = points 0,1,2 
triangle 1 = points 3,4,5 

TRIANGLE_STRIP将绘制由

组成的4个三角形
triangle 0 = points 0,1,2 
triangle 1 = points 1,2,3 
triangle 2 = points 2,3,4 
triangle 3 = points 3,4,5 

此外,它根本不清楚你的代码在做什么。也许recipeient.xxx.push正在做一些非常低效的魔术,但是当你调用gl.drawArrays时,没有迹象表明你正在创建的顶点实际上被WebGL使用。通常需要对gl.bufferDatagl.bufferSubData进行一些调用才能将数据提供给WebGL。您还要重新创建索引,但gl.drawArrays不使用索引。