java - 如何用三角形绘制3D地形?

标签 java opengl 3d rendering lwjgl

我有一个 3D boolean 数组,代表一些 3D 地形。目前我可以通过在数组中的 x y 和 z 指定的位置绘制一个点来绘制它,它看起来像这样。 The terrain as it stands

我不知道如何使用三角形来绘制它,所以它看起来像实际的地形。我也不想将每个都绘制为立方体。

是否有任何算法可以获取要绘制的点(请记住,为了提高效率,只应绘制陆地外部的点)?

最佳答案

绝对令人惊奇的问题!我忍不住要玩盒子,因为盒子很性感。实际上,生成省略隐藏面的盒子相当容易。

以下算法获取网格中 true 的 3D 位置列表,只需扫描网格并填充数组即可轻松获取该列表。此外,使用这种数据格式,您可以存储更大的网格,前提是地形相当稀疏。首先,为我的斯巴达式 for-each 循环道歉,我只是想让代码就位并避免编写数十个函数对象或使用 lambda。另外,我对使用 C++ 而不是 Java 表示歉意,家里没有 javac,而且我也不太擅长使用它。这里是:

#include <vector>
#include <map>
#include <set>
#include <utility>
#include <assert.h>
#include <math.h>

struct Pos3 {
    int x, y, z;

    Pos3(int _x = 0, int _y = 0, int _z = 0);
    bool operator <(const Pos3 &other) const;
};

std::vector<int> index_buffer;
std::vector<float> vertex_buffer;

void onInitialize()
{
    const int N = 32;
    std::vector<Pos3> points;
    GeneratePoints(points, N);
    // input: bunch of points in NxNxN box (easy to get from a boolean array,
    // can have much larger terrains if stored like this)

    std::set<Pos3> point_set;
    point_set.insert(points.begin(), points.end());
    // put all the points to a set to be able to lookup neighbors (not needed with an array)

    std::vector<std::vector<int> > polygons;
    polygons.reserve(3 * points.size()); // guess
    std::map<Pos3, int> vertex_map;
    for(size_t i = 0, n = points.size(); i < n; ++ i) {
        Pos3 p = points[i], corners[8] = {
            p, Pos3(p.x + 1, p.y, p.z), Pos3(p.x + 1, p.y + 1, p.z), Pos3(p.x, p.y + 1, p.z),
            Pos3(p.x, p.y, p.z + 1), Pos3(p.x + 1, p.y, p.z + 1), Pos3(p.x + 1, p.y + 1, p.z + 1),
            Pos3(p.x, p.y + 1, p.z + 1)
        };
        // get corners of a cube

        static const int sides[][3 + 4] = {
            0, -1,  0,  4, 5, 1, 0,          1, 0, 0,   5, 6, 2, 1,
            0,  1,  0,  6, 7, 3, 2,         -1, 0, 0,   7, 4, 0, 3,
            0,  0, -1,  0, 1, 2, 3,          0, 0, 1,   7, 6, 5, 4
        };
        // directions and side quad indices

        for(int j = 0; j < 6; ++ j) {
            Pos3 n(p.x + sides[j][0], p.y + sides[j][1], p.z + sides[j][2]); // position of a neighbor
            if(point_set.find(n) != point_set.end())
                continue; // have a neighbor, will not triangulate this side

            polygons.resize(polygons.size() + 1);
            std::vector<int> &poly = polygons.back(); // or use emplace_back() in c++11
            poly.resize(4); // form quads
            for(int v = 0; v < 4; ++ v) {
                Pos3 vert = corners[sides[j][3 + v]];
                std::map<Pos3, int>::iterator it; // use map to reuse vertices
                if((it = vertex_map.find(vert)) == vertex_map.end())
                    vertex_map[vert] = poly[v] = vertex_map.size(); // new vertex
                else
                    poly[v] = (*it).second; // existing vertex
            }
        }
        // generate sides, skip invisible sides
        // note that this still triangulates cavities, would have to flood-fill
        // outside area and then set all that is not outside to opaque (did not
        // solve that as this is also a valid behavior)
    }

    vertex_buffer.resize(vertex_map.size() * 3);
    for(std::map<Pos3, int>::const_iterator it = vertex_map.begin(), e = vertex_map.end(); it != e; ++ it) {
        size_t i = (*it).second * 3;
        vertex_buffer[i + 0] = ((*it).first.x + .5f) / (N + 1) * 2 - 1;
        vertex_buffer[i + 1] = ((*it).first.y + .5f) / (N + 1) * 2 - 1;
        vertex_buffer[i + 2] = ((*it).first.z + .5f) / (N + 1) * 2 - 1;
    }
    // convert points from the discrete domain
    // to a unit 3D cube centered around the origin

    index_buffer.reserve(polygons.size() * 2 * 3); // approximate number of triangles
    for(size_t i = 0, n = polygons.size(); i < n; ++ i) {
        const std::vector<int> &poly = polygons[i];
        for(size_t j = 2, n = poly.size(); j < n; ++ j) {
            index_buffer.push_back(poly[0]);
            index_buffer.push_back(poly[j]);
            index_buffer.push_back(poly[j - 1]);
        }
    }
    // convert polygons (those are actually quads) to triangles
}

还有一些生成法线的代码(为了清楚起见而省略),输出如下所示:

Julia set as cubes, wireframe

该形状是在离散晶格上生成的 Julia 集,当您转动它时您可能会认出该形状。

如果您可以轻松删除内部点,这实际上与您通过 Delaunay 三角剖分得到的结果非常相似。生成的形状是空心的。形状中可能存在一些“气泡”,以防 boolean 值也包含气泡(Julia 不会出现这种情况)。通过洪水填充 boolean 值以填充这些 boolean 值可以轻松解决此问题。

接下来,我们可以应用 Catmull-Clark 分割以获得更平滑的网格:

typedef std::map<std::pair<int, int>, std::pair<size_t, int> > EdgeMap;

static bool Get_EdgeID(size_t &eid, int a, int b, EdgeMap &edges)
{
    std::pair<int, int> e(std::min(a, b), std::max(a, b));
    EdgeMap::iterator it = edges.find(e);
    if(it == edges.end()) {
        edges[e] = std::make_pair(eid = edges.size(), 1); // id, count
        return true; // new edge
    } else {
        eid = (*it).second.first; // get id
        ++ (*it).second.second; // increase count
        return false; // no new edge
    }
}

void CatClark(std::vector<std::vector<int> > &src_quads, std::vector<float> &src_verts)
{
    const static float vpw[4] = {9.0f, 3.0f, 1.0f, 3.0f};
    const static float epw[4] = {3.0f, 3.0f, 1.0f, 1.0f};

    std::vector<std::vector<int> > dst_quads(src_quads.size() * 4, std::vector<int>(4)); // will produce quads
    std::vector<float> dst_verts(src_verts.size() + src_quads.size() * 3, 0); // alloc s¨pace for vertices

    EdgeMap edges;
    std::vector<int> face_valences(src_verts.size() / 3, 0);
    const size_t off_vp = src_quads.size(), off_ep = off_vp + src_verts.size() / 3;
    for(size_t j = 0; j < off_vp; ++ j) {
        assert(src_quads[j].size() == 4); // otherwise won't work
        size_t eid[4];
        for(int k = 0; k < 4; ++ k) {
            int quad[4];
            for(int i = 0; i < 4; ++ i)
                quad[i] = src_quads[j][(i + k) & 3]; // get the 4 vertices (but rotate them each k iteration)
            if(Get_EdgeID(eid[k], quad[0], quad[1], edges)) // create edges
                dst_verts.insert(dst_verts.end(), 3, .0f); // must add new vertex to accomodate subdivided edge point
            ++ face_valences[quad[0]]; // update face-valence
            for(int n = 0; n < 3; ++ n)
                dst_verts[j * 3 + n] += 0.25f * src_verts[quad[0] * 3 + n]; // increment face point 
            for(int i = 0; i < 4; ++ i) {
                for(int n = 0; n < 3; ++ n) {
                    dst_verts[(off_vp + quad[0]) * 3 + n] += vpw[i] * src_verts[quad[i] * 3 + n]; // incremente vertex point
                    dst_verts[(off_ep + eid[k]) * 3 + n] += epw[i] * src_verts[quad[i] * 3 + n]; // increment edge point
                }
            }
        }
        for(int k = 0; k < 4; ++ k) { // make child faces
            dst_quads[4 * j + k][0] = j;
            dst_quads[4 * j + k][4] = off_ep + eid[(3 + k) & 3]; 
            dst_quads[4 * j + k][5] = off_ep + eid[(0 + k) & 3]; 
            dst_quads[4 * j + k][6] = off_vp + src_quads[j][k];
        }
    }
    for(size_t j = 0, n = src_verts.size() / 3; j < n; ++ j) {
        for(int n = 0; n < 3; ++ n)
            dst_verts[(off_vp + j) * 3 + n] *= 0.0625f / float(face_valences[j]);
    }
    for(EdgeMap::const_iterator it = edges.begin(), e = edges.end(); it != e; ++ it) {
        size_t j = (*it).second.first;
        float rvalence = 0.1250f / float((*it).second.second);
        for(int n = 0; n < 3; ++ n)
            dst_verts[(off_ep + j) * 3 + n] *= rvalence;
    }
    dst_quads.swap(src_quads);
    dst_verts.swap(src_verts);
}

该算法经过改编,可与 Iñigo 'iq' Quilez/rgba 的 STL 容器一起使用,“rgba 过去和 future 介绍的技巧和技术”,Breakpoint,2007 年。

这给出的输出与使用行进立方体/行进四面体/行进三角形得到的输出非常相似,除了它总是比原始晶格的分辨率更高(使用上述方法,您可以轻松更改三角剖分分辨率)。相同数据的略有不同的 View :

Julia set as cubes after double Catmull-Clark subdivision, wireframe

或者没有线框:

Julia set as cubes after double Catmull-Clark subdivision, smooth shaded

完整的源代码以及 Visual Studio 工作区和 win32 二进制文件可以在 here 中找到。 。它使用 GLUT 和旧的固定功能管道来显示生成的几何图形(仅为了简单性和可移植性,否则我必须包含 GLEW 等)。我真的很喜欢玩弄你的问题,我希望你会喜欢这个输出......

关于java - 如何用三角形绘制3D地形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19730676/

相关文章:

matlab - 如何在 MATLAB 中绘制球体上的平滑连接图?

python - 处理相机旋转的正确方法

3d - Libgdx 中的卡片翻转动画

java - 在 Spring Boot 2.0 中使用自签名证书启用 HTTPS

java - 如何提取 Maven 配置文件中的公共(public)部分

java - Try/Catch 和循环控制

java - 按纵横比拉伸(stretch)的 OpenGL 2D 投影

java - 如何从 Firebase 存储获取下载网址?

c - 在 OpenGL 中调整窗口大小 : Garbage Output

c++ - OpenGL实际上是如何读取索引的?