swiftrealitykitreality-composer

How can I programmatically load a custom material from Reality Composer Pro?


I have created a custom shader material in Reality Composer Pro (RCP). I can attach it to models in RCP without a problem, but my issue is that I am creating my models in code. I can not figure out how to reference the material in my RCP project.

I'm trying this but getting no luck. I suspect the "Package" string could be incorrect, but the docs don't make it very clear what the string should actually be.

if let puzzleMaterial = try? ShaderGraphMaterial.load(named: "MyCustomMaterial", from: "Package", in: realityKitContentBundle) {
    // Do something with the material
} else {
    // No luck
}

Solution

  • I don't know if this is best practice or not but I made a copy of the PuzzleMaterial.usda file created by Reality Composer Pro and added it to the app's main bundle. Then I just load that into into a Data blob and used ShaderGraphMaterials init(named: from:) initializer. I peaked at the usda text file to get the "path" to the material shader:

    var puzzleMaterial : ShaderGraphMaterial? = nil
    do {
        let materialURL = Bundle.main.url(forResource: "PuzzleMaterial", 
                                          withExtension: "usda")
        if let materialURL = materialURL {
           let materialData = try Data(contentsOf: materialURL)
           puzzleMaterial = try await 
                 ShaderGraphMaterial(named:"/PuzzleMaterial/PuzzleMaterial", 
                                      from: materialData)
        }
    } catch {
        print("PuzzleMaterial load failed: \(error)")
    }
    

    I hope some one comes up with a more canonical answer that uses the Swift Package that bundles the usda file. This works for now.