"""
HB_SetPhong V1.0

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

Name-US: HB_SetPhong
Description-US: Sets Phongangle of selected Objects

!!!!If no Object is selected the Script will apply Phong on all Objects of the Scene!!!!

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

Name-DE: HB_SetPhong
Description-DE: Stellt den Phngwinkel der selektierten Objekte ein

ChangeLog:
6/11/2015 Release Version

"""


import c4d
from c4d import gui

def GetAllObjects(doc):
    def SearchOM(op):
        if not op: return
        if op.GetDown(): return op.GetDown()
        while not op.GetNext() and op.GetUp():
            op = op.GetUp()
        return op.GetNext()

    obj = doc.GetFirstObject()
    liste = list()
    liste.append(obj)
    while obj:
        obj = SearchOM(obj)
        liste.append(obj)
    return liste




def checktype(tags): # List of current Tag Types on Object
    checktypes = []
    for tag in tags:
        checktypes.append(tag.GetType())
    return checktypes

def scantags(obj,tagtypes): # Scan Tags on Object
    global UserPhong
    n       = 1 
    
    tags    = obj.GetTags()

    for tag in tags:
        if not tag: continue
        tagtype = tag.GetType()
        count   = checktype(tags).count(tagtype)       
        
        
        if tagtype==5612:
            doc.AddUndo(c4d.UNDOTYPE_CHANGE, tag)
            tag[c4d.PHONGTAG_PHONG_ANGLELIMIT]=True
            tag[c4d.PHONGTAG_PHONG_ANGLE]=c4d.utils.Rad(float(UserPhong))
            tag[c4d.PHONGTAG_PHONG_USEEDGES]=False
            c4d.EventAdd()

            
            
            

def scandoc(doc,obj,tagtypes): # Scan doc obj hierarchy
    while obj:
        scantags(obj,tagtypes) 
        scandoc(doc,obj.GetDown(),tagtypes)
        obj = obj.GetNext()

def main():  
    global UserPhong
    doc.StartUndo()
    
    UserPhong = gui.InputDialog("Set Global Phong Angle")
    

    if not UserPhong: return
    
    tagtypes = []             
    

    if len(doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_CHILDREN)): #Objects are selected
        activeobjects = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_CHILDREN)    
    else: #No Objects selected. Do it on all Objects!
        
        activeobjects = GetAllObjects(doc)
    
    for obj in activeobjects:
        scantags(obj,tagtypes)
    
    doc.EndUndo()


if __name__=='__main__':
    main()
    c4d.EventAdd()