Skip to content

Instantly share code, notes, and snippets.

@MikeUdin
Last active August 31, 2022 08:56
Show Gist options
  • Save MikeUdin/e110c66485d51016f2fef1e2acf26b3d to your computer and use it in GitHub Desktop.
Save MikeUdin/e110c66485d51016f2fef1e2acf26b3d to your computer and use it in GitHub Desktop.
'''
Create materials for all Objects Polygon Selection Tags in Cinema 4D using Python API.
Author: Mike Udin
Website: mikeudin.net
Tutorial: https://youtu.be/mJcL6i0SCtY
'''
import c4d
import random
# from pprint import pprint
def get_random_color(pastel_factor = 0.5):
return [(x+pastel_factor)/(1.0+pastel_factor) for x in [random.uniform(0,1.0) for i in [1,2,3]]]
def color_distance(c1,c2):
return sum([abs(x[0]-x[1]) for x in zip(c1,c2)])
def generate_new_color(existing_colors,pastel_factor = 0.5):
max_distance = None
best_color = None
for i in range(0,100):
color = get_random_color(pastel_factor = pastel_factor)
if not existing_colors:
return color
best_distance = min([color_distance(color,c) for c in existing_colors])
if not max_distance or best_distance > max_distance:
max_distance = best_distance
best_color = color
return best_color
def main():
if not op:
c4d.gui.MessageDialog('Please select object with Selection Tags!')
return
# Sort only polygon selection tags from all object tags
stags = [t for t in op.GetTags() if t.CheckType(c4d.Tpolygonselection)]
if not stags:
c4d.gui.MessageDialog('Please select object with Selection Tags!')
return
colors = list()
doc.StartUndo()
for stag in stags:
name = stag.GetName()
mat = c4d.Material(c4d.Mbase)
mat.SetName(name)
color = generate_new_color(colors)
colors.append(color)
mat[c4d.MATERIAL_COLOR_COLOR] = c4d.Vector(*color)
doc.InsertMaterial(mat)
doc.AddUndo(c4d.UNDOTYPE_NEWOBJ,mat)
mtag = op.MakeTag(c4d.Ttexture,stag)
mtag.SetMaterial(mat)
mtag[c4d.TEXTURETAG_RESTRICTION] = name
doc.AddUndo(c4d.UNDOTYPE_NEWOBJ,mtag)
doc.EndUndo()
c4d.EventAdd()
# pprint(colors)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment