Difficulties with SCNNode subclass

First some background. I am running some physics simulations where I need to add physical properties (not display properties) to SCNNodes that contain the elemental material, e.g., Pb (lead), H2O (water), AlO3 (Aluminum oxide), etc. It looks to me like the init(geometry: SCNGeometry?) is a designated initializer because I don't see the word convenience in front of it.


So I thought this would be easy:


class PhysicalObject: SCNNode {
    var physicalMaterial: Material
        
    public init(geometry inGeom: SCNGeometry?, withMaterial: Material) {
        physicalMaterial = withMaterial
        super.init(geometry: inGeom)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    } 
    
}


This tells me the I "Must call a designated initializer of the superclass 'SCNNode'". I don't know why this is the case since I don't see the word convenience in front of that SCNNode initializer. Question 1: Why doesn't the above work? I am assuming I am wrong about init(geometry: ) being a designated initializer but then how do we tell from Apple's documentation?


So I found a work-around. I simply called super.init() and set the geometry manually. Not pretty but works. My only issue now is that I sometimes want to create a PhysicalObject from an SCNNode via

public init(nodeToCopy: SCNNode, withMaterial: Material) {
...
}

For example, if I read in a .scn file and look for node names like "Object Pb 8.2". The "Object" tells me that this Node should be a PhysicalObject, the "Pb" tells me the material is lead, and "8.2" is the density. Question 2: How can I possibly initialize a PhysicalObject from an SCNNode when I am stuck calling the SCNNode.init() routine. I would have to copy all the important properties of the node over... geometry, transforms, children, etc. I am at a total loss as to how to accomplish this. When I initialize the scene with

let scene = SCNScene(named: "art.scnassets/input.scn")

it creates an heirarchy of SCNNodes. I need to figure out how to convert some of them to PhysicalObjects. The clone() method isn't an option since it clones to an SCNNode. So I'm stuck at the same problem of how to convert an SCNNode to a PhysicalObject.


Thanks in advance to all the experts for your assistance,


-Matt

Replies

If SceneKit seralizes your scene to disk using NSCoder, then you should be able to implement NSCoder coding and decoding methods to retain your custom subclasses and their data. That would include implemnenting a way to encode and decode your custom subclass properties.