Exemple #1
0
def main():
    fn = c4d.storage.LoadDialog(c4d.FILESELECTTYPE_ANYTHING,
                                "Folder to export", c4d.FILESELECT_DIRECTORY)
    if not fn: return  # If cancelled stop the script
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    objects = doc.GetObjects()  # Get objects

    plug = plugins.FindPlugin(1030178, c4d.PLUGINTYPE_SCENESAVER)
    if plug is None:
        return
    data = {}
    if plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data):
        if "imexporter" not in data:
            return
        objExport = data["imexporter"]
        if objExport is None:
            return

    for i, obj in enumerate(objects):  # Iterate through objects
        tempDoc = c4d.documents.BaseDocument()  # Initiralize a temp document
        clone = obj.GetClone()  # Get clone of the original object
        tags = obj.GetTags()  # Get object's tags
        for t in tags:  # Loop through tags
            if isinstance(t, c4d.TextureTag):  # If texture tag
                mat = t[c4d.TEXTURETAG_MATERIAL]  # Get material
                tempDoc.InsertMaterial(
                    mat)  # Insert material to the temp document
        tempDoc.InsertObject(clone)  # Insert clone to the temp document
        name = obj.GetName()
        path = os.path.splitext(fn)[0] + "\\" + name + ".obj"  # File name
        c4d.documents.SaveDocument(tempDoc, path,
                                   c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST,
                                   1030178)  # Export OBJ-file
        tempDoc.Flush()  # Flush temp doc
    c4d.StatusSetText("Export complete!")  # Set status text
    c4d.EventAdd()  # Refresh Cinema 4D
def main():
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    doc.StartUndo()  # Start recording undos

    link1 = CreateUserDataLink(op, "Object", op)  # Create user data link

    xptag = c4d.BaseTag(c4d.Texpresso)  # Initialize xpresso tag
    xptag.SetName("My Xpresso Tag")  # Set xpresso tag name
    op.InsertTag(xptag)  # Insert tag to object
    nodemaster = xptag.GetNodeMaster()  # Get node master
    objectNode = nodemaster.CreateNode(nodemaster.GetRoot(),
                                       c4d.ID_OPERATOR_OBJECT,
                                       None,
                                       x=200,
                                       y=100)  # Create object node
    objPort = objectNode.AddPort(
        c4d.GV_PORT_OUTPUT,  # Add 'user data link' output port to node
        c4d.DescID(c4d.DescLevel(c4d.ID_USERDATA, c4d.DTYPE_SUBCONTAINER, 0),
                   c4d.DescLevel(1)),
        message=True)

    c4d.modules.graphview.RedrawMaster(nodemaster)  # Refresh xpresso
    doc.EndUndo()  # Stop recording undos
    c4d.EventAdd()  # Refresh Cinema 4D
def main():
    # Retrieves active material
    mat = doc.GetActiveMaterial()
    if mat is None:
        raise RuntimeError("Failed to retrieve the selected material.")

    # Checks active material is a standard material
    if not mat.IsInstanceOf(c4d.Mmaterial):
        raise TypeError("The selected material is not a default c4d material.")

    # Retrieves the material's color
    color = mat[c4d.MATERIAL_COLOR_COLOR]
    if color is None:
        raise RuntimeError("Unable to retrieve the color of the color channel.")

    # Calculates the complementary color
    res = c4d.modules.colorchooser.ColorHarmonyGetComplementary(color, False)
    if not res:
        raise RuntimeError("Failed to retrieve the complementary color.")

    # Retrieves the complementary color
    complementaryColor = res[1]

    # Creates a new material with complementary color
    complementaryMat = c4d.BaseMaterial(c4d.Mmaterial)
    if complementaryMat is None:
        raise MemoryError("Failed to create a new default base material.")

    # Sets the complementary color as material's color
    complementaryMat[c4d.MATERIAL_COLOR_COLOR] = complementaryColor

    # Inserts the material with complementary color into the active document
    doc.InsertMaterial(complementaryMat)

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

    # Creates a swatch data
    swatchData = colorchooser.ColorSwatchData()
    if swatchData is None:
        return

    # Loads the swatch data from the active document
    swatchData.Load(doc)

    # Creates a swatch group
    group = swatchData.AddGroup(c4d.SWATCH_CATEGORY_DOCUMENT, "Rainbow")
    if group is not None:
        for i in xrange(20):

            # Creates rainbow colors and stores them in the previously created group
            hsv = c4d.Vector(float(i) * 0.05, 1.0, 1.0)
            rgb = c4d.utils.HSVToRGB(hsv)

            # Creates a maxon.ColorA for the current color
            col4 = maxon.ColorA()
            col4.r = rgb.x
            col4.g = rgb.y
            col4.b = rgb.z
            col4.a = 1.0
            group.AddColor(col4)

        # Inserts the swatch group
        index = swatchData.GetGroupCount(c4d.SWATCH_CATEGORY_DOCUMENT) - 1
        swatchData.SetGroupAtIndex(index, group)

        # Saves the group into the active document
        swatchData.Save(doc)

    # Updates Cinema 4D
    c4d.EventAdd()
Exemple #5
0
def main():
    # find the Arnold video post data
    arnoldRenderSettings = GetArnoldRenderSettings()
    if arnoldRenderSettings is None:
        raise BaseException("Failed to find Arnold render settings")

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

    # find aovs with Optix setting
    for driver in driversList:
        driver_name = driver[c4d.ID_BASELIST_NAME]
        print "Driver: " + driver_name + "\n"

        driver_AOVs = driver.GetChildren()

        for aov in driver_AOVs:
            aov_name = aov[c4d.ID_BASELIST_NAME]
            print "AOV: " + aov_name

            aov[c4d.C4DAI_AOV_DENOISE] = False

    c4d.EventAdd()
def main():
    doc.StartUndo()

    objList = doc.GetActiveObjects(childs=True)

    #Create Null
    null_obj = c4d.BaseObject(c4d.Onull)
    null_obj.SetName("SS Control Objects")
    doc.AddUndo(c4d.UNDOTYPE_NEW, null_obj)
    doc.InsertObject(null_obj)

    #Create Master Rectangle
    rectangle = c4d.BaseObject(c4d.Osplinerectangle)
    rectangle[c4d.PRIM_RECTANGLE_WIDTH] = 10
    rectangle[c4d.PRIM_RECTANGLE_HEIGHT] = 10
    rectangle.SetName("SS Rectangle")
    doc.AddUndo(c4d.UNDOTYPE_NEW, rectangle)
    doc.InsertObject(rectangle, parent=null_obj)

    #Create Master Instance
    master_instance = c4d.BaseObject(c4d.Oinstance)
    master_instance.SetName("SS Master Instance [Don't Delete]")
    master_instance[c4d.INSTANCEOBJECT_LINK] = rectangle
    doc.AddUndo(c4d.UNDOTYPE_NEW, master_instance)
    doc.InsertObject(master_instance, pred=rectangle)

    doc.SetActiveObject(rectangle, c4d.SELECTION_NEW)

    #Create sweeps for each selected spline
    for obj in objList:
        if obj.GetRealSpline():
            sweepSpline(obj, master_instance)
            doc.AddUndo(c4d.UNDOTYPE_CHANGE, obj)

    c4d.EventAdd()
    doc.EndUndo()
Exemple #7
0
    def MixMat():
        doc.StartUndo()
        matlist = doc.GetActiveMaterials()
        if len(matlist) > 1:

            mixmat = c4d.BaseMaterial(1029622)

            doc.InsertMaterial(mixmat)
            doc.AddUndo(c4d.UNDOTYPE_NEW, mixmat)

            doc.AddUndo(c4d.UNDOTYPE_CHANGE, mixmat)
            mixmat[c4d.MIXMATERIAL_TEXTURE1] = matlist[0]

            mixmat[c4d.MIXMATERIAL_TEXTURE2] = matlist[1]

            doc.AddUndo(c4d.UNDOTYPE_CHANGE, mixmat)
            mixmat[c4d.ID_BASELIST_NAME] = matlist[0][
                c4d.ID_BASELIST_NAME] + '|' + matlist[1][c4d.ID_BASELIST_NAME]

        else:
            return

        c4d.EventAdd()
        doc.EndUndo()
def main():

    # Retrieve the current node space Id
    nodespaceId = c4d.GetActiveNodeSpaceId()

    # Create the material and retrieve the root of the graph
    root = CreateMaterialForNodeSpace(nodespaceId)

    # Start the recursive process on the first node
    PrintChildren(root)

    # Do the same with the Redshift node space. The Redshift plugin is not
    # installed by default, so we call the function in an exception handling
    # context.
    redShiftNodeSpPaceId = maxon.Id(
        'com.redshift3d.redshift4c4d.class.nodespace')
    try:
        root = CreateMaterialForNodeSpace(redShiftNodeSpPaceId)
        PrintChildren(root)
    except:
        print(f"The node space with id {redShiftNodeSpPaceId} does not exist")

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
def main():
    if op is None:
        return

    #Run Split Command
    s = Command_Split(op)

    #Insert FFD-Deformer under Split-Object and Fit
    ffd = c4d.BaseObject(c4d.Offd)
    doc.AddUndo(c4d.UNDOTYPE_NEW, ffd)
    doc.InsertObject(ffd)
    ffd.InsertUnder(s)
    c4d.CallButton(ffd, c4d.FFDOBJECT_FITTOPARENT)

    #Clone that FFD-Deformer under our Original Object
    clone = ffd.GetClone()
    doc.AddUndo(c4d.UNDOTYPE_NEW, clone)
    clone.InsertUnder(op)

    #Remove Split-Object
    doc.AddUndo(c4d.UNDOTYPE_DELETE, s)
    s.Remove()

    c4d.EventAdd()
Exemple #10
0
def main():

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

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

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

    # This example checks if the given take contains an override for the given sphere object.
    # If so, it is checked if the "Radius" parameter is overridden.
    # In this case, the value is increased and the node updated.

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

    baseOverride = take.FindOverride(takeData, obj)

    if baseOverride is None:
        return

    ID = c4d.DescID(c4d.DescLevel(c4d.PRIM_SPHERE_RAD, c4d.DTYPE_REAL, 0))

    if baseOverride.IsOverriddenParam(ID):

        data = baseOverride.GetParameter(ID, c4d.DESCFLAGS_GET_0)
        data = data + 10.0
        baseOverride.SetParameter(ID, data, c4d.DESCFLAGS_SET_0)

        baseOverride.UpdateSceneNode(takeData, ID)
        c4d.EventAdd()
Exemple #11
0
def main():

    
    doc=c4d.documents.GetActiveDocument()
    docpath=doc.GetDocumentPath()
    
    targetPath = "/Users/Carlos/Desktop/Test 03"

    #You will need c4d R15.057 for this function
    assets=c4d.documents.GetAllAssets(doc, True, docpath)
    
    missingAssets = None
    
    saveProject_flags = c4d.SAVEPROJECT_ASSETS | c4d.SAVEPROJECT_SCENEFILE | c4d.SAVEPROJECT_PROGRESSALLOWED | c4d.SAVEPROJECT_ADDTORECENTLIST
    
    collect_file = c4d.documents.SaveProject(doc, saveProject_flags, targetPath, assets, missingAssets)
        
    c4d.EventAdd()

    if collect_file == False:
        gui.MessageDialog('The scene has not been collected,\ncheck the console for more details.') print "the scene has not been collected."
        return
    else:
        print "the scene has been collected correctly."
def main():
    # Creates a new ColorSwatchData
    swatchData = c4d.modules.colorchooser.ColorSwatchData(doc)
    if swatchData is None:
        raise MemoryError("Failed to create a ColorSwatchData.")

    # Adds a group to the newly created ColorSwatchData
    group = swatchData.AddGroup("New Group", False)
    if group is None:
        raise MemoryError("Failed to create a new group.")

    # Adds red, green and blue colors to the ColorSwatchGroup
    group.AddColor(c4d.Vector(1.0, 0.0, 0.0), True)   
    group.AddColor(c4d.Vector(0.0, 1.0, 0.0), False) 
    group.AddColor(c4d.Vector(0.0, 0.0, 1.0), False)

    # Assigns the new group
    swatchData.SetGroupAtIndex(swatchData.GetGroupCount() - 1, group)

    # Saves the color groups into the active document
    swatchData.Save(doc)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
Exemple #13
0
def main():
    # Retrieves first substance
    substance = c4d.modules.substance.GetFirstSubstance(doc)
    if substance is None:
        raise RuntimeError(
            "Failed to retrieve the first substance (most likely there is no substance)."
        )

    # Retrieves material creation mode set in Substance preferences
    mode = c4d.modules.substance.PrefsGetMaterialModeSetting()
    if mode is None:
        raise RuntimeError("Failed to retrieve the material mode setting.")

    # Creates material based on the passed Substance asset
    mat = c4d.modules.substance.CreateMaterial(substance, 0, mode)
    if mat is None:
        raise MemoryError("Failed to create a substance material.")

    # Changes name and insert material into the document
    mat.SetName(substance.GetName() + " Material From Script")
    doc.InsertMaterial(mat)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
Exemple #14
0
def main():
    doc = c4d.documents.GetActiveDocument() # Get active Cinema 4D document
    doc.StartUndo() # Start recording undos
    fn = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING,'Select pixeur palette',c4d.FILESELECT_LOAD,'') # File dialog
    if fn is None: return # If no file, exit
    f = open(fn.decode("utf-8")) # Open file and read it in UTF-8
    try: # Try to execute following script
        for line in f: # Loop trhough lines in Pixeur color palette file
            if line.startswith("R"): # If line starts with letter R
                line = line.split(" ") # Split line to list
                r = line[0][2:] # Red channel value
                g = line[1][2:] # Green channel value
                line = line[2].split(",") # Split line new list
                b = line[0][2:] # Blue channel value
                mat = c4d.BaseMaterial(c4d.Mmaterial) # Initialize new material
                color = c4d.Vector(float(r)/255,float(g)/255,float(b)/255) # Convert rgb colors to c4d format
                mat[c4d.MATERIAL_COLOR_COLOR] = color # Set color channel color
                mat[c4d.MATERIAL_LUMINANCE_COLOR] = color # Set luminance channel color
                doc.InsertMaterial(mat) # Insert material to document
                doc.AddUndo(c4d.UNDOTYPE_NEW, mat) # Add undo command for inserting new material
    except: # If something went wrong
        pass # Do nothing
    doc.EndUndo() # Stop recording undos
    c4d.EventAdd() # Refresh Cinema 4D
Exemple #15
0
def main():
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    bd = doc.GetActiveBaseDraw()  # Get active basedraw
    bc = c4d.BaseContainer()  # Initialize base container
    path, fn = os.path.split(__file__)  # Get path of the script
    data = os.path.join(path, 'AR_ToggleTintedBorder.txt')  # data file path
    if (sys.version_info >= (3, 0)):  # If Python 3 version (R23)
        f = open(data)  # Open the file for reading
    else:  # If Python 2 version (R21)
        f = open(data.decode("utf-8"))
    value = float(f.readline())  # Get value from data file
    f.close()  # Close file
    keyMod = GetKeyMod()  # Get keymodifier
    if keyMod == "None":
        if bd[c4d.
              BASEDRAW_DATA_TINTBORDER_OPACITY] == 0:  # If tinted border's opacity is 0
            bd[c4d.BASEDRAW_DATA_TINTBORDER_OPACITY] = value  # Set opacity
        else:  # If tinted border's opacity is not 0
            if (sys.version_info >= (3, 0)):  # If Python 3 version (R23)
                f = open(data, 'w')  # Open the file for writing
            else:  # If Python 2 version (R21)
                f = open(data.decode("utf-8"),
                         'w')  # Open the file for writing
            f.write(str(bd[c4d.BASEDRAW_DATA_TINTBORDER_OPACITY])
                    )  # Write current value to file
            f.close()  # Close file
            bd[c4d.BASEDRAW_DATA_TINTBORDER_OPACITY] = 0  # Set opacity to 0
    elif keyMod == "Shift":
        dlg = Dialog()  # Create dialog object
        dlg.Open(c4d.DLG_TYPE_MODAL_RESIZEABLE, 0, -1, -1, 0, 0)  # Open dialog
    elif keyMod == "Ctrl":
        bd[c4d.BASEDRAW_DATA_TINTBORDER] = not bd[
            c4d.BASEDRAW_DATA_TINTBORDER]  # Toggle 'Tinted Border' checkbox
    #except: # If something went wrong
    #pass # Do nothing
    c4d.EventAdd()  # Refresh Cinema 4D
Exemple #16
0
def main():
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document

    selection = doc.GetSelection()  # Get active selection (objects, tags)
    for s in selection:  # Iterate through selection

        print s.GetName(), "\"" + type(s).__name__ + "\"", s.GetType(
        )  # Print: name, class and type id

        if type(s).__name__ == "XPressoTag":  # If operator is xpresso tag
            nodeMaster = s.GetNodeMaster()  # Get node master
            root = nodeMaster.GetRoot()  # Get xpresso root
            for c in root.GetChildren():  # Loop through nodes
                if c.GetBit(c4d.BIT_ACTIVE):  # If node is selected
                    print "Node: " + c.GetName() + ", " + str(
                        c.GetOperatorID())  # Print node info
                    inPorts = c.GetInPorts()  # Get input ports
                    outPorts = c.GetOutPorts()  # Get output ports
                    for p in range(0,
                                   len(inPorts)):  # Loop through input ports
                        print "    In port: " + inPorts[p].GetName(
                            c) + ", " + str(
                                inPorts[p].GetMainID())  # Print inPort info
                    for p in range(0,
                                   len(outPorts)):  # Loop through output ports
                        print "    Out port: " + outPorts[p].GetName(
                            c) + ", " + str(
                                outPorts[p].GetMainID())  # Print outPort info

    materials = doc.GetMaterials()  # Get materials
    for m in materials:  # Iterate through materials
        if m.GetBit(c4d.BIT_ACTIVE):  # If material is selected
            print m.GetName(), "\"" + type(m).__name__ + "\"", m.GetType(
            )  # Print: name, class and type id

    c4d.EventAdd()  # Refresh Cinema 4D
Exemple #17
0
    def limitFloorContact(self):
        doc = documents.GetActiveDocument()
        obj = doc.GetFirstObject()

        def addProtTag(obj):
            xtag = c4d.BaseTag(c4d.Tprotection)
            xtag[c4d.PROTECTION_P] = 2
            xtag[c4d.PROTECTION_S] = False
            xtag[c4d.PROTECTION_R] = False
            xtag[c4d.PROTECTION_P_X] = False
            xtag[c4d.PROTECTION_P_Y] = True
            xtag[c4d.PROTECTION_P_Z] = False
            xtag[c4d.PROTECTION_P_MIN_Y] = 0
            xtag[c4d.PROTECTION_P_MAX_Y] = 1000000
            obj.InsertTag(xtag)

        doc = documents.GetActiveDocument()
        obj = doc.GetFirstObject()
        scene = ObjectIterator(obj)
        for obj in scene:
            if "Foot_PlatformBase" in obj.GetName():
                addProtTag(obj)

        c4d.EventAdd()
Exemple #18
0
def main():
    global copyTags
    """ The first function to run """
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    selected = doc.GetActiveObjects(0)  # Get selected objects
    bakedCameras = []  # Collect baked cameras to an array
    doc.StartUndo()  # Start recording undos
    for s in selected:  # Iterate through objects
        if s.GetType() == 5103:  # If object is a camera object
            dummyCam = DummyCamera(s, doc)  # Dummy camera
            bakeCam = dummyCam.GetClone()  # Bake camera
            name = s.GetName()  # Get camera's name
            bakeCam.SetName(name + "_baked")  # Set baked camera's name
            doc.InsertObject(bakeCam)  # Insert camera to document
            doc.AddUndo(c4d.UNDOTYPE_NEW,
                        bakeCam)  # Add undo command for creating a new object
            MoveToLast(bakeCam, doc)  # Move object to last
            doc.ExecutePasses(None, True, True, True,
                              0)  # Animate the current frame of the document
            RemoveTags(bakeCam)  # Remove tags of the object
            Bake(dummyCam, bakeCam)  # Bake the camera
            dummyCam.Remove()  # Delete Dummy camera
            CleanKeys(bakeCam)  # Clean keyframes

            if copyTags == True:
                CopyRendererTags(
                    s, bakeCam
                )  # Copies renderer tags from source camera to bake camera

            bakedCameras.append(
                bakeCam)  # Add baked camera to bakedCameras array

    for b in reversed(bakedCameras):
        MoveToFirst(b, doc)  # Move camera to top of the hierarchy list
    doc.EndUndo()  # Stop recording undos
    c4d.EventAdd()  # Refresh Cinema 4D
def main():
    # Retrieves a path to load the imported file
    selectedFile = c4d.storage.LoadDialog(title="Load File for STEP Import", type=c4d.FILESELECTTYPE_ANYTHING, force_suffix="step")
    if not selectedFile:
        return

    # Retrieves STEP import plugin
    plug = c4d.plugins.FindPlugin(c4d.FORMAT_STEPIMPORT, c4d.PLUGINTYPE_SCENELOADER)
    if plug is None:
        raise RuntimeError("Failed to retrieve the STEP importer.")

    data = dict()
    # Sends MSG_RETRIEVEPRIVATEDATA to STEP import plugin
    if not plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data):
        raise RuntimeError("Failed to retrieve private data.")

    # BaseList2D object stored in "imexporter" key hold the settings
    stepImport = data.get("imexporter", None)
    if stepImport is None:
        raise RuntimeError("Failed to retrieve BaseContainer private data.")

    # Defines the settings
    stepImport[c4d.CADIMPORT_SPLINES] = False

    stepImport[c4d.CADIMPORT_ORIGINAL_UNITS] = False
    # Sets the data by Scaling 10x and set to mm units
    scale = c4d.UnitScaleData()
    scale.SetUnitScale(10, c4d.DOCUMENT_UNIT_MM)
    stepImport[c4d.CADIMPORT_SCALE] = scale

    # Finally imports without dialogs
    if not c4d.documents.MergeDocument(doc, selectedFile, c4d.SCENEFILTER_OBJECTS | c4d.SCENEFILTER_MATERIALS, None):
        raise RuntimeError("Failed to load the document.")

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
def main():
    # Checks if selected object is valid
    if op is None:
        raise ValueError("op is none, please select one object.")

    # Only continue if object is in quaternion rotation mode
    if not op.IsQuaternionRotationMode():
        raise RuntimeError("Object mode is not set to quaternion mode.")

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

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

    # Does not continue if there are no keys inside curve
    if curve.GetKeyCount() == 0:
        raise RuntimeError("There is no keys on the curve.")

    # Retrieves first key
    key = curve.GetKey(0)
    if key is None:
        raise RuntimeError("Failed to retrieve they first key of the curve.")

    # Checks quaternion interpolation is linear (SLERP)
    if key.GetQuatInterpolation() == c4d.ROTATIONINTERPOLATION_QUATERNION_SLERP:
        # If yes, change it to cubic
        key.SetQuatInterpolation(curve, c4d.ROTATIONINTERPOLATION_QUATERNION_CUBIC)

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

    #validate object and selectiontag
    if not op: return
    if not op.IsInstanceOf(c4d.Opolygon): return
    tags = op.GetTags()

    #deselect current polygonselection and store a backup to reselect
    polyselection = op.GetPolygonS()
    store = c4d.BaseSelect()
    polyselection.CopyTo(store)

    #loop through the tags and check if name and type fits
    #if so split
    t = op.GetFirstTag()
    while t:
        if t.GetType() == c4d.Tpolygonselection:
            #select polygons from selectiontag
            tagselection = t.GetBaseSelect()
            tagselection.CopyTo(polyselection)

            #split: polygonselection to a new object
            sec = utils.SendModelingCommand(
                command=c4d.MCOMMAND_SPLIT,
                list=[op],
                mode=c4d.MODELINGCOMMANDMODE_POLYGONSELECTION,
                doc=doc)

            if not sec: return
            print sec
            sec[0].InsertAfter(op)

        t = t.GetNext()

    store.CopyTo(polyselection)
    c4d.EventAdd()
Exemple #22
0
def main():
    bd = doc.GetActiveBaseDraw()
    bd[c4d.BASEDRAW_DATA_RENDERSAFE] = not bd[c4d.BASEDRAW_DATA_RENDERSAFE]
    bd[c4d.BASEDRAW_DATA_TINTBORDER] = not bd[c4d.BASEDRAW_DATA_TINTBORDER]
    bd[c4d.BASEDRAW_DATA_TINTBORDER_OPACITY] = 0.9
    c4d.EventAdd()
Exemple #23
0
    def genesis_import(self, file_path, dtu, sss_value, normal_value,
                       bump_value):
        mat = StandardMaterials.StdMaterials()
        morph = Morphs.Morphs()
        var = Utilities.Variables()
        jnt_fixes = DazRig.JointFixes()
        wgt = Weights()
        anim = Animations.Animations()
        pose = Poses()

        if os.path.exists(file_path) == False:
            gui.MessageDialog(
                "Nothing to import.\nYou have to export from DAZ Studio first",
                c4d.GEMB_OK,
            )
            return 0
        print("Import FBX from : {0}".format(os.path.dirname(file_path)))
        c4d.EventAdd()
        self.import_daz_fbx(file_path)
        c4d.EventAdd()
        c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW
                      | c4d.DRAWFLAGS_NO_THREAD
                      | c4d.DRAWFLAGS_STATICBREAK)
        dzc4d.deselect_all()  # Deselect All

        screen = c4d.gui.GeGetScreenDimensions(0, 0, True)

        c4d.EventAdd()
        dzc4d.update_viewport()
        c4d.CallCommand(300001026, 300001026)  # Deselect All
        dzc4d.del_unused_mats()
        c4d.EventAdd()

        var.store_dtu(dtu)
        if var.prepare_variables():
            gui.MessageDialog(
                "Import Failed.\nYou can check the console for more info (Shift + F10)",
                c4d.GEMB_OK,
            )
            print("Import Failed")
            return
        print("Import Done")

        print("Starting Material Updates")

        c4d.EventAdd()
        c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW
                      | c4d.DRAWFLAGS_NO_THREAD
                      | c4d.DRAWFLAGS_STATICBREAK)
        c4d.EventAdd()
        c4d.CallCommand(300001026, 300001026)  # Deselect All
        dzc4d.del_unused_mats()
        mat.store_materials(dtu)
        mat.store_sliders(sss_value, normal_value, bump_value)
        mat.update_materials()

        print("Material Conversion Done")
        c4d.EventAdd()

        wgt.store_subdivision(dtu)
        if wgt.check_level():
            auto_weight = c4d.gui.QuestionDialog(
                "Subdivisions have been detected\nthis is currently not fully supported.\nWould you like to autoweight the mesh?"
            )
            if auto_weight:
                wgt.auto_calculate_weights(var.body)

        pose.store_pose(dtu)
        pose.store_offset(dtu)
        is_posed = pose.checkIfPosed()
        is_anim = anim.check_animation_exists(var.c_joints)
        clear_pose = False
        if is_posed:
            clear_pose = gui.QuestionDialog(
                "Importing Posed Figure is currently not fully supported\nWould you like to try to fix bone orientation?",
            )
            if clear_pose:
                pose.clear_pose(var.c_joints)
                pose.fix_offset(var.c_joints, var.c_skin_data)

        if is_anim == False or clear_pose:
            jnt_fixes.store_joint_orientations(dtu)
            jnt_fixes.fix_joints(var.c_skin_data, var.c_joints, var.c_meshes)
            c4d.EventAdd()
            dzc4d.deselect_all()
            if is_posed:
                pose.restore_pose(var.c_joints)
            make_tpose = gui.QuestionDialog(
                "Would you like to Convert\nthe Base Pose to a T-Pose?", )
            if make_tpose:
                pose.preAutoIK()
                c4d.EventAdd()

        else:
            gui.MessageDialog(
                "Animation or a Pose was Detected\nJoint Orientation has not been fixed",
                type=c4d.GEMB_ICONEXCLAMATION,
            )
        c4d.EventAdd()

        if var.body.GetTag(c4d.Tposemorph):
            print("Starting Morph Updates")
            morph.store_morph_links(dtu)
            morph.store_variables(var.body, var.c_meshes, var.c_joints,
                                  var.skeleton, var.c_poses)
            morph.morphs_to_delta()
            morph.delete_morphs(var.c_meshes)
            morph.connect_morphs_to_parents(var.body, var.c_meshes)
            morph.add_drivers()
            morph.rename_morphs(var.c_meshes)
            print("Morph Corrections Done")
            c4d.EventAdd()

        c4d.DrawViews(c4d.DRAWFLAGS_ONLY_ACTIVE_VIEW
                      | c4d.DRAWFLAGS_NO_THREAD
                      | c4d.DRAWFLAGS_STATICBREAK)
        c4d.EventAdd()

        self.dialog = guiASKtoSave()
        self.dialog.Open(
            dlgtype=c4d.DLG_TYPE_MODAL,
            xpos=screen["sx2"] // 2 - 210,
            ypos=screen["sy2"] // 2 - 100,
            defaultw=200,
            defaulth=150,
        )
Exemple #24
0
def main():
    # ---------------------------------------------------------------------------------------------------
    # Setup and export AI-sequence with Sketch and Toon
    fn = c4d.storage.LoadDialog(
        c4d.FILESELECTTYPE_ANYTHING,
        "Select Save Path",
        flags=c4d.FILESELECT_DIRECTORY)  # Select path to save
    if not fn: return  # If cancelled stop the script
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    renderData = doc.GetActiveRenderData()  # Get document render data
    currVideoPost = renderData.GetFirstVideoPost()  # Get first render effect
    sntFound = False  # Initialize variable for storing info is 'Sketch and Toon' effect enabled already
    while currVideoPost is not None:  # Loop through render effects
        if currVideoPost.GetType(
        ) == 1011015:  # If 'Sketch and Toon' effect found
            sntFound = True  # Set variable to true
        currVideoPost = currVideoPost.GetNext(
        )  # Get next render effect on list
    if sntFound == False:  # If 'Sketch and Toon' effect is not enabled already
        sketchEffect = c4d.documents.BaseVideoPost(
            1011015)  # Initialize 'Sketch and Toon' effect
        renderData.InsertVideoPostLast(
            sketchEffect)  # Add 'Sketch and Toon' effect to render settings
    sketchMat = c4d.BaseMaterial(1011014)  # Initialize 'Sketch Material'
    doc.InsertMaterial(sketchMat)  # Insert material to document
    sketchTags = []  # Initialize list for 'Sketch Style' tags
    # ---------------------------------------------------------------------------------------------------
    # Export plug-in settings
    plug = plugins.FindPlugin(1012074, c4d.PLUGINTYPE_SCENESAVER)
    if plug is None:
        return
    data = {}
    if plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, data):
        if "imexporter" not in data:
            return
        aiExport = data["imexporter"]
        if aiExport is None:
            return
        # Change Illustrator export settings
        aiExport[c4d.TUAIEXPORT_OUTPUTSIZE] = 0  # Output: Render
        aiExport[c4d.TUAIEXPORT_ZSORT] = 0
        aiExport[c4d.TUAIEXPORT_SCALE] = 1  # Scale: 100%
        aiExport[c4d.TUAIEXPORT_EXPORTLINES] = 1  # Export lines
        aiExport[c4d.TUAIEXPORT_LINEOPACITY] = 0  # Disable line opacity
        aiExport[c4d.TUAIEXPORT_LINETHICKNESS] = 0  # Disable line thickness
        aiExport[c4d.TUAIEXPORT_LINEPATTERNS] = 0  # Disable line patterns
        aiExport[c4d.TUAIEXPORT_LINECONNECTIONS] = 1  # Enable line connections
        aiExport[c4d.TUAIEXPORT_EXPORTSURFACE] = 0  # Disable surface export
        aiExport[c4d.TUAIEXPORT_ANIMATION] = 1  # Export animation
        aiExport[c4d.TUAIEXPORT_ANIMTYPE] = 0  # Output As: Files
        aiExport[c4d.TUAIEXPORT_FRAMES] = 2  # Frames: Manual
        aiExport[c4d.TUAIEXPORT_FRAME_START] = doc.GetLoopMinTime(
        )  # Animation first frame
        aiExport[c4d.TUAIEXPORT_FRAME_END] = doc.GetLoopMaxTime(
        )  # Animation last frame
        aiExport[c4d.TUAIEXPORT_FRAME_RATE] = doc.GetFps()  # Frame rate
    # ---------------------------------------------------------------------------------------------------
    # Handle selected objects
    selection = doc.GetActiveObjects(
        c4d.GETACTIVEOBJECTFLAGS_0)  # Get selected objects
    for i in xrange(0, len(selection)):  # Loop through selected objects
        #sketchTags.append(c4d.BaseTag(1011012)) # Insert 'Sketch Style' tag to sketchTags list
        sketchTag = c4d.BaseTag(1011012)  # Initialize a sketch tag
        sketchTag[
            c4d.
            OUTLINEMAT_LINE_DEFAULT_MAT_V] = sketchMat  # Put sketch material to sketch tag
        sketchTag[c4d.OUTLINEMAT_LINE_SPLINES] = 1  # Enable splines
        sketchTag[c4d.OUTLINEMAT_LINE_FOLD] = 0  # Disable fold
        sketchTag[c4d.OUTLINEMAT_LINE_CREASE] = 0  # Disable crease
        sketchTag[c4d.OUTLINEMAT_LINE_BORDER] = 0  # Disable border
        selection[i].InsertTag(
            sketchTag)  # Insert sketch tag to selected object
        # ---------------------------------------------------------------------------------------------------
        folderPath = os.path.splitext(fn)[0]  # Folder path
        objectName = selection[i].GetName()  # Get object name
        os.mkdir(folderPath + "\\" + objectName)  # Create new folders
        fullFilePath = folderPath + "\\" + objectName + "\\" + objectName + ".ai"  # Full file path
        c4d.documents.SaveDocument(doc, fullFilePath,
                                   c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST,
                                   1012074)  # Export AI-file
        sketchTag.Remove()  # Delete sketch tag
    # ---------------------------------------------------------------------------------------------------
    # Remove unnecessary stuff
    #for st in sketchTags: # Loop through sketchTags
    #st.Remove() # Remove 'Sketch Style' tag
    sketchMat.Remove()  # Remove 'Sketch Material'
    if sntFound == False:  # If there was not 'Sketch and Toon' render effect already
        sketchEffect.Remove()  # Remove 'Sketch and Toon' render effect
    # ---------------------------------------------------------------------------------------------------
    c4d.StatusClear()  # Clear status bar
    c4d.StatusSetText("Export complete!")  # Set status text
    c4d.EventAdd()  # Refresh Cinema 4D
def main():
    fn = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, "Select reference file",
                      c4d.FILESELECT_LOAD)  # Load file
    if fn == None: return None  # If no file, stop the script

    # Material
    mat = c4d.BaseMaterial(c4d.Mmaterial)  # Initialize material
    mat.SetName("REFERENCE_MATERIAL")  # Set material name
    mat[c4d.MATERIAL_USE_REFLECTION] = 0  # Disable reflection channel
    mat[c4d.MATERIAL_ANIMATEPREVIEW] = 1  # Enable 'Animate Preview'
    mat[c4d.
        MATERIAL_PREVIEWSIZE] = 1  # Set 'Texture Preview Size' to 'No Scaling'
    shader = c4d.BaseShader(c4d.Xbitmap)  # Initialize bitmap shader
    shader[c4d.BITMAPSHADER_FILENAME] = fn  # Set bitmap file
    doc.ExecutePasses(None, 0, 1, 1,
                      0)  # Needed when pressing buttons virtually
    c4d.CallButton(
        shader,
        c4d.BITMAPSHADER_CALCULATE)  # Press 'Animation>Calculate' button
    mat[c4d.
        MATERIAL_COLOR_SHADER] = shader  # Set shader to material's color channel
    mat.InsertShader(shader)  # Insert shader to color channel
    mat.Message(c4d.MSG_UPDATE)  # Update material
    mat.Update(True, True)  # Update material
    irs = c4d.modules.render.InitRenderStruct(
    )  # Needed to get shader's bitmap info
    if shader.InitRender(irs) == c4d.INITRENDERRESULT_OK:
        bitmap = shader.GetBitmap()  # Get bitmap
        shader.FreeRender()  # Frees all resources used by this shader
        if bitmap is not None:  # If there is bitmap
            width = bitmap.GetSize()[0]  # Get bitmap width in pixels
            height = bitmap.GetSize()[1]  # Get bitmap height in pixels
    doc.InsertMaterial(mat)  # Insert material to document

    # Camera
    cam = c4d.BaseObject(c4d.Ocamera)  # Initialize camera object
    cam.SetName("REFERENCE_CAMERA")  # Set camera name
    cam[c4d.
        CAMERAOBJECT_TARGETDISTANCE] = width  # Set camera focus to match bitmap width
    cam[c4d.
        ID_BASEOBJECT_VISIBILITY_RENDER] = 1  # Set camera's visible in rendeerr to off
    doc.InsertObject(cam)  # Insert camera to document

    # Plane
    plane = c4d.BaseObject(c4d.Oplane)  # Initialize plane object
    plane[
        c4d.
        ID_BASEOBJECT_VISIBILITY_RENDER] = 1  # Set plane's visible in renderer to off
    plane.SetName("REFERENCE_PLANE")  # Set plane name
    plane[c4d.PRIM_AXIS] = 5  # Set plane's orientation to -z
    plane[c4d.PRIM_PLANE_SUBW] = 1  # Set plane's width segments
    plane[c4d.PRIM_PLANE_SUBH] = 1  # Set plane's height segments
    plane[c4d.PRIM_PLANE_WIDTH] = width  # Set plane's width
    plane[c4d.PRIM_PLANE_HEIGHT] = height  # Set planes height
    plane[c4d.ID_BASEOBJECT_REL_POSITION,
          c4d.VECTOR_Z] = width  # Set plane's z position
    plane.InsertUnder(cam)  # Insert plane object under camera object

    # Tags
    t = c4d.BaseTag(5616)  # Initialize texture tag
    plane.InsertTag(t)  # Insert texture tag to object
    tag = plane.GetFirstTag()  # Get object's first tag
    tag[c4d.TEXTURETAG_MATERIAL] = mat  # Set material to texture tag
    tag[c4d.TEXTURETAG_PROJECTION] = 6  # Set texture projection to uvw mapping
    d = c4d.BaseTag(5613)  # Initialize display tag
    d[c4d.DISPLAYTAG_AFFECT_DISPLAYMODE] = True  # Use custom shading mode
    d[c4d.DISPLAYTAG_SDISPLAYMODE] = 7  # Use 'Constant Shading'
    d[c4d.DISPLAYTAG_AFFECT_TEXTURES] = True  # Use textures
    plane.InsertTag(d)  # Insert display tag to object

    # Base view
    c4d.CallCommand(12544)  # Create new viewport
    bd = doc.GetActiveBaseDraw()  # Get active base draw
    bd[c4d.
       BASEDRAW_DATA_TINTBORDER_OPACITY] = 1  # Set tinted borders for base view
    bd[c4d.BASEDRAW_DATA_CAMERA] = cam  # Set base view's camera
    bd[c4d.BASEDRAW_TITLE] = "REFERENCE_VIEWPORT"  # Set base view name

    cam[c4d.ID_BASEOBJECT_REL_POSITION,
        c4d.VECTOR_X] = 5000000  # Move camera far away
    c4d.EventAdd()  # Refresh Cinema 4D
def main():
    # Checks if selected object is valid
    if op is None:
        raise ValueError("op is none, please select one object.")

    # Check if it's a polygon object
    if not op.IsInstanceOf(c4d.Opolygon):
        raise TypeError("Selected object is not a polygon Object.")

    # Defines settings for PolygonReduction.PreProcess()
    settings = c4d.BaseContainer()
    settings[c4d.POLYREDUXOBJECT_PRESERVE_3D_BOUNDARY] = True
    settings[c4d.POLYREDUXOBJECT_PRESERVE_UV_BOUNDARY] = True

    # Defines data for PolygonReduction.PreProcess()
    data = dict()
    data['_op'] = op
    data['_doc'] = doc
    data['_settings'] = settings
    data['_thread'] = None

    # Creates PolygonReduction object
    polyReduction = c4d.utils.PolygonReduction()
    if polyReduction is None:
        raise RuntimeError("Failed to create the PolygonReduction.")

    # Pre-process the data
    if not polyReduction.PreProcess(data):
        raise RuntimeError(
            "Failed to Pre-Process the PolygonReduction with data.")

    # Asks for number of edges level
    while True:
        # Opens a Dialog where user can enter a text
        userInput = c4d.gui.InputDialog("Enter number of edges level:")

        # Checks if operation was cancelled
        if userInput == "":
            return

        # Tries to convert to integer
        try:
            edgesLevel = int(userInput)
            break
        except ValueError:
            c4d.gui.MessageDialog("Please enter a number.")

    # Sets edges level number
    polyReduction.SetRemainingEdgesLevel(
        min(edgesLevel, polyReduction.GetMaxRemainingEdgesLevel()))
    polyReduction.SetRemainingEdgesLevel(
        min(edgesLevel, polyReduction.GetMaxRemainingEdgesLevel()))

    # Retrieves edges level count after reduction
    realEdgeResult = polyReduction.GetRemainingEdgesLevel()
    print("Edge Result: {0}".format(realEdgeResult))

    # Updates the original PolygonObject
    op.Message(c4d.MSG_UPDATE)

    # Pushes an update event to Cinema 4D
    c4d.EventAdd()
Exemple #27
0
    def set_up_bump_normal(self, prop, rs_material, rs):
        lib = texture_library
        bump_exists = False
        normal_exists = False

        for prop_name in lib["bump"]["Name"]:
            if prop_name in prop.keys():
                if prop[prop_name]["Texture"] != "":
                    path = prop[prop_name]["Texture"]
                    strength = prop[prop_name]["Value"]
                    strength = self.check_value("float", strength)
                    texture_node = self.create_texture_rs(path, rs, -100, -200)
                    self.set_gamma(texture_node, "Linear")
                    bump_node = rs.CreateShader("BumpMap", 0, 0)
                    bump_node[c4d.REDSHIFT_SHADER_BUMPMAP_INPUTTYPE] = 0
                    bump_node.ExposeParameter(
                        c4d.REDSHIFT_SHADER_BUMPMAP_INPUT, c4d.GV_PORT_INPUT)
                    bump_node[c4d.REDSHIFT_SHADER_BUMPMAP_SCALE] = (
                        strength * self.bump_value / 100)
                    rs_material.ExposeParameter(
                        c4d.REDSHIFT_SHADER_MATERIAL_BUMP_INPUT,
                        c4d.GV_PORT_INPUT)
                    rs.CreateConnection(texture_node, bump_node, "Out Color",
                                        "Input")
                    bump_exists = True
        for prop_name in lib["normal"]["Name"]:
            if prop_name in prop.keys():
                if prop[prop_name]["Texture"] != "":
                    path = prop[prop_name]["Texture"]
                    strength = prop[prop_name]["Value"]
                    strength = self.check_value("float", strength)
                    texture_node = self.create_texture_rs(path, rs, -100, -200)
                    self.set_gamma(texture_node, "Linear")
                    normal_node = rs.CreateShader("BumpMap", 0, 0)
                    normal_node[c4d.REDSHIFT_SHADER_BUMPMAP_INPUTTYPE] = 1
                    normal_node.ExposeParameter(
                        c4d.REDSHIFT_SHADER_BUMPMAP_INPUT, c4d.GV_PORT_INPUT)
                    normal_node[c4d.REDSHIFT_SHADER_BUMPMAP_SCALE] = (
                        strength * self.normal_value / 100)
                    rs.CreateConnection(texture_node, normal_node, "Out Color",
                                        "Input")
                    normal_exists = True

        rs_material.ExposeParameter(c4d.REDSHIFT_SHADER_MATERIAL_BUMP_INPUT,
                                    c4d.GV_PORT_INPUT)
        if normal_exists and bump_exists:
            bump_blend = rs.CreateShader("BumpBlender", 150, -200)
            bump_blend.ExposeParameter(
                c4d.REDSHIFT_SHADER_BUMPBLENDER_BASEINPUT, c4d.GV_PORT_INPUT)
            bump_blend.ExposeParameter(
                c4d.REDSHIFT_SHADER_BUMPBLENDER_BUMPINPUT0, c4d.GV_PORT_INPUT)
            bump_blend[c4d.REDSHIFT_SHADER_BUMPBLENDER_ADDITIVE] = True
            bump_blend[c4d.REDSHIFT_SHADER_BUMPBLENDER_BUMPWEIGHT0] = 1
            rs.CreateConnection(bump_node, bump_blend, "Out", "Base Input")
            rs.CreateConnection(normal_node, bump_blend, "Out", "Bump Input 0")
            rs.CreateConnection(bump_blend, rs_material,
                                "Out Displacement Vector", "Bump Input")
        elif normal_exists:
            rs.CreateConnection(normal_node, rs_material, "Out", "Bump Input")
        elif bump_exists:
            rs.CreateConnection(bump_node, rs_material, "Out", "Bump Input")
        c4d.EventAdd()
Exemple #28
0
import c4d

tag = c4d.BaseTag(c4d.Tpython)
op.InsertTag(tag)

tagCode = open(
    '/Users/gewoonsander/Library/Preferences/MAXON/CINEMA 4D R17_89538A46/library/scripts/renderme.py',
    'r')
tag[c4d.TPYTHON_CODE] = tagCode.read()

c4d.EventAdd()
Exemple #29
0
def endExport(mainDialog, exportData):
    #mainHelpers.deleteCopiedMeshes(exportData.allMeshObjects)
    if exportData is not None:
        if len(exportData.AWDerrorObjects) > 0:
            newMessage = c4d.plugins.GeLoadString(ids.ERRORMESSAGE) + "\n"
            for errorMessage in exportData.AWDerrorObjects:
                newMessage += c4d.plugins.GeLoadString(errorMessage.errorID)
                if errorMessage.errorData != None:
                    newMessage += "\n\n" + str(
                        c4d.plugins.GeLoadString(
                            ids.ERRORMESSAGEOBJ)) + " = " + str(
                                errorMessage.errorData)
            c4d.gui.MessageDialog(newMessage)
            if mainDialog.GetBool(ids.CBOX_CLOSEAFTEREXPORT) == True:
                exportData = None
                c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW | c4d.DA_NO_THREAD
                              | c4d.DA_NO_REDUCTION | c4d.DA_STATICBREAK)
                c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
                c4d.EventAdd(c4d.EVENT_ANIMATE)
                mainDialog.Close()
                return True
            exportData = None
            c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW | c4d.DA_NO_THREAD
                          | c4d.DA_NO_REDUCTION | c4d.DA_STATICBREAK)
            c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
            c4d.EventAdd(c4d.EVENT_ANIMATE)
            return True
        if len(exportData.AWDwarningObjects) > 0:
            newMessage = c4d.plugins.GeLoadString(ids.WARNINGMESSAGE) + "\n"
            for errorMessage in exportData.AWDwarningObjects:
                newMessage += c4d.plugins.GeLoadString(errorMessage.errorID)
                if errorMessage.errorData != None:
                    newMessage += "AWDWarningObject: " + str(
                        errorMessage.errorData)
            print "Warning " + str(newMessage)
            if mainDialog.GetBool(ids.CBOX_CLOSEAFTEREXPORT) == True:
                exportData = None
                c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW | c4d.DA_NO_THREAD
                              | c4d.DA_NO_REDUCTION | c4d.DA_STATICBREAK)
                c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
                c4d.EventAdd(c4d.EVENT_ANIMATE)
                mainDialog.Close()
                return True
        if mainDialog.GetBool(ids.CBOX_CLOSEAFTEREXPORT
                              ) == True and exportData.cancel != True:
            exportData = None
            c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW | c4d.DA_NO_THREAD
                          | c4d.DA_NO_REDUCTION | c4d.DA_STATICBREAK)
            c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
            c4d.EventAdd(c4d.EVENT_ANIMATE)
            mainDialog.Close()
            return True
    exportData = None
    c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW | c4d.DA_NO_THREAD
                  | c4d.DA_NO_REDUCTION | c4d.DA_STATICBREAK)
    c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)
    c4d.EventAdd(c4d.EVENT_ANIMATE)
    maindialogHelpers.enableAll(mainDialog, True)
    #print c4d.plugins.GeLoadString(ids.SUCCESSMESSAGE)
    mainHelpers.updateCanvas(mainDialog, exportData)
    c4d.EventAdd(c4d.EVENT_ANIMATE)
    mainDialog.SetTimer(0)
Exemple #30
0
def somaMake(somaLines, neuroFile, fileName):
    """Create splines to make the cell body."""

    #reference global variables that set model parameters
    global DoHN, DoConnect, DoRail, DoSweep, NSides
    
    #create spline
    Spline = c4d.BaseObject(c4d.Ospline)
    
    #add name to spline
    Spline[c4d.ID_BASELIST_NAME] = "Soma"
    
    #set type to linear
    Spline[c4d.SPLINEOBJECT_TYPE] = 0
    
    #set number of points for spline
    Spline.ResizeObject(len(somaLines))
    for n in range(0, len(somaLines)):
        currLine = somaLines[n]
        
        #create the variables for positioning the points
        sx = float(currLine[2])
        sy = float(currLine[3])
        sz = float(currLine[4])
        if coordsystem=="left":  #Convert to left-hand for C4D added by GJ March 11, 2013
            sz = -sz
        sRad = float(currLine[5])
        pos = c4d.Vector(sx, sy, sz)
        Spline.SetPoint(n, pos)
    
    #create the soma spline
    doc.InsertObject(Spline)
    
    #create sweep object
    if DoSweep == True:
        Sweep = c4d.BaseObject(c4d.Osweep)
        Sweep[c4d.ID_BASELIST_NAME] = "Soma Sweep"
        Sweep[c4d.SWEEPOBJECT_CONSTANT] = False
        Sweep[c4d.SWEEPOBJECT_RAILDIRECTION] = False
        Sweep[c4d.CAP_TYPE] = 1
        Sweep.SetPhong(True, True, 80)
        Sweep.SetDeformMode(False)
        doc.InsertObject(Sweep)
    
        #create the profile for the sweep
        Profile = c4d.BaseObject(c4d.Osplinenside)
        Profile[c4d.ID_BASELIST_NAME] = "Profile"
        Profile[c4d.PRIM_NSIDE_RADIUS] = sRad
        Profile[c4d.PRIM_NSIDE_SIDES] = NSides
        doc.InsertObject(Profile)
        
        Spline.InsertUnder(Sweep)
        Profile.InsertUnder(Sweep)
        
    #add undo for spline creation
    doc.AddUndo(c4d.UNDOTYPE_NEW, Spline)

    #insert the spline under the null object
    if DoSweep == True:
        parent = doc.SearchObject(fileName)
        Sweep.InsertUnder(parent)
            
    c4d.EventAdd()