Custom SceneKit Geometry in Swift on iOS not working but equivalent Objective C code does

后端 未结 3 1785
南笙
南笙 2020-12-06 02:17

I am keen to adopt the new Swift language as this seems to be the way forward with Apple development. I have also been impressed with the new SceneKit support in iOS 8. I wo

3条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 02:28

    Well, the two pieces of code doesn't translate exactly to one another. The int in C is not the same as Int in Swift. It's actually called CInt in Swift:

    /// The C 'int' type.
    typealias CInt = Int32
    

    If you change both occurrences to use CInt instead, the error message that you previously got goes away (at least for me in an OS X Playground. However, it still doesn't render anything for me.

    I don't think sizeofValue is used to return the size of an array. It looks to me like it's returning the size of the pointer:

    let indexes: CInt[] = [0, 1, 2]
    sizeofValue(indexes)                   // is 8
    sizeof(CInt)                           // is 4
    sizeof(CInt) * countElements(indexes)  // is 12
    
    // compare to other CInt[]
    let empty: CInt[] = []
    let large: CInt[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    
    sizeofValue(indexes)                   // is 8 (your array of indices again)
    sizeofValue(empty)                     // is 8
    sizeofValue(large)                     // is 8
    

    So, for me the following code works (I've put the arguments on different lines to make it easier to point out my changes):

    let src = SCNGeometrySource(vertices: &verts, count: 3)
    let indexes: CInt[] = [0, 1, 2] // Changed to CInt
    
    let dat  = NSData(
        bytes: indexes,
        length: sizeof(CInt) * countElements(indexes) // Changed to size of CInt * count
    )
    let ele = SCNGeometryElement(
        data: dat,
        primitiveType: .Triangles,
        primitiveCount: 1,
        bytesPerIndex: sizeof(CInt) // Changed to CInt
    )
    let geo = SCNGeometry(sources: [src], elements: [ele])
    
    let nd = SCNNode(geometry: geo)
    scene.rootNode.addChildNode(nd)
    

    With this result:

    enter image description here

提交回复
热议问题