"""
HB_Instancer V1.0

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

Name-US: HB_Instancer
Description-US: Converts selected Objects to Renderinstances while the last selected is the Reference


Name-DE: HB_Instancer
Description-DE: Macht Renderinstanzen und referenziert das letzte selektierte Objekt

ChangeLog:
6/11/2015 Release Version

"""

import c4d

def main():
    doc = c4d.documents.GetActiveDocument()
    doc.StartUndo()

    ObjList = doc.GetOrderedActiveObjects()

    if len(ObjList)==1:
        Name=ObjList[0].GetName()
        Posobj=ObjList[0].GetMl()
        Instance=c4d.BaseObject(c4d.Oinstance)
        Instance[c4d.INSTANCEOBJECT_LINK]=ObjList[0]
        Instance[c4d.INSTANCEOBJECT_RENDERINSTANCE]=True
        Instance.SetName("Instance of "+Name)
        Instance.SetMl(Posobj)
        doc.AddUndo(c4d.UNDOTYPE_NEW, Instance)
        Instance.InsertAfter(ObjList[0])
        
    LastObject = ObjList[len(ObjList)-1]
    Name=LastObject.GetName()
    if not ObjList: return


    for obj in ObjList:
        
        Posobj=obj.GetMl()
        
        Instance=c4d.BaseObject(c4d.Oinstance)
        Instance[c4d.INSTANCEOBJECT_LINK]=LastObject
        Instance[c4d.INSTANCEOBJECT_RENDERINSTANCE]=True
        Instance.SetName("Instance of "+Name)
        Instance.SetMl(Posobj)
        doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj)
        if obj is not LastObject:
            doc.AddUndo(c4d.UNDOTYPE_NEW, Instance)
            Instance.InsertBefore(obj)
            
            obj.Remove()


    doc.EndUndo()
    c4d.EventAdd()

if __name__=='__main__':
    main()