表观指数限制

Apparent indices limit

在 swift 中使用 SceneKit 我试图构建自定义 3D 对象(地形)。为了构建地形,我构建了一个平面,我将其分为多个水平和垂直部分。如果数字或部分较小,一切都很好,但如果数字不大,应用程序会在某些具有 EXC_BAD_ACCESS.

的深层 OpenGL 函数中崩溃。

这是地形的简化版本(是的,它只是一个平面),没有出现问题:

let width:Float = 12
let depth:Float = 12
let height:Float = 2
let nx = 6
let nz = 6

func build() -> SCNGeometry {
    var vertices : [SCNVector3] = Array()
    for i in 0..<(nx + 1) {
        for j in 0..<(nz + 1) {
            let x = (Float(i) / Float(nx)) * width - width/2
            let z = (Float(j) / Float(nz)) * depth - depth/2
            let y = Float(0)
            vertices.append(SCNVector3(x:x, y:y, z:z))
        }
    }

    var indices : [CInt] = []
    for i in 0..<nx {
        for j in 0..<nz {
            indices.append(CInt(i   + j * (nz+1)))
            indices.append(CInt(i+1 + j * (nz+1)))
            indices.append(CInt(i   + (j+1)*(nz+1)))

            indices.append(CInt(i+1 + j * (nz+1)))
            indices.append(CInt(i+1 + (j+1)*(nz+1)))
            indices.append(CInt(i   + (j+1)*(nz+1)))
        }
    }

    let data = NSData(bytes: vertices, length: sizeof(SCNVector3) * countElements(vertices))

    let vertexSource = SCNGeometrySource(data: data, semantic: SCNGeometrySourceSemanticVertex, vectorCount: vertices.count, floatComponents: true, componentsPerVector: 3, bytesPerComponent: sizeof(Float), dataOffset: 0, dataStride: sizeof(SCNVector3))

    let indexData = NSData(bytes: indices, length: sizeof(CInt) * countElements(indices))

    let element = SCNGeometryElement(data: indexData, primitiveType: SCNGeometryPrimitiveType.Triangles, primitiveCount: indices.count, bytesPerIndex: sizeof(CInt))

    return SCNGeometry(sources: [vertexSource], elements: [element])
}

现在将 nx 和 nz 更改为:

let nx = 8
let nz = 8

崩溃

这似乎与指数数量密切相关,但在 ~300 时我认为我不应该达到极限。

非常感谢任何建议、帮助或解决方案。谢谢

问题可能是您在创建 SCNGeometryElement 时传递的是 primitiveCount: indices.count 而不是 indices.count/3 (因为每个三角形有三个索引)。我很惊讶没有更早的边界检查,但如果没有它,您肯定会看到崩溃,具体取决于索引的数量。