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

Triangulating a Plane in WebGL

我正在尝试在 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);
}

但是当我画出来的时候,它看起来是这样的:

我想知道如何解决这个问题,以及如何制作一个可以采用任意数量的行/列并计算必要的顶点以生成 MxN 网格的通用函数。

我专门查看了 this site,但我无法弄清楚 trianglestrip 变量的来源。

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

在您的特定情况下,虽然 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) );

没有2s

当然,这 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 不使用索引。