"""
HB_SelectionMaker V1.0

Last Modified: 6/25/2015
Works with CINEMA 4D R16.050 and up.
Copyright: Holger Biebrach, www.c4dstuff.com

Name-US: HB_SelectionMaker
Description-US: Makes Polygon Selections and assigns a material

Usage:
First make a Polygonselection. If you run this script you will be asked to choose a Name for this selection. When you hit enter the Script will do following:
- Create a new Material with a Random Color (if no Material is selected in Material Manager)
- Assign the Material to the current Selected Polygons
- Name the Selection Tag and the new Material properly.

This happens only if you have no Material Selected in the Material Manager. If you select a Material first it will use this Material instead of creating a new one.

Video Tutorial:
https://youtu.be/Ki6I9sRdeUU?t=7m37s


Name-DE: HB_SelectionMaker
Description-DE: Macht eine Polygonselektion und weisst ein Material zu

ChangeLog:
6/11/2015 Release Version

"""
import c4d
from  c4d import gui 
from random import randint
 

def randomColor():
    r = randint(0,255) / 256.0    
    g = randint(0,255) / 256.0    
    b = randint(0,255) / 256.0 
    color = c4d.Vector(r,g,b)
    return color


def main():
    obj=doc.GetActiveObject()
    objname=obj.GetName()
    if doc.GetMode()!=c4d.Mpolygons:
        return
    

    if not obj:
        return
    
    if obj.GetType()!=c4d.Opolygon:
        return
   
   
   
   
    nameinput = gui.InputDialog("Input Selectionname")
    if not nameinput: return
    
    
    
    seltag=doc.GetActiveTag()
    if seltag:
        seltag.DelBit(c4d.BIT_ACTIVE) 
    
    c4d.CallCommand(12552) # Set Selection
    
   
    newseltag=doc.GetActiveTag()
   
    newseltag.SetName(nameinput)
     
    
    selmat=doc.GetActiveMaterial()
    if not selmat:
        newmat = c4d.BaseMaterial(5703)
        doc.InsertMaterial(newmat)
        doc.AddUndo(c4d.UNDOTYPE_NEW, newmat)
        c4d.EventAdd()
        newmat.SetName(objname+"::"+nameinput)
        newmat[c4d.MATERIAL_COLOR_COLOR]=randomColor()
        newmat.SetBit(c4d.BIT_ACTIVE)
        
        
    c4d.CallCommand(12169) # Apply
    c4d.CallCommand(300001026) # Deselect All
    
    
    mattag=doc.GetActiveTag()
    mattag[c4d.TEXTURETAG_RESTRICTION]=nameinput
   
   
   

if __name__=='__main__':
    main()
