ios SCNGeometry以多边形作为基本类型

rkue9o1l  于 2023-08-08  发布在  iOS
关注(0)|答案(1)|浏览(117)

试图弄清楚我如何创建一个SCNGeometry与多边形作为primitiveType,我的目标是添加多边形形状的节点作为一个球体节点的子节点,并使其看起来像MKPolygonMap工具包,like in this example


的数据
我现在的代码是:

//Take an arbitrary array of vectors
let vertices: [SCNVector3] = [
SCNVector3Make(-0.1304485, 0.551937, 0.8236193),
SCNVector3Make(0.01393811, 0.601815, 0.7985139),
SCNVector3Make(0.2971005, 0.5591929, 0.7739732),
SCNVector3Make(0.4516893, 0.5150381, 0.7285002),
SCNVector3Make(0.4629132, 0.4383712, 0.7704169),
SCNVector3Make(0.1333823, 0.5224985, 0.8421428),
SCNVector3Make(-0.1684743, 0.4694716, 0.8667254)]

//Does polygon shape require indices?
let indices: [Int] = [0,1,2,3,4,5,6]

let vertexSource = SCNGeometrySource(vertices: vertices)
let indexData = Data(bytes: indices, count: indices.count * MemoryLayout<Int>.size)

//Note!!! I get compiler error if primitiveCount is greater than 0
let element = SCNGeometryElement(data: indexData, primitiveType: .polygon, primitiveCount: 0, bytesPerIndex: MemoryLayout<Int>.size)
let geometry = SCNGeometry(sources: [vertexSource], elements: [element])

let material = SCNMaterial()
material.diffuse.contents = UIColor.purple.withAlphaComponent(0.75)
material.isDoubleSided = true
geometry.firstMaterial = material

let node = SCNNode(geometry: geometry)

字符串
当像这样使用SCNGeometryElement时,我得到一个空节点。

qncylg1j

qncylg1j1#

你有两个问题:

  1. SceneKit(和Metal)仅支持32位整数作为索引(source)。因此,索引数组的类型需要是[Int32]
  2. SceneKit需要两条多边形信息:多边形中的点数和顶点数组中的点的索引。从Apple关于SCNGeometryPrimitiveTypePolygon(仅存在于Objective-C中)的文档中可以看到:
    元素的data属性会保留两个值序列。
  • 第一个序列具有与几何元素的primitiveCount值相等的多个值。此序列中的每个值指定多边形基本体中的顶点数。例如,如果第一个序列是[5,3],则几何图形元素包含一个五边形,后跟一个三角形。
  • 数据的其余部分是顶点索引的序列。第一序列中的每个条目指定第二序列中的条目的对应数目。例如,如果第一序列包括值[5,3],则第二序列包括五个用于五边形的索引,其后是三个用于三角形的索引。

您需要将索引数组更改为:

let indices: [Int32] = [7, /* We have a polygon with seven points */,
                        0,1,2,3,4,5,6 /* The seven indices for our polygon */
                       ]

字符串
然后,将primitiveCount设置为1(我们有一个多边形要绘制)并更改缓冲区的大小:

let indexData = Data(bytes: indices, 
                     count: indices.count * MemoryLayout<Int32>.size)

// Now without runtime error
let element = SCNGeometryElement(data: indexData, 
                                 primitiveType: .polygon,
                                 primitiveCount: 1, 
                                 bytesPerIndex: MemoryLayout<Int32>.size)

相关问题