Esempio n. 1
0
def dataAddBool(obj, name, parent, default):
    ud = c4d.GetCustomDatatypeDefault(c4d.DTYPE_BOOL)
    ud[c4d.DESC_NAME] = name
    ud[c4d.DESC_DEFAULT] = default
    ud[c4d.DESC_PARENTGROUP] = parent
    uid = obj.AddUserData(ud)
    obj[uid] = default
    def PopupWDISPLAYMODE(self):

        bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_LONG)

        bc.SetInt32(c4d.DESC_CUSTOMGUI, c4d.CUSTOMGUI_CYCLE)
        bc.SetInt32(c4d.DESC_MIN, 0)
        bc.SetInt32(c4d.DESC_MAX, 3)

        cycle = c4d.BaseContainer()

        cycle.SetString(
            c4d.SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_WDISPLAYMODE_WIRE,
            "Wireframe")
        cycle.SetString(
            c4d.SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_WDISPLAYMODE_ISOPARM,
            "Isoparms")
        cycle.SetString(
            c4d.SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_WDISPLAYMODE_BOX, "Box")
        cycle.SetString(
            c4d.SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_WDISPLAYMODE_SKELETON,
            "Skeleton")

        bc.SetContainer(c4d.DESC_CYCLE, cycle)

        return bc
Esempio n. 3
0
def CreateUserDataCycle(obj,
                        name,
                        link,
                        cycle,
                        parentGroup=None,
                        shortname=None,
                        unit=c4d.DESC_UNIT_INT):
    if obj is None: return False
    if shortname is None: shortname = name
    bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_LONG)
    bc.SetInt32(c4d.DESC_CUSTOMGUI, c4d.CUSTOMGUI_CYCLE)
    cycleContainer = c4d.BaseContainer()
    for i, c in enumerate(cycle):
        cycleContainer.SetString(i, c)
    bc[c4d.DESC_CYCLE] = cycleContainer
    bc[c4d.DESC_NAME] = name
    bc[c4d.DESC_SHORT_NAME] = shortname
    bc[c4d.DESC_DEFAULT] = link
    bc[c4d.DESC_ANIMATE] = c4d.DESC_ANIMATE_OFF
    bc[c4d.DESC_SHADERLINKFLAG] = True
    if parentGroup is not None:
        bc[c4d.DESC_PARENTGROUP] = parentGroup
    element = obj.AddUserData(bc)
    obj[element] = link
    return element
Esempio n. 4
0
def CreateFilepath(obj, itemName="Filepath", overwrite=False):
    """
    Create a new UserData item of type "Link" and add it to the UserDataContainer of the specified object.

    Args:
        obj (c4d.BaseObject): The Cinema4D object to add UserData to.
        [optional] itemName (str): The name of the UserData item to be created. Default is "Filepath".
        [optional] overwrite: Whether to overwrite any existing identical UserData. False by default.
    Returns:
        True on success, False on failure
    """

    if obj == None:
        return False

    UserData = obj.GetUserDataContainer()

    if itemName == None: itemName = "Filepath" + str(len(UserData))

    if UserDataExists(obj, itemName):
        if overwrite == False:
            return False
        else:
            DestroyUserData(obj, itemName)

    BaseContainer = c4d.GetCustomDatatypeDefault(c4d.DTYPE_FILENAME)
    BaseContainer[c4d.DESC_NAME] = itemName
    BaseContainer[c4d.DESC_SHORT_NAME] = itemName

    item = obj.AddUserData(BaseContainer)

    return True
Esempio n. 5
0
    def build_finger_controllers(self):

        for dir in Directions:
            obj = doc.SearchObject('Root_Controls')

            for finger in IndexName:

                #userdata
                bc = c4d.GetCustomDataTypeDefault(c4d.DTYPE_REAL)
                bc[c4d.DESC_NAME] = dir + finger + 'Finger'
                bc[c4d.DESC_UNIT] = c4d.DESC_UNIT_DEGREE
                bc[c4d.DESC_MIN] = 0
                bc[c4d.DESC_MAX] = math.radians(360)
                bc[c4d.DESC_STEP] = math.radians(1)
                bc[c4d.DESC_CUSTOMGUI] = c4d.CUSTOMGUI_REALSLIDER
                element1 = obj.AddUserData(bc)
                obj[element1] = 0

                # Assign Tick
                bc = c4d.GetCustomDatatypeDefault(
                    c4d.DTYPE_BOOL)  # Create default container
                bc[c4d.DESC_NAME] = dir + finger + 'Controlled'
                # Rename the entry
                element2 = obj.AddUserData(bc)
                # Add userdata container
                obj[element2] = 0
Esempio n. 6
0
def main():
    # Gets the TakeData from the active document (holds all information about Takes)
    takeData = doc.GetTakeData()
    if takeData is None:
        raise RuntimeError("Failed to retrieve the take data.")

    # Gets the active Take and check it's not the main one
    take = takeData.GetCurrentTake()
    if take.IsMain():
        raise RuntimeError("The selected take is already the main one.")

    # Creates a Custom Bool Datatype
    bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_BOOL)
    if bc is None:
        raise RuntimeError("Failed to create a BaseContainer.")
    bc[c4d.DESC_NAME] = "Enable"

    # Adds an User Data to the Take
    userData = take.AddUserData(bc)

    # Sets the value to True
    take.SetParameter(userData, True, c4d.DESCFLAGS_SET_0)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
Esempio n. 7
0
def CreateUserData(obj, itemName, itemtype, overwrite=False):
    """ 
    Create a new UserData item and add it to the UserDataContainer of the specified object.

    Args:
        obj (c4d.BaseObject): The Cinema4D object to add UserData to.
        itemName (str): The name of the UserData item to be created.
        itemtype: The data type of the UserData item to be created. Available DataTypes:
            c4d.DTYPE_BASELISTLINK  (BaseList2D).
            c4d.DTYPE_BOOL  (bool).
            c4d.DTYPE_BUTTON    (Button).
            c4d.DTYPE_CHILDREN  (Children).
            c4d.DTYPE_COLOR (Color).
            c4d.DTYPE_DYNAMIC   (GV dynamic).
            c4d.DTYPE_FILENAME  (str).
            c4d.DTYPE_GROUP (Group).
            c4d.DTYPE_LONG  (long).
            c4d.DTYPE_MATRIX    (Matrix)
            c4d.DTYPE_MULTIPLEDATA  (Multiple data entry).
            c4d.DTYPE_NONE  (None).
            c4d.DTYPE_NORMAL    (Normal).
            c4d.DTYPE_POPUP (Popup).
            c4d.DTYPE_REAL  (float)
            c4d.DTYPE_SEPARATOR (Separator).
            c4d.DTYPE_STATICTEXT    (Static text).
            c4d.DTYPE_STRING    (str).
            c4d.DTYPE_SUBCONTAINER  (BaseContainer).
            c4d.DTYPE_TEXTURE   (Texturename).
            c4d.DTYPE_TIME  (BaseTime).
            c4d.DTYPE_VECTOR    (Vector).
        overwrite: Whether to overwrite any existing UserData with same name. False by default
    Returns:
        True on success, False on failure
     """
    if obj == None: return
    if itemtype == None: itemtype = c4d.NONE

    UserData = obj.GetUserDataContainer()
    if itemName == None: itemName = "User Data" + str(len(UserData))

    if UserDataExists(obj, itemName):
        if overwrite == False:
            return
        else:
            DestroyUserData(obj, itemName)

    BaseContainer = c4d.GetCustomDatatypeDefault(itemtype)
    BaseContainer[c4d.DESC_NAME] = itemName
    BaseContainer[c4d.DESC_SHORT_NAME] = itemName

    if itemtype == c4d.DTYPE_BUTTON:
        BaseContainer[c4d.DESC_CUSTOMGUI] = c4d.CUSTOMGUI_BUTTON

    if itemtype == c4d.DTYPE_SEPARATOR:
        BaseContainer[c4d.DESC_CUSTOMGUI] = c4d.CUSTOMGUI_SEPARATOR

    item = obj.AddUserData(BaseContainer)

    return True
Esempio n. 8
0
def CreateIntegerData(obj,
                      itemName="Integer",
                      interface=c4d.CUSTOMGUI_LONG,
                      _min=None,
                      _max=None,
                      step=1,
                      overwrite=False):
    """
    Create a new UserData item of type "Integer" and add it to the UserDataContainer of the specified object.

    Args:
        obj (c4d.BaseObject): The Cinema4D object to add UserData to.
        itemName (str): The name of the UserData item to be created. Default is "Integer".
        interface (str or int): The type of the User Interface to implement for this User Data item. Can be "Integer" or "Integer Slider". Default is "Integer"
        _min (float): The minimum allowed value for this UserData item. 0.0 by default.
        _max (float): The maximum allowed value for this UserData item. 1.0 by default.
        _step (float): The step value for each UI nudge. 0.01 by default.
        units (str): The units in which the float value is expressed. Can be "Real" , "Percent" , "Degrees" or "Meters". "Real" by default.
        overwrite: Whether to overwrite any existing identical UserData. False by default.
    Returns:
        True on success, False on failure
    """

    if obj == None: return False

    if isinstance(interface, str):
        interface = D.IntegerInterface[interface]

    UserData = obj.GetUserDataContainer()

    if UserDataExists(obj, itemName):
        if overwrite == False:
            return False
        else:
            DestroyUserData(obj, itemName)

    if not interface == c4d.CUSTOMGUI_CYCLE or interface == c4d.CUSTOMGUI_CYCLEBUTTON:

        BaseContainer = c4d.GetCustomDatatypeDefault(c4d.DTYPE_LONG)
        BaseContainer[c4d.DESC_NAME] = itemName
        BaseContainer[c4d.DESC_SHORT_NAME] = itemName
        BaseContainer[c4d.DESC_CUSTOMGUI] = interface

        if _min != None:
            BaseContainer[c4d.DESC_MIN] = _min
        if _max != None:
            BaseContainer[c4d.DESC_MAX] = _max

        BaseContainer[c4d.DESC_STEP] = step
        BaseContainer[c4d.DESC_UNIT] = c4d.DESC_UNIT_LONG

        item = obj.AddUserData(BaseContainer)

        return True

    return False
Esempio n. 9
0
def CreateFloatData(obj,
                    itemName="Float",
                    interface=c4d.CUSTOMGUI_REAL,
                    _min=None,
                    _max=None,
                    step=0.01,
                    units="Real",
                    overwrite=False):
    """
    Create a new UserData item of type "Float" and add it to the UserDataContainer of the specified object.

    Args:
        obj (c4d.BaseObject): The Cinema4D object to add UserData to.
        [optional] itemName (str): The name of the UserData item to be created. Default is "Float".
        [optional] interface (str): The type of the User Interface to implement for this User Data item. Can be "Float" , "Float Slider" or "Float Slider No EditField" . Default is "Float".
        [optional] _min (float): The minimum allowed value for this UserData item. 0.0 by default.
        [optional] _max (float): The maximum allowed value for this UserData item. 1.0 by default.
        [optional] _step (float): The step value for each UI nudge. 0.01 by default.
        [optional] units (str or int): The units in which the float value is expressed. Can be "Real", "Percent", "Degrees" or "Meters". "Real" by default.
        [optional] overwrite: Whether to overwrite any existing identical UserData. False by default.
    Returns:
        True on success, False on failure
    """

    if obj == None: return False

    if isinstance(interface, str):
        interface = D.FloatInterface[interface]

    if isinstance(units, str):
        units = D.FloatUnits[units]

    if UserDataExists(obj, itemName):
        if overwrite == False:
            return False
        else:
            DestroyUserData(obj, itemName)

    BaseContainer = c4d.GetCustomDatatypeDefault(c4d.DTYPE_REAL)
    BaseContainer[c4d.DESC_NAME] = itemName
    BaseContainer[c4d.DESC_SHORT_NAME] = itemName

    if _min != None:
        BaseContainer[c4d.DESC_MIN] = _min
    if _max != None:
        BaseContainer[c4d.DESC_MAX] = _max

    BaseContainer[c4d.DESC_STEP] = step

    BaseContainer[c4d.DESC_CUSTOMGUI] = interface
    BaseContainer[c4d.DESC_UNIT] = units

    item = obj.AddUserData(BaseContainer)

    return True
Esempio n. 10
0
def dataAddVector(obj, name, parent, unit, step, Min, default):
    ud = c4d.GetCustomDatatypeDefault(c4d.DTYPE_VECTOR)
    ud[c4d.DESC_NAME] = name
    ud[c4d.DESC_UNIT] = unit
    ud[c4d.DESC_STEP] = step
    ud[c4d.DESC_MIN] = Min
    ud[c4d.DESC_MAXEX] = False
    ud[c4d.DESC_DEFAULT] = default
    ud[c4d.DESC_PARENTGROUP] = parent
    uid = obj.AddUserData(ud)
    obj[uid] = default
Esempio n. 11
0
def CreateUserDataString(obj, name, link, parentGroup=None, shortname=None):
    if obj is None: return False
    if shortname is None: shortname = name
    bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_STRING)
    bc[c4d.DESC_NAME] = name
    bc[c4d.DESC_SHORT_NAME] = shortname
    bc[c4d.DESC_DEFAULT] = link
    bc[c4d.DESC_ANIMATE] = c4d.DESC_ANIMATE_OFF
    bc[c4d.DESC_SHADERLINKFLAG] = True
    if parentGroup is not None:
        bc[c4d.DESC_PARENTGROUP] = parentGroup
    element = obj.AddUserData(bc)
    obj[element] = link
    return element
def CreateUserDataLink(obj, name, link, parentGroup=None, shortname=None):
    """ Create user data link """
    if obj is None: return False # If there is no object stop the function
    if shortname is None: shortname = name # Short name is name
    bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_BASELISTLINK) # Initialize user data
    bc[c4d.DESC_NAME] = name # Set user data name
    bc[c4d.DESC_SHORT_NAME] = shortname # Set userdata short name
    bc[c4d.DESC_DEFAULT] = link # Set default value
    bc[c4d.DESC_ANIMATE] = c4d.DESC_ANIMATE_OFF # Disable animation option
    bc[c4d.DESC_SHADERLINKFLAG] = True
    if parentGroup is not None: # If there is parent group
        bc[c4d.DESC_PARENTGROUP] = parentGroup # Set parent group
    element = obj.AddUserData(bc) # Add user data
    obj[element] = link # Set user data value
    return element # Return user data field
Esempio n. 13
0
def CreateDropDown(obj,
                   itemName="DropDown",
                   interface=c4d.CUSTOMGUI_CYCLE,
                   data=["A", "B", "C"],
                   overwrite=False):
    """
    Create a new UserData item of type "Integer" and add it to the UserDataContainer of the specified object.

    Args:
        obj (c4d.BaseObject): The Cinema4D object to add UserData to.
        itemName (str): The name of the UserData item to be created. Default is "DropDown".
        interface (str or int): The type of the User Interface to implement for this User Data item. Can be "Cycle" or "Cycle Button". Default is "Cycle"
        data ([str]): A list of strings representing the different values of the Dropdown list.
        overwrite: Whether to overwrite any existing identical UserData. False by default.
    Returns:
        True on success, False on failure
    """

    if obj == None: return False

    if isinstance(interface, str):
        interface = D.IntegerInterface[interface]

    UserData = obj.GetUserDataContainer()

    if UserDataExists(obj, itemName):
        if overwrite == False:
            return False
        else:
            DestroyUserData(obj, itemName)

    if interface == c4d.CUSTOMGUI_CYCLE or interface == c4d.CUSTOMGUI_CYCLEBUTTON:

        BaseContainer = c4d.GetCustomDatatypeDefault(c4d.DTYPE_LONG)
        BaseContainer[c4d.DESC_NAME] = itemName
        BaseContainer[c4d.DESC_SHORT_NAME] = itemName
        BaseContainer[c4d.DESC_CUSTOMGUI] = interface

        cycle = c4d.BaseContainer()
        for index in range(0, len(data)):
            cycle.SetString(index, data[index])

        BaseContainer.SetContainer(c4d.DESC_CYCLE, cycle)

        item = obj.AddUserData(BaseContainer)
        return True

    return False
def CreateUserDataFloat(obj,
                        name,
                        val=0,
                        parentGroup=None,
                        unit=c4d.DESC_UNIT_REAL):
    if obj is None: return False
    bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_REAL)
    bc[c4d.DESC_NAME] = name
    bc[c4d.DESC_SHORT_NAME] = name
    bc[c4d.DESC_DEFAULT] = val
    bc[c4d.DESC_ANIMATE] = c4d.DESC_ANIMATE_ON
    bc[c4d.DESC_UNIT] = unit
    bc[c4d.DESC_STEP] = 2
    if parentGroup is not None:
        bc[c4d.DESC_PARENTGROUP] = parentGroup
    element = obj.AddUserData(bc)
    obj[element] = val
    return element
Esempio n. 15
0
    def add_path_group(self, morph_ctrl, morph_link):
        path = str(morph_link["Path"])
        path = path.replace("//", "/")
        group_names = path.split("/")
        parent = None
        for grp_name in group_names:
            grp_name = str(grp_name)
            user_id = self.find_user_data_by_name(morph_ctrl, grp_name)
            if not user_id:
                group = c4d.GetCustomDatatypeDefault(c4d.DTYPE_GROUP)
                group[c4d.DESC_NAME] = grp_name
                group[c4d.DESC_PARENTGROUP] = parent
                group[c4d.DESC_DEFAULT] = c4d.DESC_GUIOPEN

                parent = morph_ctrl.AddUserData(group)
            else:
                parent = user_id
        return parent
    def PopupSDISPLAYMODE(self):

        bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_LONG)

        bc.SetInt32(c4d.DESC_CUSTOMGUI, c4d.CUSTOMGUI_CYCLE)
        bc.SetInt32(c4d.DESC_MIN, 0)
        bc.SetInt32(c4d.DESC_MAX, 7)

        cycle = c4d.BaseContainer()

        cycle.SetString(
            c4d.
            SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_SDISPLAYMODE_GOURAUD_SHADING,
            "Gouraud Shading")
        cycle.SetString(
            c4d.
            SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_SDISPLAYMODE_GOURAUD_SHADING_LINES,
            "Gouraud Shading (Lines)")
        cycle.SetString(
            c4d.
            SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_SDISPLAYMODE_QUICK_SHADING,
            "Quick Shading")
        cycle.SetString(
            c4d.
            SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_SDISPLAYMODE_QUICK_SHADING_LINES,
            "Quick Shading (Lines)")
        cycle.SetString(
            c4d.
            SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_SDISPLAYMODE_CONSTANT_SHADING,
            "Constant Shading")
        cycle.SetString(
            c4d.
            SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_SDISPLAYMODE_CONSTANT_SHADING_LINES,
            "Constant Shading (Lines)")
        cycle.SetString(
            c4d.SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_SDISPLAYMODE_HIDDEN,
            "Hidden Line")
        cycle.SetString(
            c4d.SMALL_FAR_AWAY_SHADING_MODE_CONTROLLER_SDISPLAYMODE_LINES,
            "Lines")

        bc.SetContainer(c4d.DESC_CYCLE, cycle)

        return bc
def main():

    takeData = doc.GetTakeData()
    if takeData is None:
        return

    take = takeData.GetCurrentTake()
    if take is None:
        return

    # This example adds a new boolean userdata parameter to the given BaseTake.

    bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_BOOL)
    bc[c4d.DESC_NAME] = "Enable"

    userData = take.AddUserData(bc)
    take.SetParameter(userData, True, c4d.DESCFLAGS_SET_0)

    c4d.EventAdd()
Esempio n. 18
0
def main():
    # get Active Objects
    activeObjects = doc.GetActiveObjects(c4d.GETACTIVEOBJECTFLAGS_CHILDREN)
    if not activeObjects:
        gui.MessageDialog('Please select one or more objects.')
        return

    # user input dialog
    cryptoinput_dlg = cryptoinput_dialog()
    if cryptoinput_dlg == False:
        return

    # list iterator
    i = 0

    for obj in activeObjects:
        if cryptoinput_dlg[4] == True:
            i += 1
        else:
            i = 0

        userdata = obj.GetUserDataContainer()

        # skip when the user data is already added
        skip = False
        for id, bc in obj.GetUserDataContainer():
            if bc[c4d.DESC_NAME] == cryptoinput_dlg[2]:
                skip = True
                break

        # add the new user data
        if skip is False:
            bc = c4d.GetCustomDatatypeDefault(c4d.DTYPE_STRING)
            bc[c4d.DESC_NAME] = cryptoinput_dlg[2]
            element2 = obj.AddUserData(bc)
            obj[element2] = "Obj 0" + str(i)
        else:
            gui.MessageDialog('User data %s already exists on object %s.' %
                              (cryptoinput_dlg[2], obj.GetName()))

    c4d.EventAdd()

    arnold_ops(cryptoinput_dlg)
Esempio n. 19
0
def main():

    sweepObj = c4d.BaseObject(c4d.Osweep)
    sweepObj[c4d.ID_BASELIST_NAME] = "Line"

    bc1 = c4d.GetCustomDatatypeDefault(c4d.DTYPE_GROUP)
    bc1[c4d.DESC_NAME] = "Ray Attribute"
    bc1[c4d.
        DESC_DEFAULT] = 1  # Make userdata group tab stay open in default-open-tab mode(Right mouse button click on an object tab).
    bc1[c4d.DESC_PARENTGROUP] = c4d.DescID(
        0)  # Put this group as a table of the object

    [bc2, bc4
     ] = [c4d.GetCustomDatatypeDefault(c4d.DTYPE_BOOL) for i in range(0, 2)]
    [bc3, bc5] = [
        c4d.GetCustomDatatypeDefault(c4d.CUSTOMDATATYPE_INEXCLUDE_LIST)
        for i in range(0, 2)
    ]
    bc2[c4d.DESC_NAME] = "From Point"
    bc3[c4d.DESC_NAME] = "From Objects List"
    bc4[c4d.DESC_NAME] = "To Point"
    bc5[c4d.DESC_NAME] = "To Objects List"

    DesID1 = sweepObj.AddUserData(
        bc1
    )  # Get root user group description ID for other insertions, and active tab

    for item in [bc2, bc3, bc4, bc5]:
        item[c4d.DESC_PARENTGROUP] = DesID1
        sweepObj.AddUserData(item)

    contourSpline = c4d.BaseObject(c4d.Osplinenside)
    contourSpline[c4d.PRIM_NSIDE_RADIUS] = 5

    raySpline = c4d.BaseObject(c4d.Ospline)

    # Init a empty spline
    raySpline.ResizeObject(0, 0)

    for item in [raySpline, contourSpline]:
        item.InsertUnder(sweepObj)

    # Core code in python tag
    pythonTag = c4d.BaseTag(c4d.Tpython)
    pythonTag[c4d.ID_BASELIST_NAME] = "Auto Connection Updater"
    pythonTag[c4d.TPYTHON_CODE] = (
        """# Description: A script to create a multiple connector to connect between two group of objects
# Author: eZioPan
# Page: github.com/eZioPan
# License: Creative Commons Attribution Share Alike 4.0
# Version: 0.2.0
# Last Update: 2018Oct22

import c4d
from c4d.modules import mograph as mo

lastState = False       # track last running state

# filter non-exist objects out of result object list
def extractInExData(inExData):
    output = []
    inExLen = inExData.GetObjectCount()
    for i in range(0,inExLen):
        obj = inExData.ObjectFromIndex(doc,i)
        # check both InExcludeData.GetObjectCount() and InExcludeData.ObjectFromIndex() to get actual objects in list.
        if obj == None:
            continue
        output.append(obj)
    return output

# extract point postion information on demand
def GetGroupPointsPos(objLs=[], usePoint=False):
    posLs = []
    for obj in objLs:
        objMg = obj.GetMg()
        if usePoint == False or obj.GetType() == c4d.Onull:
             posLs.append(objMg.off)
        elif obj.IsInstanceOf(c4d.Obasemogen):
            md = mo.GeGetMoData(obj)
            moMatrixLs = md.GetArray(c4d.MODATA_MATRIX)
            for moMatrix in moMatrixLs:
                point = moMatrix.off
                posLs.append(objMg*point)
        else:
            pointPosLs = obj.GetCache().GetDeformCache().GetAllPoints()
            for point in pointPosLs:
                posLs.append(objMg*point)
    return posLs

# modify line data from point position
def SetLinePointPos(lineObj, fromPosLs, toPosLs):
    fromPosCnt = len(fromPosLs)
    toPosCnt = len(toPosLs)
    rayCnt = max(fromPosCnt, toPosCnt)

    iLineMg = ~(lineObj.GetMg()) # Invert carrier global matrix

    # apply invert carrier matrix to all point position
    for i in range(fromPosCnt):
        fromPosLs[i] = iLineMg * fromPosLs[i]
    for i in range(toPosCnt):
        toPosLs[i] = iLineMg * toPosLs[i]

    lineObj.ResizeObject(2*rayCnt, rayCnt)

    for i in range(rayCnt):
        lineObj.SetSegment(id=i, cnt=2, closed=False)

    if fromPosCnt <= toPosCnt:
        for i in range(toPosCnt):
            pairNum = i % fromPosCnt
            lineObj.SetPoint(i*2, fromPosLs[pairNum-1])
            lineObj.SetPoint(i*2+1, toPosLs[i])
    else:
        for i in range(fromPosCnt):
            pairNum = i % toPosCnt
            lineObj.SetPoint(i*2, fromPosLs[i])
            lineObj.SetPoint(i*2+1, toPosLs[pairNum-1])

def main():

    global lastState

    sweepObj = op.GetObject()
    lineObj = sweepObj.GetDown().GetNext()
    fromPoint = sweepObj[c4d.ID_USERDATA,2]
    fromInExData = sweepObj[c4d.ID_USERDATA,3]
    toPoint = sweepObj[c4d.ID_USERDATA,4]
    toInExData = sweepObj[c4d.ID_USERDATA,5]

    fromLs = extractInExData(fromInExData)
    toLs = extractInExData(toInExData)

    if len(fromLs) == 0 or len(toLs) == 0:
        if lastState == True: # do not pour garbage into console, or refresh scene too fast.
            lineObj.ResizeObject(0,1)   # clean spline data if nothing to generate.
            lineObj.Message(c4d.MSG_UPDATE)
            print("[RayConnector] Not enough Objects.")
            lastState = False
        return None           # Terminate execution

    if lastState == False:              # do not pour garbage into console
        lastState = True
        print("[RayConnector] OK.")

    fromPosLs = GetGroupPointsPos(fromLs,fromPoint)
    toPosLs = GetGroupPointsPos(toLs,toPoint)

    SetLinePointPos(lineObj, fromPosLs, toPosLs)

    lineObj.Message(c4d.MSG_UPDATE)     # Update points change of object

    return True
""")

    intActTag = c4d.BaseTag(c4d.Tinteraction)
    intActTag[c4d.ID_BASELIST_NAME] = "Disable Viewport Selection"
    intActTag[c4d.INTERACTIONTAG_SELECT] = True

    for tag in [pythonTag, intActTag]:
        sweepObj.InsertTag(tag)

    doc = c4d.documents.GetActiveDocument()
    doc.StartUndo()
    doc.InsertObject(sweepObj)
    doc.SetActiveObject(sweepObj, mode=c4d.SELECTION_NEW)
    c4d.gui.ActiveObjectManager_SetObject(  # Change active tab after insert into scene
        id=c4d.ACTIVEOBJECTMODE_OBJECT,
        op=sweepObj,
        flags=c4d.ACTIVEOBJECTMANAGER_SETOBJECTS_NOMODESWITCH,
        activepage=DesID1)
    doc.AddUndo(c4d.UNDOTYPE_NEW, item)
    doc.EndUndo()
    c4d.EventAdd()
def main():

    fromObj = c4d.BaseObject(c4d.Onull)
    fromObj[c4d.ID_BASELIST_NAME] = "FromLoc"
    fromObj[c4d.NULLOBJECT_RADIUS] = 20

    toObj = c4d.BaseObject(c4d.Onull)
    toObj[c4d.ID_BASELIST_NAME] = "ToLoc"
    toObjoff = c4d.Vector(0, 0, 0)
    toObjv1 = c4d.Vector(-1, 0, 0)
    toObjv2 = c4d.Vector(0, 0.8, 0)
    toObjv3 = c4d.Vector(0, 0, -1)
    toObj.SetMg(c4d.Matrix(toObjoff, toObjv1, toObjv2, toObjv3))
    toObj[c4d.NULLOBJECT_RADIUS] = 16

    # Set Pyramid shape of locator
    for item in [fromObj, toObj]:
        item[c4d.NULLOBJECT_DISPLAY] = 12
        item[c4d.NULLOBJECT_ORIENTATION] = 3

    sweepObj = c4d.BaseObject(c4d.Osweep)
    sweepObj[c4d.ID_BASELIST_NAME] = "Line"

    bc1 = c4d.GetCustomDatatypeDefault(c4d.DTYPE_GROUP)
    bc1[c4d.DESC_NAME] = "Ray Attribute"
    bc1[c4d.DESC_PARENTGROUP] = c4d.DescID(
        0)  # Put this group as a table of the object

    [bc2, bc3] = [
        c4d.GetCustomDatatypeDefault(c4d.DTYPE_BASELISTLINK)
        for i in range(0, 2)
    ]
    bc2[c4d.DESC_NAME] = "From Object"
    bc3[c4d.DESC_NAME] = "To Object"

    [bc4, bc5
     ] = [c4d.GetCustomDatatypeDefault(c4d.DTYPE_REAL) for i in range(0, 2)]
    bc4[c4d.DESC_NAME] = "Start Distance"
    bc5[c4d.DESC_NAME] = "End Distance"

    # Set default spline data
    bc6 = c4d.GetCustomDatatypeDefault(c4d.CUSTOMDATATYPE_SPLINE)
    bc6[c4d.DESC_NAME] = "Length Ratio Remap"

    bc7 = c4d.GetCustomDatatypeDefault(c4d.DTYPE_BOOL)
    bc7[c4d.DESC_NAME] = "Positive Z Only"

    # Get root user group description ID for other insertions
    DesID1 = sweepObj.AddUserData(bc1)

    for item in [bc2, bc3, bc4, bc5, bc6, bc7]:
        item[c4d.DESC_PARENTGROUP] = DesID1
        sweepObj.AddUserData(item)

    sweepObj[c4d.ID_USERDATA, 2] = fromObj

    sweepObj[c4d.ID_USERDATA, 3] = toObj

    sweepObj[c4d.ID_USERDATA, 5] = 500

    # Set customized spline user data
    initSplineData = c4d.SplineData()
    initSplineData.DeleteAllPoints()

    initSplineData.MakePointBuffer(4)

    for knot in [[0, 0, 0], [1, 0.2, 1], [2, 0.8, 1], [3, 1, 0]]:
        initSplineData.SetKnot(
            index=knot[0],
            vPos=c4d.Vector(knot[1], knot[2], 0),
            lFlagsSettings=c4d.FLAG_KNOT_T_KEEPVISUALANGLE,
            vTangentLeft=c4d.Vector(-0.05, 0, 0),
            vTangentRight=c4d.Vector(0.05, 0, 0),
            interpol=c4d.CustomSplineKnotInterpolationBezier)

    # Replace default spline data with customized one
    sweepObj[c4d.ID_USERDATA, 6] = initSplineData

    contourSpline = c4d.BaseObject(c4d.Osplinenside)

    contourSpline[c4d.PRIM_NSIDE_RADIUS] = 5

    raySpline = c4d.BaseObject(c4d.Ospline)

    # Init a 2 points spline
    raySpline.ResizeObject(2, 0)

    for item in [raySpline, contourSpline]:
        item.InsertUnder(sweepObj)

    # Core code in python tag
    pythonTag = c4d.BaseTag(c4d.Tpython)
    pythonTag[c4d.DESC_NAME] = "AutoConnectionUpdater"
    pythonTag[c4d.TPYTHON_CODE] = (
        """# Description: A script to create a ray connector to connect two objects
# Author: eZioPan
# Page: github.com/eZioPan
# License: Creative Commons Attribution Share Alike 4.0

import c4d
def main():
    sweepObj = op.GetObject()
    lineObj = op.GetObject().GetDown().GetNext()
    objFrom = sweepObj[c4d.ID_USERDATA,2]
    objTo = sweepObj[c4d.ID_USERDATA,3]
    startDistance = sweepObj[c4d.ID_USERDATA,4]
    endDistance = sweepObj[c4d.ID_USERDATA,5]
    mapperSpline = sweepObj[c4d.ID_USERDATA,6]
    positiveChecker = sweepObj[c4d.ID_USERDATA,7]

    if objFrom == None or objTo == None:
        print("Not enough Object")
        return None

    if startDistance == endDistance:
        print("same value at startDistance and endDistance")
        return None

    objFromPos = objFrom.GetMg().off
    objFromZ = objFrom.GetMg().v3
    objToPos = objTo.GetMg().off

    lineObj.SetPoint(0,objFromPos)
    lineObj.SetPoint(1,objToPos)
    lineObj.Message(c4d.MSG_UPDATE)     # Update point change of object

    ratio = 0

    # Get distance of two objects in From Object's Z direction
    dotProducted = objFromZ.GetNormalized().Dot(objToPos-objFromPos)
    if positiveChecker == False or dotProducted > 0:
        dis = abs(dotProducted)
        ratio = mapperSpline.GetPoint((dis-startDistance)/(endDistance-startDistance))[1]
    sweepObj[c4d.SWEEPOBJECT_GROWTH] = ratio
    return True
""")
    sweepObj.InsertTag(pythonTag)

    doc = c4d.documents.GetActiveDocument()
    doc.StartUndo()
    for item in [sweepObj, toObj, fromObj]:
        doc.InsertObject(item)
        doc.AddUndo(c4d.UNDOTYPE_NEW, item)
    doc.EndUndo()
    doc.SetActiveObject(sweepObj, mode=c4d.SELECTION_NEW)
    c4d.EventAdd()
Esempio n. 21
0
def createNewUserData(mainDialog, newContainer):

    newXpressoTag = newContainer.MakeTag(1001149)
    nodemaster = newXpressoTag.GetNodeMaster()  #Generates xpresso nodes
    controllerNode = nodemaster.CreateNode(
        nodemaster.GetRoot(), c4d.ID_OPERATOR_OBJECT, insert=None, x=20,
        y=50)  #create condition node and place in X,Y coord
    controllerNode.GetOperatorContainer()
    mainNode = nodemaster.CreateNode(
        nodemaster.GetRoot(), c4d.ID_OPERATOR_OBJECT, insert=None, x=300,
        y=0)  #create condition node and place in X,Y coord
    mainNode.GetOperatorContainer()
    #nodeporst=node1.GetInPorts()
    #node2 = nodemaster.CreateNode(nodemaster.GetRoot(), c4d.ID_OPERATOR_OBJECT, insert=None, x=100, y=200) #create Object node and place in X,Y coord
    #node2.AddPort(c4d.GV_PORT_INPUT, c4d.ID_BASEOBJECT_POSITION) #add a position input port to the object node
    #node1out=node2.AddPort(c4d.GV_PORT_OUTPUT, c4d.ID_BASEOBJECT_REL_POSITION) #add a position output port to the object node

    xpressoNode = nodemaster.CreateNode(
        nodemaster.GetRoot(), c4d.ID_OPERATOR_OBJECT, insert=None, x=500,
        y=0)  #create condition node and place in X,Y coord
    xpressoNode[c4d.GV_OBJECT_OBJECT_ID] = newXpressoTag
    blendShapeNames = names.blendShapeNames
    shapeCount = 0
    bc = c4d.GetCustomDatatypeDefault(
        c4d.DTYPE_BASELISTLINK)  #create default container
    bc[c4d.DESC_NAME] = "ControllerObject"
    bc[c4d.DESC_CUSTOMGUI] = c4d.CUSTOMGUI_LINKBOX
    element = newContainer.AddUserData(bc)  #add userdata container
    newContainer[element] = newContainer
    newPortDataOut = controllerNode.AddPort(c4d.GV_PORT_OUTPUT, element)
    mainDialog.blendShapeTargets = []
    while shapeCount < len(blendShapeNames):
        bc = c4d.GetCustomDatatypeDefault(
            c4d.DTYPE_REAL)  #create default container
        bc[c4d.DESC_NAME] = blendShapeNames[shapeCount]
        bc[c4d.DESC_UNIT] = c4d.DESC_UNIT_PERCENT
        bc[c4d.DESC_MIN] = 0.0
        bc[c4d.DESC_MAX] = 1.0
        bc[c4d.DESC_STEP] = 0.01
        bc[c4d.DESC_CUSTOMGUI] = c4d.CUSTOMGUI_REALSLIDER
        element = newContainer.AddUserData(bc)  #add userdata container
        bc = c4d.GetCustomDatatypeDefault(
            c4d.DTYPE_REAL)  #create default container
        bc[c4d.DESC_NAME] = blendShapeNames[shapeCount]
        #bc[c4d.DESC_UNIT] = c4d.DESC_UNIT_PERCENT
        bc[c4d.DESC_MIN] = 0.0
        bc[c4d.DESC_MAX] = 200.0
        bc[c4d.DESC_MAXSLIDER] = 2.0
        bc[c4d.DESC_STEP] = 0.0001
        bc[c4d.DESC_CUSTOMGUI] = c4d.CUSTOMGUI_REALSLIDER
        element2 = newXpressoTag.AddUserData(bc)  #add userdata container
        newXpressoTag[element2] = 1
        newPort = mainNode.AddPort(
            c4d.GV_PORT_OUTPUT,
            element)  #add a position output port to the object node
        newPort2 = xpressoNode.AddPort(
            c4d.GV_PORT_OUTPUT,
            element2)  #add a position output port to the object node
        mathNode = nodemaster.CreateNode(
            nodemaster.GetRoot(),
            c4d.ID_OPERATOR_MATH,
            insert=None,
            x=700,
            y=shapeCount * 60)  #create condition node and place in X,Y coord
        mathNode[c4d.GV_MATH_FUNCTION_ID] = 2
        mathNode[c4d.ID_BASELIST_NAME] = blendShapeNames[shapeCount]
        mathNode.GetOutPorts()[0].SetName(blendShapeNames[shapeCount])
        nodemaster.Message(c4d.MSG_UPDATE)
        newPort.Connect(mathNode.GetInPorts()[0])
        newPort2.Connect(mathNode.GetInPorts()[1])
        #print (element)
        mainDialog.blendShapeTargets.append(element)
        shapeCount += 1
    eyeGazeNames = names.eyeGazeNames
    eyeGazeCount = 0
    mainDialog.eyeGazeTargets = []
    while eyeGazeCount < len(eyeGazeNames):
        bc = c4d.GetCustomDatatypeDefault(
            c4d.DTYPE_REAL)  #create default container
        bc[c4d.DESC_NAME] = eyeGazeNames[eyeGazeCount]
        bc[c4d.DESC_UNIT] = c4d.DESC_UNIT_REAL
        bc[c4d.DESC_MIN] = -90.0
        bc[c4d.DESC_MAX] = 90.0
        bc[c4d.DESC_STEP] = 0.01
        bc[c4d.DESC_CUSTOMGUI] = c4d.CUSTOMGUI_REALSLIDER
        element = newContainer.AddUserData(bc)  #add userdata container
        newPort = mainNode.AddPort(
            c4d.GV_PORT_OUTPUT,
            element)  #add a position output port to the object node
        mainDialog.eyeGazeTargets.append(element)
        eyeGazeCount += 1

    c4d.modules.graphview.RedrawMaster(nodemaster)
    nodemaster.Message(c4d.MSG_UPDATE)
    c4d.EventAdd()
Esempio n. 22
0
def main():

    circle = c4d.SplineObject(pcnt=0, type=c4d.SPLINETYPE_BEZIER)
    circle[c4d.ID_BASELIST_NAME] = "Circle"
    circle[c4d.SPLINEOBJECT_CLOSED] = True

    bc0 = c4d.GetCustomDatatypeDefault(c4d.DTYPE_GROUP)
    bc0[c4d.DESC_NAME] = "Circle Attribute"
    bc0[c4d.DESC_DEFAULT] = 1
    bc0[c4d.DESC_PARENTGROUP] = c4d.DescID(0)

    DesID0 = circle.AddUserData(bc0)

    bc1 = c4d.GetCustomDatatypeDefault(c4d.DTYPE_REAL)
    bc1[c4d.DESC_NAME] = "Radius"
    bc1[c4d.DESC_DEFAULT] = 200
    bc1[c4d.DESC_MIN] = 0

    bc2 = c4d.GetCustomDatatypeDefault(c4d.DTYPE_LONG)
    bc2[c4d.DESC_NAME] = "Point Number"
    bc2[c4d.DESC_DEFAULT] = 4
    bc2[c4d.DESC_MIN] = 2

    DescIDLs = []
    for item in [bc1, bc2]:
        item[c4d.DESC_PARENTGROUP] = DesID0
        DescID = circle.AddUserData(item)
        DescIDLs.append(DescID)

    circle[DescIDLs[0]] = 200
    circle[DescIDLs[1]] = 4

    # Core code in python tag
    pythonTag = c4d.BaseTag(c4d.Tpython)
    pythonTag[c4d.ID_BASELIST_NAME] = "Circle Modifier"
    pythonTag[c4d.TPYTHON_CODE] = (
        """# Description: A script to create an arbitrary-number-of-point circle with bezier spline
# Author: eZioPan
# Page: github.com/eZioPan
# License: Creative Commons Attribution Share Alike 4.0
# Version: 0.0.1
# Last Update: 2018Nov2
import c4d, math
#Welcome to the world of Python

deg = math.pi/180.0

def main():

    circle = op.GetObject()

    pCnt = circle[c4d.ID_USERDATA,3]           # Here is the point count
    radius = circle[c4d.ID_USERDATA,2]         # Here is the radius of circle

    #Prepare the data
    tangentLength = (4/3)*math.tan(math.pi/(2*pCnt))*radius # single side tangent handle length
    pointPosLs = []
    tangentLs = []
    for i in range(0,pCnt):

        angle = i*(2*math.pi)/pCnt    # caculate the angle

        # caculate point position
        y = math.sin(angle)*radius
        x = math.cos(angle)*radius
        pointPosLs.append(c4d.Vector(x, y, 0))

        # tangent position
        lx = math.sin(angle)*tangentLength
        ly = -math.cos(angle)*tangentLength
        rx = -lx
        ry = -ly
        vl = c4d.Vector(lx, ly, 0)
        vr = c4d.Vector(rx, ry, 0)
        tangentLs.append([vl, vr])

    # resize bezier curve
    circle.ResizeObject(pcnt=pCnt, scnt=1)
    circle.SetSegment(id=0, cnt=pCnt, closed=True)

    circle.SetAllPoints(pointPosLs) # set point position

    # set tangent position
    for i in range(0, pCnt):
        circle.SetTangent(i, tangentLs[i][0], tangentLs[i][1])

    circle.Message(c4d.MSG_UPDATE)

    return circle
""")

    circle.InsertTag(pythonTag)
    doc = c4d.documents.GetActiveDocument()

    doc.StartUndo()
    doc.InsertObject(circle)
    doc.SetActiveObject(circle, mode=c4d.SELECTION_NEW)
    doc.AddUndo(c4d.UNDOTYPE_NEW, circle)
    doc.EndUndo()

    c4d.EventAdd()