"""
HB_GroupSymmetry V1.0

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

Name-US: HB_GroupSymmetry
Description-US: Groups selected Objects and make them Symmetrical [SHIFT: Make Symmetry in Global Space]

Video Tutorial:
https://youtu.be/Ki6I9sRdeUU?t=42m6s

Name-DE: HB_GroupSymmetry
Description-DE: Gruppiert Objekte und macht diese Symmetrischt  [SHIFT: Make Symmetry in Global Space]

ChangeLog:
6/11/2015 Release Version

"""



import c4d
from c4d import utils

def GetGlobalPosition(obj):
    return obj.GetMg().off

def GetGlobalRotation(obj):
    return utils.MatrixToHPB(obj.GetMg())




def SetGlobalPosition(obj, pos):
    m = obj.GetMg()
    m.off = pos
    obj.SetMg(m)


def SetGlobalRotation(obj, rot):

    m = obj.GetMg()
    pos = m.off
    scale = c4d.Vector( m.v1.GetLength(),
                        m.v2.GetLength(),
                        m.v3.GetLength())

    m = utils.HPBToMatrix(rot)

    m.off = pos
    m.v1 = m.v1.GetNormalized() * scale.x
    m.v2 = m.v2.GetNormalized() * scale.y
    m.v3 = m.v3.GetNormalized() * scale.z

    obj.SetMg(m)



def main():
    doc.StartUndo()
    
    bc = c4d.BaseContainer()
    c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD,c4d.BFM_INPUT_CHANNEL,bc)
        
    modifier= bc[c4d.BFM_INPUT_QUALIFIER]
        
      
    
    c4d.CallCommand(100004772) # Group Objects
    group = doc.GetActiveObject()
    
    if modifier==0:
        groupPos=group.GetMl()
    else:
        groupPos=group.GetMg()

    group.SetName("group")

    Symmetry_Root=c4d.BaseObject(c4d.Onull)
    Symmetry_Root.SetName("Symmetry_Root")
    doc.AddUndo(c4d.UNDOTYPE_NEW, Symmetry_Root)
    Symmetry_Root.InsertAfter(group)
    
    #Symmetry_Root.GetMl
    doc.AddUndo(c4d.UNDOTYPE_CHANGE, group)
    group.InsertUnder(Symmetry_Root)
    sym=c4d.BaseObject(c4d.Osymmetry)
    doc.AddUndo(c4d.UNDOTYPE_NEW, sym)
    sym.InsertBefore(Symmetry_Root)
    
    
    if modifier == 1: # SHIFT
        SetGlobalPosition(sym, c4d.Vector(0,0,0))
        SetGlobalRotation(sym, c4d.Vector(0,0,0))
        
        
    doc.AddUndo(c4d.UNDOTYPE_CHANGE, Symmetry_Root)
    Symmetry_Root.InsertUnder(sym)
    
    if modifier == 1: #SHIFT
        group.SetMg(groupPos)
    else:
        group.SetMl(groupPos)
    
    doc.EndUndo()
    c4d.EventAdd()

if __name__=='__main__':
    main()
