Back to the Shapespark home page

[API] Cloning Material with a new name

Hi there,

let’s say I have 2 meshes with the same material. But I would like to make 2 separate materials out of it. Is this possible? What I’ve tried so far is:

  1. I cloned the material

  2. Then I assigned a new name to the clone

  3. Then I applied the cloned material to the mesh.

However, when I search for the material with the new name via findMaterial() it is not found. Can the cloned material be added to the material library afterwards? Or is there a much better approach to this problem?

Thank you

Do you call Viewer.setMaterialEditable() function for both materials (it is documented here: https://github.com/shapespark/shapespark-viewer-api#replace-textures-using-images-or-videos-from-external-source)?

Without this call the viewer will merge materials with identical properties and it not possible to find and modify such merged materials separately.

Unfortunately I can’t get it to work. Let’s imagine the following scenario:

We have 2 nodes that share the same material. But now I would like to have a hover effect for both materials (emissive). My idea at first was simply to change the names of the materials for the nodes, which of course didn’t work. So I thought to myself, I would take the material from each node, clone it, change the name and apply it to itself again to separate the materials.

Here is an example code

var node = viewer.findNodesOfType("MY_NODE")[0];
var material_to_clone = node.mesh.material;
var cloned_material = Object.assign(Object.create(Object.getPrototypeOf(material_to_clone)), material_to_clone);

cloned_material.name = "NEW_NAME";

node.mesh.material = cloned_material;

This is probably a wrong approach.

I thought you cloned the materials in the 3D modelling program. Is this something that would be possible in your case? Such JavaScript cloning won’t work because materials have WebGL state associated with them that won’t be cloned properly.

Thank you, so I can stop trying :slight_smile: