I'm trying to create a custom geometry object in SceneKit, which should be a plane with an arbitrary shape. I'm supplying the outlining vertices of the shape, and want to fill up the inside of it.
So far I have been using this code:
extension SCNGeometry {
static func polygonPlane(vertices: [SCNVector3]) -> SCNGeometry {
var indices: [Int32] = [Int32(vertices.count)]
var index: Int32 = 0
for _ in vertices {
indices.append(index)
index += 1
}
let vertexSource = SCNGeometrySource(vertices: vertices)
let textureCoords : [CGPoint] = [] // Fix to map textures to the polygon plane...
let textureCoordsSource = SCNGeometrySource(textureCoordinates: textureCoords)
let indexData = Data(bytes: indices, count: indices.count * MemoryLayout<Int32>.size)
let element = SCNGeometryElement(data: indexData, primitiveType: .polygon, primitiveCount: 1, bytesPerIndex: MemoryLayout<Int32>.size)
let geometry = SCNGeometry(sources: [vertexSource, textureCoordsSource], elements: [element])
let imageMaterial = SCNMaterial()
imageMaterial.diffuse.contents = UIImage(named: "texture.jpg")
let scaleX = (Float(1)).rounded()
let scaleY = (Float(1)).rounded()
imageMaterial.diffuse.contentsTransform = SCNMatrix4MakeScale(scaleX, scaleY, 0)
imageMaterial.isDoubleSided = true
geometry.firstMaterial = imageMaterial
return geometry
}
}
This works reasonably well when making more simple polygon shapes, but does not work as intended when the shape becomes more complex and narrow in different places. I also don't know of any way to create texture coordinates in order to apply a custom texture with this approach.
I think I need to utilize some kind of polygon triangulation algorithm in order to break the shape into triangles, and then use the correct SCNGeometryPrimitiveType such as .triangles or .triangleStrip. This could probably also allow me to do a UV-mapping for the texture coordinates, however I'm not sure how that would work as of right now.
The polygon triangulation algorithm would need to be able to handle 3D coordinates, as the created 2D geometry should exist in a 3D world (you should be able to create tilted polygon planes etc.). I have not been able to find any 3D polygon triangulation algorithms already implemented in Swift yet.
To be clear on the texture coordinates; the texture that would be used is a repeating texture such as this one:
