Example #1
0
def main():
    # Checks if there is an active object and if it's a Cube object
    if op is None:
        raise ValueError("op is none, please select one object.")

    if not op.CheckType(c4d.Ocube):
        raise TypeError("The objects is not a cube.")

    # 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.")

    # Gets the DescID corresponding to the Cube size
    ID = c4d.DescID(c4d.DescLevel(c4d.PRIM_CUBE_LEN, c4d.DTYPE_VECTOR, 0),
                    c4d.DescLevel(c4d.VECTOR_X, c4d.DTYPE_REAL, 0))
    newValue = 300.0

    # Add an override if this parameter is not already overridden, otherwise returns the already existing override
    overrideNode = take.FindOrAddOverrideParam(takeData, op, ID, newValue)
    if overrideNode is None:
        raise RuntimeError("Failed to find the override node.")

    # Updates the scene with the new Take
    overrideNode.UpdateSceneNode(takeData, ID)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
Example #2
0
    def get_driver_output(self, link, node_master, x, y, pm_tag, driver_node):
        """Check which type of link it is a creates node and Output based on it

        Args:
            link (list): Information for one of the Bones/Morphs that Drives the output
            node_master (c4d.modules.graphview.GvNodeMaster):
                        represents the parent used for the Xpresso Group
            x (int): Horizontal Position of Node
            y (int): Vertical Position of Node

        Returns:
            driver_output (c4d.modules.graphview.GvPort): Output to connect to Python Node
        """
        joint_name = link["Bone"]
        prop = link["Property"]
        if joint_name != "None":
            # Create Joint Driver
            vector, rotation = self.find_vector(prop)
            joint = self.find_joint(joint_name)
            descid = c4d.DescID(
                c4d.DescLevel(rotation, 0, 0),
                c4d.DescLevel(vector, 0, 0),
            )
            driver_node = self.create_node(node_master, joint, x, y)
            driver_output = driver_node.AddPort(c4d.GV_PORT_OUTPUT, descid)
        else:
            morph_num = self.find_morph_id_by_name(pm_tag, prop)
            driver_output = driver_node.AddPort(c4d.GV_PORT_OUTPUT, morph_num)
            if driver_output is None:
                driver_output = self.nodes[self.body_name][prop]["Output2"]
            self.store_morph(self.body, driver_output, "Output2", prop)
        return driver_output
Example #3
0
    def set_matrix(self, matrix, frame):
        """

        :type frame: int
        :param frame:
        :type: Matrix
        :param matrix:
        :return:
        """
        transform = [
            matrix.get().off,
            c4d.utils.MatrixToHPB(matrix.get(),
                                  self.__object.GetRotationOrder()),
            matrix.get().GetScale()
        ]
        for i_type in range(3):
            for i_dir in range(3):
                desc_id = c4d.DescID(
                    c4d.DescLevel(ID_TYPES[i_type], c4d.DTYPE_VECTOR, 0),
                    c4d.DescLevel(ID_DIRS[i_dir], c4d.DTYPE_REAL, 0))
                track = self.__object.FindCTrack(desc_id)
                if track is None:
                    track = c4d.CTrack(self.__object, desc_id)
                    self.__object.InsertTrackSorted(track)
                curve = track.GetCurve()
                key = curve.AddKey(c4d.BaseTime(frame, get_fps()))['key']
                if key is None:
                    print('Error: Failed to add keys!')
                    continue
                track.FillKey(context_doc, self.__object, key)
                key.SetValue(curve, transform[i_type][i_dir])
def main():
    # Creates the object in memory
    obj = c4d.BaseObject(c4d.Ocube)

    # Creates the track in memory. Defined by it's DescID
    trackY = c4d.CTrack(obj, c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_POSITION, c4d.DTYPE_VECTOR, 0),
                                        c4d.DescLevel(c4d.VECTOR_Y, c4d.DTYPE_REAL, 0)))

    # Gets curves for the track
    curveY = trackY.GetCurve()

    # Creates a key in the Y curve with value 0 at 0 frame with a spline interpolation
    keyA, keyAIndex = CreateKey(curveY, c4d.BaseTime(0), value=0, interpolation=c4d.CINTERPOLATION_SPLINE)

    # Retrieves time at frame 10
    keyBTime = c4d.BaseTime(10, doc.GetFps())

    # Creates another key in the Y curve with value 100 at 10 frame with a spline interpolation
    keyB, keyBIndex = CreateKey(curveY, keyBTime, value=100, interpolation=c4d.CINTERPOLATION_SPLINE)

    # Inserts the track containing the Y curve to the object
    obj.InsertTrackSorted(trackY)

    # Inserts the object in document
    doc.InsertObject(obj)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
Example #5
0
def main():

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

    take = takeData.GetCurrentTake()
    if take.IsMain():
        return

    cube = doc.GetActiveObject()
    if cube is None:
        return

    if cube.GetType() != c4d.Ocube:
        return

    # This example adds an override to the current take for the object (that must be a cube) and changes the "Size" parameter.

    ID = c4d.DescID(c4d.DescLevel(c4d.PRIM_CUBE_LEN, c4d.DTYPE_VECTOR, 0),
                    c4d.DescLevel(c4d.VECTOR_X, c4d.DTYPE_REAL, 0))
    newValue = 300.0

    overrideNode = take.FindOrAddOverrideParam(takeData, cube, ID, newValue)

    if overrideNode is not None:
        overrideNode.UpdateSceneNode(takeData, ID)
        c4d.EventAdd()
Example #6
0
def Bake(source, target):
    """ Bake function  """

    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    fps = doc.GetFps()  # Get Frame Rate
    startFrame = doc.GetLoopMinTime().GetFrame(
        fps)  # Get first frame of Preview Range
    endFrame = doc.GetLoopMaxTime().GetFrame(
        fps)  # Get last frame of Preview Range

    for i in range(startFrame, endFrame + 1):  # Iterate through Preview Range
        SetCurrentFrame(i, doc)  # Set current frame
        frame = doc.GetTime().GetFrame(fps)  # Get current frame

        dataVault = [
            [903, c4d.DTYPE_REAL, 1000, c4d.DTYPE_VECTOR],
            [903, c4d.DTYPE_REAL, 1001, c4d.DTYPE_VECTOR],
            [903, c4d.DTYPE_REAL, 1002, c4d.DTYPE_VECTOR],  # Position
            [904, c4d.DTYPE_REAL, 1000, c4d.DTYPE_VECTOR],
            [904, c4d.DTYPE_REAL, 1001, c4d.DTYPE_VECTOR],
            [904, c4d.DTYPE_REAL, 1002, c4d.DTYPE_VECTOR],  # Rotation
            [905, c4d.DTYPE_REAL, 1000, c4d.DTYPE_VECTOR],
            [905, c4d.DTYPE_REAL, 1001, c4d.DTYPE_VECTOR],
            [905, c4d.DTYPE_REAL, 1002, c4d.DTYPE_VECTOR],  # Scale
        ]

        for data in dataVault:  # Iterate through data vault
            if len(data) == 2:  # Float
                desc = c4d.DescID(c4d.DescLevel(data[0], data[1], 0))
                value = source[data[0]]

            if len(data) == 4:  # Vector
                desc = c4d.DescID(c4d.DescLevel(data[0], data[3], 0),
                                  c4d.DescLevel(data[2], data[1], 0))
                value = source[data[0], data[2]]

            track = target.FindCTrack(desc)  # Try to find CTrack
            if not track:  # If CTrack does not exists
                track = c4d.CTrack(target, desc)  # Initialize CTrack
                target.InsertTrackSorted(track)  # Insert CTrack to the object

            curve = track.GetCurve()  # Get Curve of the CTrack
            currentTime = c4d.BaseTime(frame, fps)  # Get current time
            key = curve.AddKey(currentTime)["key"]
            track.FillKey(doc, target, key)

            if data[1] == c4d.DTYPE_REAL:  # Float
                key.SetValue(curve, value)
            else:  # If boolean or integer
                key.SetValue(curve, value)
                key.SetGeData(
                    curve,
                    value)  # Keyframe value needs to be set with SetGeData
Example #7
0
def new_rig(obj, cachetype):
    #create a Python tag and attach it to the selected tag's object
    pythontag = c4d.BaseTag(c4d.Tpython)

    #set the Python code inside the tag
    pythontag[
        c4d.TPYTHON_CODE] = copyright + pythontagcode + pythontagcode_dict[
            cachetype]

    #add userdata to the Python tag
    userdata = c4d.GetCustomDataTypeDefault(c4d.DTYPE_REAL)
    userdata[c4d.DESC_NAME] = "Frame"
    pythontag.AddUserData(userdata)
    pythontag[c4d.ID_USERDATA, 1] = 0.0

    #add an animation track to the userdata we just created
    track = c4d.CTrack(
        pythontag,
        c4d.DescID(c4d.DescLevel(c4d.ID_USERDATA, c4d.DTYPE_SUBCONTAINER, 0),
                   c4d.DescLevel(1, c4d.DTYPE_REAL, 0)))
    pythontag.InsertTrackSorted(track)
    #get the curve of our new track (we'll attach keyframes to this curve)
    curve = track.GetCurve()
    #make some keyframes, setting their time, value and curve
    key1 = c4d.CKey()
    key1.SetTime(curve, doc.GetMinTime())
    key1.SetValue(curve, doc.GetMinTime().Get() * doc.GetFps())
    key1.SetTimeRight(curve, c4d.BaseTime(0.5))

    key2 = c4d.CKey()
    key2.SetTime(curve, doc.GetMaxTime())
    key2.SetValue(curve, doc.GetMaxTime().Get() * doc.GetFps())
    key2.SetTimeLeft(curve, c4d.BaseTime(-0.5))

    #add the keyframes to the curve
    curve.InsertKey(key1)
    curve.InsertKey(key2)

    #set the Python tag's priority
    priority = c4d.PriorityData()
    priority.SetPriorityValue(c4d.PRIORITYVALUE_MODE, c4d.CYCLE_GENERATORS)
    priority.SetPriorityValue(c4d.PRIORITYVALUE_PRIORITY, -1)
    pythontag[c4d.EXPRESSION_PRIORITY] = priority

    #add the Python tag to the selected object, and add an undo
    doc.StartUndo()
    obj.InsertTag(pythontag)
    doc.AddUndo(c4d.UNDOTYPE_NEW, pythontag)
    doc.EndUndo()

    c4d.EventAdd(c4d.EVENT_FORCEREDRAW)

    print "Cache retimer successfully added to " + obj.GetName() + "!"
def getXYZtrack(obj, trackID, channelID, doc):
    # Find the Track
    param = c4d.DescID(c4d.DescLevel(trackID, c4d.DTYPE_VECTOR, 0),
                       c4d.DescLevel(channelID, c4d.DTYPE_REAL, 0))
    track = obj.FindCTrack(param)

    # Create if no track found
    if not track:
        track = c4d.CTrack(obj, param)
        doc.AddUndo(c4d.UNDOTYPE_NEW, track)
        obj.InsertTrackSorted(track)

    return track
    def DescriptionItemsBeforeDistance(self, node, description, singleID,
                                       groupID, newParameterID, index):

        # SDISPLAYMODE POPUP MENU

        newID = newParameterID
        newParameterID = newParameterID + 1

        self.parameterIDArrays[SDISPLAYMODE].append(newID)

        descid = c4d.DescID(
            c4d.DescLevel(newID, c4d.DTYPE_LONG, node.GetType()))

        addParameter = singleID is None

        if not addParameter: addParameter = descid.IsPartOf(singleID)[0]

        if addParameter:

            bc = self.PopupSDISPLAYMODE()

            bc.SetString(c4d.DESC_NAME, "SDISPLAYMODE " + str(index + 1))
            bc.SetString(c4d.DESC_SHORT_NAME, "Shading Mode")

            description.SetParameter(descid, bc, groupID)

        # WDISPLAYMODE POPUP MENU

        newID = newParameterID
        newParameterID = newParameterID + 1

        self.parameterIDArrays[WDISPLAYMODE].append(newID)

        descid = c4d.DescID(
            c4d.DescLevel(newID, c4d.DTYPE_LONG, node.GetType()))

        addParameter = singleID is None

        if not addParameter: addParameter = descid.IsPartOf(singleID)[0]

        if addParameter:

            bc = self.PopupWDISPLAYMODE()

            bc.SetString(c4d.DESC_NAME, "WDISPLAYMODE " + str(index + 1))
            bc.SetString(c4d.DESC_SHORT_NAME, "Style")

            description.SetParameter(descid, bc, groupID)

        return newParameterID
Example #10
0
def update_drivers():

    #drivers objects list
    objectsList = get_all_objects(doc.GetFirstObject(),
                                  lambda x: x.CheckType(ARNOLD_DRIVER), [])
    path_id = c4d.DescID(c4d.DescLevel(C4DAIP_DRIVER_EXR_FILENAME),
                         c4d.DescLevel(1))

    for obj in objectsList:
        driver_name = obj[c4d.ID_BASELIST_NAME]
        print driver_name
        if not driver_name == "<display driver>":
            obj.SetParameter(path_id, "c:\\my\\new\\path", c4d.DESCFLAGS_SET_0)
        else:
            None
Example #11
0
def main():
    exrDriver = c4d.BaseObject(ARNOLD_DRIVER)
    exrDriver.SetName("myDriver")
    path_id = c4d.DescID(c4d.DescLevel(C4DAIP_DRIVER_EXR_FILENAME),
                         c4d.DescLevel(1))
    type_id = c4d.DescID(c4d.DescLevel(C4DAIP_DRIVER_EXR_FILENAME),
                         c4d.DescLevel(2))
    print "Current path: %s" % exrDriver.GetParameter(path_id,
                                                      c4d.DESCFLAGS_GET_0)
    print "Current type: %d" % exrDriver.GetParameter(type_id,
                                                      c4d.DESCFLAGS_GET_0)
    exrDriver.SetParameter(path_id, "c:\\test\\path", c4d.DESCFLAGS_SET_0)
    exrDriver.SetParameter(type_id, 1, c4d.DESCFLAGS_SET_0)

    doc.InsertObject(exrDriver)
    c4d.EventAdd()
Example #12
0
def createAnimationObject(curObj, animTag, newName, doc):

    #newObj=curObj.GetClone()
    #doc.InsertObject(newObj,curObj.GetUp(),curObj)
    doc.SetActiveObject(curObj, c4d.SELECTION_NEW)
    c4d.CallCommand(12233)
    newObj = curObj.GetNext()
    extraRemove = None
    if newObj.GetType() != c4d.Opolygon:
        extraRemove = newObj
        newObj = newObj.GetDown()
        doc.InsertObject(newObj, curObj.GetUp(), curObj)
    cleanTracks(newObj)
    id = c4d.DescID(c4d.DescLevel(c4d.CTpla, c4d.CTpla, 0))
    plaTrack = c4d.CTrack(newObj, id)
    newObj.InsertTrackSorted(plaTrack)
    setNewtracks(plaTrack, curObj, newObj, animTag, doc)
    newAnimationTag = newObj.GetTag(1030484)
    newAnimationTag[1054] = 1056
    newAnimationTag[1051] = False
    newAnimationTag[1010] = True
    newAnimationTag[1011] = newName
    animTag[1010] = False
    newObj.SetName(newName)
    if extraRemove is not None:
        extraRemove.Remove()
    c4d.EventAdd()
Example #13
0
def Bake(source, target):
    """ Bake function  """

    doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document
    fps = doc.GetFps() # Get Frame Rate
    startFrame = doc.GetLoopMinTime().GetFrame(fps) # Get first frame of Preview Range
    endFrame = doc.GetLoopMaxTime().GetFrame(fps) # Get last frame of Preview Range

    desc = c4d.DescID(c4d.DescLevel(c4d.CTpla, c4d.CTpla, 0))
    PLAtrack = c4d.CTrack(target, desc) # Initialize a PLA track
    target.InsertTrackSorted(PLAtrack) # Insert PLA track to the object

    curve = PLAtrack.GetCurve() # Get Curve of the CTrack

    for i in range(startFrame, endFrame+1): # Iterate through Preview Range
        SetCurrentFrame(i, doc) # Set current frame
        frame = doc.GetTime().GetFrame(fps) # Get current frame

        points = source.GetAllPoints()
        
        #key.SetValue(curve, value)
        #key.SetGeData(curve, value) # Keyframe value needs to be set with SetGeData

        currentTime = c4d.BaseTime(frame, fps) # Get current time
        #points = source.GetAllPoints()
        key = curve.AddKey(currentTime)["key"]

        target.SetAllPoints(points)
        target.Message(c4d.MSG_UPDATE)
        PLAtrack.FillKey(doc, target, key)
Example #14
0
def createAnimationObject(curObj, animTag, newName, doc):

    #newObj=curObj.GetClone()
    #doc.InsertObject(newObj)
    doc.SetActiveObject(curObj, c4d.SELECTION_NEW)
    c4d.CallCommand(
        12233)  # perform "current state to object" on the selected object
    # search the newly created object
    stateObj = curObj.GetNext()
    newObj = getPolyObject(stateObj)
    stateObj.Remove()
    doc.InsertObject(newObj, curObj.GetUp(), curObj)

    cleanTracks(newObj)
    id = c4d.DescID(c4d.DescLevel(c4d.CTpla, c4d.CTpla, 0))
    plaTrack = c4d.CTrack(newObj, id)
    newObj.InsertTrackSorted(plaTrack)
    setNewtracks(plaTrack, curObj, newObj, animTag, doc)
    newAnimationTag = newObj.GetTag(1030484)
    newAnimationTag[1054] = 1056
    newAnimationTag[1051] = False
    newAnimationTag[1010] = True
    newAnimationTag[1011] = newName
    animTag[1010] = False
    newObj.SetName(newName)
    c4d.EventAdd()
Example #15
0
    def DescriptionItemsBeforeDistance(self, node, description, singleID,
                                       groupID, newParameterID, index):

        # OBJECT NAME STRING

        newID = newParameterID
        newParameterID = newParameterID + 1

        self.parameterIDArrays[OBJECT_NAMES].append(newID)

        descid = c4d.DescID(
            c4d.DescLevel(newID, c4d.DTYPE_STRING, node.GetType()))

        addParameter = singleID is None

        if not addParameter: addParameter = descid.IsPartOf(singleID)[0]

        if addParameter:

            bc = self.String()

            bc.SetString(c4d.DESC_NAME, "Object " + str(index + 1))
            bc.SetString(c4d.DESC_SHORT_NAME, "Object")

            description.SetParameter(descid, bc, groupID)

        return newParameterID
Example #16
0
def main():

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

    # This example creates ten takes with different overrides of the material color.

    material = doc.GetActiveMaterial()
    if material is None:
        return

    if material.GetType() != c4d.Mmaterial:
        return

    for i in xrange(10):

        takeName = "Variation " + str(i)
        materialVariation = takeData.AddTake(takeName, None, None)

        if materialVariation is not None:

            materialColorParameter = c4d.DescID(
                c4d.DescLevel(c4d.MATERIAL_COLOR_COLOR, c4d.DTYPE_COLOR, 0))

            hsv = c4d.Vector(float(i) * 0.1, 1.0, 1.0)
            rgb = c4d.utils.HSVToRGB(hsv)

            overrideNode = materialVariation.FindOrAddOverrideParam(
                takeData, material, materialColorParameter, rgb)

            if overrideNode is not None:
                overrideNode.UpdateSceneNode(takeData, materialColorParameter)

    c4d.EventAdd()
Example #17
0
def userdata_tree(ud):
    """
  Builds a tree of userdata information. Returns a proxy root node that
  contains at least the main User Data group and eventually other root
  groups.
  """

    DataNode = Node[dict]
    params = HashDict()
    root = Node[None]()

    # Create a node for every parameter.
    for descid, bc in ud:
        params[descid] = DataNode(descid=descid, bc=bc)

    # The main userdata group is not described in the UserData container.
    descid = c4d.DescID(
        c4d.DescLevel(c4d.ID_USERDATA, c4d.DTYPE_SUBCONTAINER, 0))
    node = DataNode(descid=descid, bc=c4d.BaseContainer())
    params[descid] = node
    root.add_child(node)

    # Establish parent-child parameter relationships.
    for descid, bc in ud:
        node = params[descid]
        parent_id = bc[c4d.DESC_PARENTGROUP]
        try:
            parent = params[parent_id]
        except KeyError:
            root.add_child(node)
        else:
            parent.add_child(node)

    return root
Example #18
0
    def ExposeParameter(self, parameterID, portType):
        """Expose a parameter in a GvNode.

        :param parameterID: The ID of the parameter or the full c4d.DescID.
        :type paramaterID: int or c4d.DescID
        :param portType: c4d.GV_PORT_INPUT or c4d.GV_PORT_OUTPUT.
        :type portType: int
        :return: True if success otherwise False.
        :rtype: Bool
        """
        if not isinstance(parameterID, int) and not isinstance(parameterID, c4d.DescID):
            raise TypeError("parameterID is not valid")

        if isinstance(parameterID, int):
            if self._GvNode.AddPortIsOK(portType, parameterID):
                if self.__DoUndo:
                    self._GvNode.GetNodeMaster().AddUndo()
                return self._GvNode.AddPort(
                    portType, c4d.DescID(c4d.DescLevel(parameterID)), message=True
                )
        else:
            if self.__DoUndo:
                self._GvNode.GetNodeMaster().AddUndo()
            return self._GvNode.AddPort(portType, parameterID, message=True)

        return False
def main():
    # Retrieves active material
    mat = doc.GetActiveMaterial()
    if not mat: return

    # Tries to obtain a gradient shader
    gradient = mat[c4d.MATERIAL_COLOR_SHADER]
    if not gradient: return
    if gradient.GetType() != c4d.Xgradient: return

    # Creates a new Description
    desc = c4d.Description()
    if not desc: return

    # Builds the gradient DescID
    descid = c4d.DescID(
        c4d.DescLevel(c4d.SLA_GRADIENT_GRADIENT, c4d.CUSTOMDATATYPE_GRADIENT,
                      c4d.Xgradient))

    # Retrieves the gradient knots description
    desc.GetSubDescriptionWithData(descid, [gradient], c4d.BaseContainer(),
                                   None)

    # Retrieves the gradient data with its knots
    gradientData = gradient[descid]

    # Prints the gradient knots
    knotCount = gradientData.GetKnotCount()
    for idx in range(knotCount):
        print gradientData.GetKnot(idx)

    # Prints the gradient description
    for bc, paramid, groupid in desc:
        print bc[c4d.DESC_NAME], paramid[-1].dtype
Example #20
0
def main():

    if op is None:
        return

    if op.GetType() != c4d.Osphere:
        return

    # This example edits the given sphere object
    # If auto take is enabled, the current take is used.

    undoObject = op.GetClone(c4d.COPYFLAGS_0)

    op.SetParameter(c4d.DescID(c4d.DescLevel(c4d.PRIM_SPHERE_RAD)), 100.0,
                    c4d.DESCFLAGS_SET_0)

    takeData = doc.GetTakeData()
    if takeData is not None and takeData.GetTakeMode() == c4d.TAKE_MODE_AUTO:

        currentTake = takeData.GetCurrentTake()

        if currentTake is not None:
            currentTake.AutoTake(takeData, op, undoObject)

    c4d.EventAdd()
def main():
    # Check active object
    if op is None:
        return

    # Search object's rotation track
    trackID = c4d.DescID(
        c4d.DescLevel(c4d.ID_BASEOBJECT_REL_ROTATION, c4d.DTYPE_VECTOR,
                      op.GetType()))
    track = op.FindCTrack(trackID)
    if track is None:
        return

    # Get the curve for the track
    curve = track.GetCurve()
    if curve is None:
        return

    ret, curveX, curveY, curveZ = op.GetVectorCurves(curve)
    if ret:
        print "c4d.ID_BASEOBJECT_REL_ROTATION curves:"
        print "Curve H:", curveX
        print "Curve P:", curveY
        print "Curve B:", curveZ
    else:
        print "Could not get vector curves!"
def main():
    
    path = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, "Sound file", c4d.FILESELECT_LOAD)
    folderPath, fileName = os.path.split(path)

    doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document    
    time = c4d.BaseTime(doc.GetTime().Get()) # Get current time
    
    null = c4d.BaseObject(c4d.Onull) # Initialize a null
    null.SetName("Sound: "+fileName) # Set name
    null[c4d.NULLOBJECT_DISPLAY] = 14 # Set 'Display' to 'None'
    null[c4d.ID_BASELIST_ICON_FILE] = "440000255" # Set icon
    null[c4d.ID_BASELIST_ICON_COLORIZE_MODE] = 2 # Set 'Icon Color' to 'Display Color'
    null[c4d.ID_BASEOBJECT_USECOLOR] = 2 # Set 'Display Color' to 'On'
    null[c4d.ID_BASEOBJECT_COLOR] = c4d.Vector(140.0/255.0, 203.0/255.0, 1.0)
    null[c4d.ID_BASELIST_ICON_COLOR] = c4d.Vector(140.0/255.0, 203.0/255.0, 1.0)
    doc.InsertObject(null) # Insert null to the document   

    desc = c4d.DescID(c4d.DescLevel(c4d.CTsound, c4d.CTsound, 0))
    SoundTrack = c4d.CTrack(null, desc) # Initialize a sound Track
    null.InsertTrackSorted(SoundTrack) # Insert the sound track to the object
    SoundTrack[c4d.CID_SOUND_NAME] = path # Set sou
    SoundTrack[c4d.CID_SOUND_START] = time

    c4d.EventAdd()
Example #23
0
def main():
    # Checks if selected object is valid
    if op is None:
        raise ValueError("op is none, please select one object.")

    # Searches object's rotation track
    trackID = c4d.DescID(
        c4d.DescLevel(c4d.ID_BASEOBJECT_REL_ROTATION, c4d.DTYPE_VECTOR,
                      op.GetType()))
    track = op.FindCTrack(trackID)
    if track is None:
        raise RuntimeError(
            "Failed to retrieve the track, Object may not have track.")

    # Gets the curve for the track
    curve = track.GetCurve()
    if curve is None:
        raise RuntimeError(
            "Failed to retrieve the curves, Object may not have curves.")

    # Gets the X,Y,Z curves from a Vector curve
    ret, curveX, curveY, curveZ = op.GetVectorCurves(curve)
    if not ret:
        raise RuntimeError("Failed to retrieve the vector curve.")

    print("c4d.ID_BASEOBJECT_REL_ROTATION curves:")
    print("Curve H: {0}".format(curveX))
    print("Curve P: {0}".format(curveY))
    print("Curve B: {0}".format(curveZ))
Example #24
0
def update_driversPath():

    #drivers objects list
    objectsList = get_all_objects(doc.GetFirstObject(),
                                  lambda x: x.CheckType(ARNOLD_DRIVER), [])

    for obj in objectsList:
        driver_name = obj[c4d.ID_BASELIST_NAME]
        driver_type = obj[c4d.C4DAI_DRIVER_TYPE]

        if driver_type == C4DAIN_DRIVER_EXR:
            driver_filename = C4DAIP_DRIVER_EXR_FILENAME
        elif driver_type == C4DAIN_DRIVER_DEEPEXR:
            driver_filename = C4DAIP_DRIVER_DEEPEXR_FILENAME
        elif driver_type == C4DAIN_DRIVER_TIFF:
            driver_filename = C4DAIP_DRIVER_TIFF_FILENAME
        elif driver_type == C4DAIN_DRIVER_PNG:
            driver_filename = C4DAIP_DRIVER_PNG_FILENAME
        elif driver_type == C4DAIN_DRIVER_JPEG:
            driver_filename = C4DAIP_DRIVER_JPEG_FILENAME
        else:
            driver_filename = 0

        if driver_type == C4DAIN_DRIVER_EXR:
            driver_format = ".exr"
        elif driver_type == C4DAIN_DRIVER_DEEPEXR:
            driver_format = ".exr"
        elif driver_type == C4DAIN_DRIVER_TIFF:
            driver_format = ".tiff"
        elif driver_type == C4DAIN_DRIVER_PNG:
            driver_format = ".png"
        elif driver_type == C4DAIN_DRIVER_JPEG:
            driver_format = ".jpg"
        else:
            driver_format = ""

        path_id = c4d.DescID(c4d.DescLevel(driver_filename), c4d.DescLevel(1))
        driver_name = driver_name.replace(" ", "_")
        driver_custom_path = "./$prj/$prj_" + driver_name + driver_format
        print driver_custom_path

        if not driver_type == C4DAIN_DRIVER_DISPLAY:
            obj.SetParameter(path_id, driver_custom_path, c4d.DESCFLAGS_SET_0)
        else:
            None

    c4d.EventAdd()
Example #25
0
def AddUserData(obj, name, id, Dtye, step, min, max):
    bc = c4d.GetCustomDataTypeDefault(Dtye)  # Create default container
    bc[c4d.DESC_NAME] = name  # Rename the entry
    bc[c4d.DESC_MIN] = min  # Set min value
    bc[c4d.DESC_MAX] = max  # Set max value
    bc[c4d.DESC_STEP] = step  # Set step value
    bc[c4d.DESC_CUSTOMGUI] = 1000489  # Set float slider
    bc[c4d.DESC_MINSLIDER] = min  # Set min value slider
    bc[c4d.DESC_MAXSLIDER] = max  # Set man value slider

    parentGroup = c4d.DescID(c4d.DescLevel(c4d.ID_USERDATA),
                             c4d.DescLevel(1, c4d.DTYPE_GROUP,
                                           0))  # 1 is my secondary Group ID
    bc.SetData(c4d.DESC_PARENTGROUP, parentGroup)

    obj.SetUserDataContainer([c4d.ID_USERDATA, id],
                             bc)  # Add userdata container
Example #26
0
def main():
    selection = doc.GetSelection()
    i = 0

    minTime = doc.GetMinTime()
    maxTime = doc.GetMaxTime()

    print minTime.GetFrame(doc.GetFps())
    print maxTime.GetFrame(doc.GetFps())

    for t in range(minTime.GetFrame(doc.GetFps()),
                   maxTime.GetFrame(doc.GetFps())):

        frame = c4d.BaseTime(t / float(doc.GetFps()))

        for item in selection:

            trackPos = c4d.DescID(
                c4d.DescLevel(c4d.ID_BASEOBJECT_REL_POSITION, c4d.DTYPE_VECTOR,
                              item.GetType()))
            trackRot = c4d.DescID(
                c4d.DescLevel(c4d.ID_BASEOBJECT_REL_ROTATION, c4d.DTYPE_VECTOR,
                              item.GetType()))

            xPos = item.GetVectorTracks(trackPos)[1].GetValue(doc, frame)
            yPos = item.GetVectorTracks(trackPos)[2].GetValue(doc, frame)
            zPos = item.GetVectorTracks(trackPos)[3].GetValue(doc, frame)

            xRot = item.GetVectorTracks(trackRot)[1].GetValue(doc, frame)
            yRot = item.GetVectorTracks(trackRot)[2].GetValue(doc, frame)
            zRot = item.GetVectorTracks(trackRot)[3].GetValue(doc, frame)

            print xPos, yPos, zPos
            print xRot, yRot, zRot

            #print item.GetVectorTracks(trackRot)

    c4d.EventAdd()
    c4d.DrawViews()
Example #27
0
def get_arf_psr_desc_id(arf, psr, dim=-1):
    # Drag and drop element directly to python console to get DescID expression
    arf_L = ["abs", "rel", "frozen"]
    arf_str_L = ["ABS", "REL", "FROZEN"]
    psr_L = ["pos", "rot", "scale"]
    psr_str_L = ["POSITION", "ROTATION", "SCALE"]

    arf_str = arf_str_L[arf_L.index(arf.lower())]
    psr_str = psr_str_L[psr_L.index(psr.lower())]

    desc_level_1_1 = eval("_".join(["c4d.ID_BASEOBJECT", arf_str, psr_str]))
    desc_level_1 = c4d.DescLevel(desc_level_1_1, c4d.DTYPE_VECTOR, 0)

    xyz_str = ["X", "Y", "Z"]
    if dim == -1:
        desc_id = c4d.DescID(desc_level_1)
    else:
        desc_level_2_1 = eval(("c4d.VECTOR_" + xyz_str[dim]))
        desc_level_2 = c4d.DescLevel(desc_level_2_1, c4d.DTYPE_REAL, 0)
        desc_id = c4d.DescID(desc_level_1, desc_level_2)

    return desc_id
def main():
    if op is None: return
    if op.GetClassification() != c4d.Obase: return

    # Retrieves the active object's description
    desc = op.GetDescription(c4d.DESCFLAGS_DESC_0)
    if not desc: return

    # Builds the object's X position parameter DescID
    descid = c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_POSITION, 0, 0),
                        c4d.DescLevel(c4d.VECTOR_X, 0, 0))
    # Prints previously built DescID
    print descid

    # Calls CheckDescID() to retrieve the complete DescID for the object's X position parameter
    ret = desc.CheckDescID(descid, [op])
    if ret is None:
        print "Could not check description ID"
        return

    # Prints the complete DescID
    print ret
Example #29
0
def main():
    # Checks if selected object is valid
    if op is None:
        raise ValueError("op is none, please select one object.")
    
    # Retrieves the active object's description
    desc = op.GetDescription(c4d.DESCFLAGS_DESC_0)
    if desc is None:
        raise RuntimeError("Failed to retrieve the description.")

    # Builds the object's X position parameter DescID
    descId = c4d.DescID(c4d.DescLevel(c4d.ID_BASEOBJECT_REL_POSITION, 0, 0), c4d.DescLevel(c4d.VECTOR_X, 0, 0))

    # Prints previously built DescID
    print(descId)

    # Calls CheckDescID() to retrieve the complete DescID for the object's X position parameter
    ret = desc.CheckDescID(descId, [op])
    if ret is None:
        raise RuntimeError("Could not check description ID.")

    # Prints the complete DescID
    print(ret)
Example #30
0
def getVecIds(id=c4d.ID_BASEOBJECT_REL_POSITION):
    """Get IDs for X, Y, Z components of a vector id. For example, XYZ of c4d.ID_BASEOBJECT_GLOBAL_POSITION"""
    x = c4d.DescID(c4d.DescLevel(id, c4d.DTYPE_VECTOR, 0),
                   c4d.DescLevel(c4d.VECTOR_X, c4d.DTYPE_REAL, 0))
    y = c4d.DescID(c4d.DescLevel(id, c4d.DTYPE_VECTOR, 0),
                   c4d.DescLevel(c4d.VECTOR_Y, c4d.DTYPE_REAL, 0))
    z = c4d.DescID(c4d.DescLevel(id, c4d.DTYPE_VECTOR, 0),
                   c4d.DescLevel(c4d.VECTOR_Z, c4d.DTYPE_REAL, 0))
    return (x, y, z)