SCNGeometry with polygon as primitiveType

会有一股神秘感。 提交于 2019-11-29 07:44:53
jlsiewert

You have two problems:

  1. SceneKit (and Metal) only support 32 bit integers as indices (source). So the type of your indices array needs to be [Int32].

  2. SceneKit needs two pieces of information for polygons: The number of points in the polygon and the index of the point in the vertex array. From Apple's documentation on SCNGeometryPrimitiveTypePolygon (which only exists in Objective-C):

The element’s data property holds two sequences of values.

  • The first sequence has a number of values equal to the geometry element’s primitiveCount value. Each value in this sequence specifies the number of vertices in a polygon primitive. For example, if the first sequence is [5, 3], the geometry element contains a pentagon followed by a triangle.
  • The rest of the data is a sequence of vertex indices. Each entry in the first sequence specifies a corresponding number of entries in the second sequence. For example, if the first sequence includes the values [5, 3], the second sequence includes five indices for the pentagon, followed by three indices for the triangle.

You need to change your index array to:

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

Then, set the primitiveCount to 1 (we have one polygon to draw) and change the size of the buffer:

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!