Example #1
0
def insertObject(pX,pY,pZ,pHeight):
    obj = c4d.BaseObject(c4d.Ocube)        
    #obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(randrange(10,150),randrange(10,150),randrange(10,150))
    obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(5,5,pHeight)
    res = utils.SendModelingCommand(command = c4d.MCOMMAND_CURRENTSTATETOOBJECT,
                                    list = [obj],
                                    mode = c4d.MODELINGCOMMANDMODE_ALL,
                                    bc = c4d.BaseContainer(),
                                    doc = doc)[0] 
    res[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_X] = pX
    res[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_Y] = pY
    res[c4d.ID_BASEOBJECT_REL_POSITION,c4d.VECTOR_Z] = pZ 
                                                 
    doc.InsertObject(res)
    doc.SetActiveObject(res, c4d.SELECTION_NEW)
    c4d.EventAdd()
    sel = res.GetPolygonS()
    sel.Select(2)
    
    cubeList.append(res) 
    
    #if (x > 0):#connect this with the last cube
    #    doc.SetActiveObject(cubeList[x-1], c4d.SELECTION_ADD)                    
    
    
    #send a modeling command here
    settings = c4d.BaseContainer()                 # Settings
    settings[c4d.MDATA_EXTRUDE_OFFSET] = 50.0      # Length of the extrusion

    res = utils.SendModelingCommand(command = c4d.ID_MODELING_BRIDGE_TOOL,
                                    list = [op],
                                    mode = c4d.MODELINGCOMMANDMODE_POLYGONSELECTION,
                                    bc = settings,
                                    doc = doc)
Example #2
0
def main():
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    doc.StartUndo()  # Start recording undos
    storeMode = doc.GetMode()  # Get current editor mode
    doc.SetMode(c4d.Medges)  # Set editor mode to 'Edges'
    selection = doc.GetActiveObjects(0)  # Get active objects
    makeEditable = c4d.MCOMMAND_MAKEEDITABLE  # Mcommand 'Make Editable'
    selectAll = c4d.MCOMMAND_SELECTALL  # Mcommand 'Select All'
    edgeToSpline = c4d.MCOMMAND_EDGE_TO_SPLINE  # Mcommand 'Edge To Spline'
    modeEdgeSel = c4d.MODELINGCOMMANDMODE_EDGESELECTION  # Modeling command mode 'Edge Selection'
    createUndo = c4d.MODELINGCOMMANDFLAGS_CREATEUNDO  # Modeling command flag 'Create undo'
    bc = c4d.BaseContainer()  # Initialize base container
    u.SendModelingCommand(makeEditable, selection, modeEdgeSel, bc, doc,
                          createUndo)  # Send modeling command 'Make Editable'
    u.SendModelingCommand(selectAll, selection, modeEdgeSel, bc, doc,
                          createUndo)  # Send modeling command 'Select All'
    u.SendModelingCommand(edgeToSpline, selection, modeEdgeSel, bc, doc,
                          createUndo)  # Send modeling command 'Edge To Spline'
    for obj in selection:  # Iterate through selected objects
        spline = obj.GetDown()  # Get spline
        doc.AddUndo(c4d.UNDOTYPE_NEW,
                    spline)  # Add undo for inserting spline object
        spline.InsertAfter(obj)  # Move spline next to original object
        spline.SetMg(obj.GetMg())  # Reset spline objects matrix
        obj.Remove()  # Delete original object
    doc.SetMode(storeMode)  # Set editor mode back as it was
    doc.EndUndo()  # End recording undos
    c4d.EventAdd()  # Refresh Cinema 4D
def GetCurrentState(o):
    obj = utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
                                    list=[o],
                                    mode=c4d.MODELINGCOMMANDMODE_ALL,
                                    bc=c4d.BaseContainer(),
                                    doc=doc)
    return utils.SendModelingCommand(command=c4d.MCOMMAND_JOIN,
                                     list=obj,
                                     mode=c4d.MODELINGCOMMANDMODE_ALL,
                                     bc=c4d.BaseContainer(),
                                     doc=doc)
Example #4
0
    def BreakPhongEdges(self, obj):
        settings = c4d.BaseContainer()

        # First step. Unbreak all edges
        self._doc.AddUndo(c4d.UNDOTYPE_CHANGE_NOCHILDREN, obj)
        utils.SendModelingCommand(c4d.MCOMMAND_UNBREAKPHONG, [obj],
                                  c4d.MODELINGCOMMANDMODE_ALL, settings,
                                  self._doc)

        # Second. Break Phong shading based on selected edges
        self._doc.AddUndo(c4d.UNDOTYPE_CHANGE_NOCHILDREN, obj)
        utils.SendModelingCommand(c4d.MCOMMAND_BREAKPHONG, [obj],
                                  c4d.MODELINGCOMMANDMODE_EDGESELECTION,
                                  settings, self._doc)
Example #5
0
def main():
    path = c4d.storage.SaveDialog()
    for child in op.GetChildren():
        count = 0
        tempSelectList = list()
        tempSelectName = list()
        for tag in child.GetTags():
            if isinstance(
                    tag,
                    c4d.SelectionTag) and tag.GetName().startswith("Piece"):
                count += 1
            elif isinstance(tag, c4d.SelectionTag
                            ) and not tag.GetName().startswith("Piece"):
                tempSelection = c4d.BaseSelect()
                tag.GetBaseSelect().CopyTo(tempSelection)
                tempSelectList.append(tempSelection)
                tempSelectName.append(tag.GetName())
                child.KillTag(c4d.Tpolygonselection, count)
        lastTag = child.GetLastTag()
        for index, selection in enumerate(tempSelectList):
            newTag = child.MakeTag(c4d.Tpolygonselection, lastTag)
            newTag.SetName(tempSelectName[index])
            selection.CopyTo(newTag.GetBaseSelect())

        count = 0
        for tag in child.GetTags():
            if isinstance(
                    tag,
                    c4d.SelectionTag) and tag.GetName().startswith("Piece"):
                newselection = child.GetPolygonS()
                newselection.DeselectAll()
                selection = tag.GetBaseSelect().CopyTo(newselection)

                secList = utils.SendModelingCommand(
                    command=c4d.MCOMMAND_SPLIT,
                    list=[child],
                    mode=c4d.MODELINGCOMMANDMODE_POLYGONSELECTION,
                    doc=doc)
                if secList:
                    sec = secList[0]
                    sec.SetName(tag.GetName())
                    sec.InsertAfter(op)
                    for i in range(count):
                        sec.KillTag(c4d.Tpolygonselection)

                    fbxPath = path + '_' + str(count) + '.fbx'
                    c4dPath = path + '_' + str(count) + '.c4d'
                    print(fbxPath)
                    newDoc = c4d.documents.IsolateObjects(doc, [sec])
                    obj = newDoc.GetFirstObject()
                    newDoc.SetSelection(obj, c4d.SELECTION_NEW)
                    c4d.documents.SaveDocument(
                        newDoc, fbxPath,
                        c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, 1026370)
                    c4d.documents.SaveDocument(
                        newDoc, c4dPath,
                        c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST,
                        c4d.FORMAT_C4DEXPORT)
                    sec.Remove()
                    count += 1
Example #6
0
def insertObject(pX, pY, pZ, pWidth, pHeight, pDepth, pIndex):
    #INSERT A CUBE
    obj = c4d.BaseObject(c4d.Ocube)
    obj[c4d.PRIM_CUBE_SUBX] = 2
    obj[c4d.PRIM_CUBE_SUBY] = 2
    obj[c4d.PRIM_CUBE_SUBZ] = 2

    #INITIAL TEXTURE FOR STRUCTURE
    tex = obj.MakeTag(c4d.Ttexture)
    tex[c4d.TEXTURETAG_MATERIAL] = doc.SearchMaterial("dk_gray_metal")
    tex[c4d.TEXTURETAG_PROJECTION] = 6  #UVW

    obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(pWidth, pHeight, pDepth)
    res = utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
                                    list=[obj],
                                    mode=c4d.MODELINGCOMMANDMODE_ALL,
                                    bc=c4d.BaseContainer(),
                                    doc=doc)[0]
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X] = pX
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Y] = pY
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z] = pZ
    res[c4d.ID_BASELIST_NAME] = "cuby_" + str(pIndex)

    doc.InsertObject(res)
    doc.SetActiveObject(res, c4d.SELECTION_NEW)
    c4d.EventAdd()

    #EXTRUDE THE SURFACES TO RANDOM LENGTHS
    sel = res.GetPolygonS()
    c4d.CallCommand(12187)  # Polygons

    saveToPath = "D:\_projects\3d_sandbox\cubic_transformations\render\cuby_"
    outerCounter = 1
    innerCounter = 1

    for growthCounter in range(0, 10):
        for f in range(0, 23):
            c4d.CallCommand(13324)  # Deselect All
            sel.Select(f)

            c4d.CallCommand(1011183)  # Extrude
            getTool()[c4d.MDATA_EXTRUDE_OFFSET] = randrange(10, 40) * 1.0
            fireAction(obj)

        #print(saveToPath + str(outerCounter) + "_" + str(innerCounter))
        #kick out a render
        doc[c4d.RDATA_PATH] = ""
        c4d.CallCommand(12098)  # Save
        c4d.CallCommand(12099)  # Render to Picture Viewer
        #time.sleep(1)
        innerCounter = innerCounter + 1

        outerCounter = outerCounter + 1
        '''
        doc[c4d.RDATA_PATH] = "D:\_projects\3d_sandbox\cubic_transformations\render\cuby_" + str(growthCounter) + str(f)
        c4d.CallCommand(465003525) # Add to Render Queue...
        c4d.CallCommand(465003513) # Start Rendering
        '''

    return obj
Example #7
0
def main():
    # Creates Voronoi Fracture object and inserts it into the active document
    voronoi = c4d.VoronoiFracture()
    doc.InsertObject(voronoi)
    
    # Creates Cube object and inserts it into the active document
    cube = c4d.BaseObject(c4d.Ocube)
    doc.InsertObject(cube)
    
    # Makes it editable and finally insert it as child of Voronoi Fracture object
    editable = utils.SendModelingCommand(c4d.MCOMMAND_MAKEEDITABLE, list=[cube], mode=c4d.MODIFY_ALL, doc=doc)
    doc.InsertObject(editable[0], parent=voronoi)
    
    # Adds a point generator
    ret = voronoi.AddPointGenerator(c4d.ID_POINTCREATOR_CREATORTYPE_DISTRIBUTION)
    generator = ret[0]
    generator[c4d.ID_POINTCREATOR_CREATEDPOINTAMOUNT] = 25
    generator[c4d.ID_POINTCREATOR_CREATEPOINTSSEED] = 73519
    
    # Adds a shader generator
    ret = voronoi.AddPointGenerator(c4d.ID_POINTCREATOR_CREATORTYPE_SHADER)
    generator = ret[0]
    
    # Setups Noise shader
    noise = c4d.BaseShader(c4d.Xnoise)
    noise[c4d.SLA_NOISE_NOISE] = c4d.NOISE_OFFSET+c4d.NOISE_VORONOI_3
    
    # Sets the shader for the generator
    generator[c4d.ID_POINTCREATOR_SHADER_SHADER] = noise
    generator.InsertShader(noise)
    generator.Message(c4d.MSG_UPDATE)
    
    c4d.EventAdd()
Example #8
0
def ptToEdg(obj, frm, to):
    bc = c4d.BaseContainer()
    bc.SetInt32(c4d.MDATA_CONVERTSELECTION_LEFT, frm)
    bc.SetInt32(c4d.MDATA_CONVERTSELECTION_RIGHT, to)
    bc.SetBool(c4d.MDATA_CONVERTSELECTION_TOLERANT, False)

    res = utils.SendModelingCommand(command=c4d.MCOMMAND_CONVERTSELECTION,
                                    list=[obj],
                                    mode=c4d.MODELINGCOMMANDMODE_EDGESELECTION,
                                    bc=bc,
                                    doc=None)
    def BreakShading(cls, obj):
        # Save original selected edges
        originalEdgeS = obj.GetEdgeS().GetClone()

        # Smooth (unbreak) all edges
        settings = c4d.BaseContainer()
        doc.AddUndo(c4d.UNDOTYPE_CHANGE_NOCHILDREN, obj)
        utils.SendModelingCommand(c4d.MCOMMAND_UNBREAKPHONG, [obj],
                                  c4d.MODELINGCOMMANDMODE_ALL, settings, doc)

        cls.SelectUVBorders(obj)

        doc.AddUndo(c4d.UNDOTYPE_CHANGE_NOCHILDREN, obj)
        utils.SendModelingCommand(c4d.MCOMMAND_BREAKPHONG, [obj],
                                  c4d.MODELINGCOMMANDMODE_EDGESELECTION,
                                  settings, doc)

        doc.AddUndo(c4d.UNDOTYPE_CHANGE_SELECTION, obj)

        # Restore original selected edges
        originalEdgeS.CopyTo(obj.GetEdgeS())
def get_connected_polygons(obj, remaining_polygons):
    # type: (PolygonObject, List[int]) -> List[int]
    bs = obj.GetPolygonS()
    bs.DeselectAll()
    bs.Select(remaining_polygons[0])
    utils.SendModelingCommand(command=c4d.MCOMMAND_SELECTCONNECTED,
                              list=[obj],
                              mode=c4d.MODELINGCOMMANDMODE_POLYGONSELECTION,
                              bc=BaseContainer(),
                              doc=doc)
    result = []
    for polygon_index in remaining_polygons:
        if bs.IsSelected(polygon_index):
            result.append(polygon_index)

    return result
Example #11
0
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)
    
    #define the name to search for
    name = "Polygon Selection"
        
        
    #loop through the tags and check if name and type fits
    #if so split 
    t = op.GetFirstTag()
    while t:
        if t.GetType() == c4d.Tpolygonselection:
            if name in t.GetName():

                #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()
def insertObject(pX, pY, pZ, pHeight, pIndex):
    obj = c4d.BaseObject(c4d.Ocube)

    obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(5, 5, pHeight)
    res = utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
                                    list=[obj],
                                    mode=c4d.MODELINGCOMMANDMODE_ALL,
                                    bc=c4d.BaseContainer(),
                                    doc=doc)[0]
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X] = pX
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Y] = pY
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z] = pZ
    res[c4d.ID_BASELIST_NAME] = "tile_" + str(pIndex)

    doc.InsertObject(res)
    doc.SetActiveObject(res, c4d.SELECTION_NEW)
    c4d.EventAdd()
    #sel = res.GetPolygonS()
    #sel.Select(2)

    cubeList.append(res)
Example #13
0
        def removeMoisureTag(obj):
            # validate object and selectiontag
            if not obj:
                return
            if not obj.IsInstanceOf(c4d.Opolygon):
                return
            tags = obj.GetTags()

            # deselect current polygonselection and store a backup to reselect
            polyselection = obj.GetPolygonS()

            # define the name to search for
            name = "EyeMoisture"

            # loop through the tags and check if name and type fits
            # if so split
            t = obj.GetFirstTag()
            while t:
                if t.GetType() == c4d.Tpolygonselection:
                    if name in t.GetName():

                        # select polygons from selectiontag
                        tagselection = t.GetBaseSelect()
                        tagselection.CopyTo(polyselection)

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

                        if not sec:
                            print(sec)
                            return

                t = t.GetNext()

            c4d.EventAdd()
Example #14
0
def insertObject(pX, pY, pZ, pHeight):
    obj = c4d.BaseObject(c4d.Ocube)
    #obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(randrange(10,150),randrange(10,150),randrange(10,150))
    obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(5, 5, pHeight)
    obj[c4d.PRIM_CUBE_SUBX] = 4
    obj[c4d.PRIM_CUBE_SUBY] = 4
    obj[c4d.PRIM_CUBE_SUBZ] = 4

    res = utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
                                    list=[obj],
                                    mode=c4d.MODELINGCOMMANDMODE_ALL,
                                    bc=c4d.BaseContainer(),
                                    doc=doc)[0]

    #res[c4d.PRIM_CUBE_DOFILLET] = True
    #res[c4d.PRIM_CUBE_FRAD] = 2
    #res[c4d.PRIM_CUBE_SUBF] = 3
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X] = pX
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Y] = pY
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z] = pZ

    doc.InsertObject(res)
    doc.SetActiveObject(res, c4d.SELECTION_NEW)
    c4d.EventAdd()
Example #15
0
def do_one_file(inputfile):
    helper = helperClass()

    inputStructure = inputfile.split('-')[0]
    inputStage = inputfile.split('-')[1]
    print('inputStructure ' + inputStructure)
    print('inputStage ' + inputStage)

    outputDirectory = os.path.join(outputBasePath,
                                   outputStructures[inputStructure],
                                   outputStages[inputStage])
    print(outputDirectory)
    inputfile = inputfile + '.obj'

    c4d.documents.LoadFile(
        os.path.join(current_dir, 'base-visual-cell-maker-file.c4d'))
    doc = helper.getCurrentScene()

    filename = inputfile
    file_to_load = os.path.join(loadpath, filename)

    # Import without dialogs
    c4d.documents.MergeDocument(doc, file_to_load, c4d.SCENEFILTER_OBJECTS,
                                None)
    c4d.EventAdd()

    # get the main object
    target_obj = helper.getObject(filename)
    print(target_obj.GetName())

    tp = target_obj.GetDown()
    while tp is not None:
        print("tp name = ", tp.GetName())
        i = int(tp.GetName()[-1])
        doc.SetSelection(tp)

        # getting rid of tags that came from chimera
        tp.KillTag(c4d.Tnormal)
        tp.KillTag(c4d.Ttexture)
        tp.KillTag(c4d.Tphong)
        tp.MakeTag(c4d.Tphong)

        c4d.CallCommand(14039, 14039)  # Optimize
        c4d.CallCommand(14039, 14039)  # Optimize

        # doc.InsertObject(smoothing_deformer)
        #        reducer = c4d.BaseObject(1001253) # Polgyon reduction
        #        reducer[c4d.POLYREDUCTIONOBJECT_STRENGTH] = settings[i]['polygonReduction']
        #        helper.setName(reducer, "Polygon_Reduction_"+tp.GetName())
        #        helper.AddObject(reducer, parent=tp)

        #     displacer = helper.getObject("displacer_" + str(i))
        #       helper.reParent(displacer, tp)
        if i == 1:
            CellMembraneHolster = helper.getObject("Holster_1")
            while CellMembraneHolster.GetDown() is not None:  # tp is not None:
                helper.reParent(CellMembraneHolster.GetDown(), tp)
        if i == 2:
            DNAHolster = helper.getObject("Holster_2")
            while DNAHolster.GetDown() is not None:  # tp is not None:
                helper.reParent(DNAHolster.GetDown(), tp)
        if i == 3:
            StructureHolster = helper.getObject("Holster_3")
            while StructureHolster.GetDown() is not None:  # tp is not None:
                helper.reParent(StructureHolster.GetDown(), tp)


#        smoothing_deformer = c4d.BaseObject(1024529) # smoothing deformer
#        smoothing_deformer[c4d.ID_CA_SMOOTHING_DEFORMER_OBJECT_STRENGTH] = settings[i]['smoothStrength']
#        helper.setName(smoothing_deformer, "Smoothing_"+tp.GetName())
#        helper.AddObject(smoothing_deformer, parent=tp)

        tp = tp.GetNext()

    res = utils.SendModelingCommand(
        command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
        list=[target_obj],
        doc=doc,
        # flags = c4d.MODELINGCOMMANDFLAGS_CREATEUNDO
    )
    res = res[0]
    helper.setName(res, helper.getName(res) + '_reduced')
    print("created reduced object")
    helper.AddObject(res)

    doc.SetSelection(target_obj)
    target_obj[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 1
    c4d.EventAdd()

    # return

    #   c4d.documents.SaveDocument(doc, os.path.join(current_dir, 'gj.c4d'), c4d.SAVEDOCUMENTFLAGS_0, c4d.FORMAT_C4DEXPORT)
    c4d.documents.SaveDocument(
        doc, os.path.join(outputDirectory,
                          inputStructure + '_prebake' + '.c4d'),
        c4d.SAVEDOCUMENTFLAGS_0, c4d.FORMAT_C4DEXPORT)

    print("deleting original target object")
    target_obj.Remove()
    c4d.EventAdd()

    material = doc.GetFirstMaterial()
    tp = res.GetDown()

    # enter polygon edit mode
    c4d.CallCommand(12187)  # Polygons

    while tp is not None:
        print("make texture tag")
        texture = tp.MakeTag(c4d.Ttexture)
        texture[
            c4d.TEXTURETAG_PROJECTION] = c4d.TEXTURETAG_PROJECTION_SPHERICAL
        texture[c4d.TEXTURETAG_MATERIAL] = material

        doc.SetSelection(texture)

        # makes a uvw tag on the object
        c4d.CallCommand(12235, 12235)  # Generate UVW Coordinates
        print("generate uvw coords")
        doc.SetSelection(tp.GetTag(c4d.Tuvw))

        uvsettings = c4d.BaseContainer()
        uvsettings.SetBool(c4d.OPTIMALMAPPING_PRESERVEORIENTATION, False)
        uvsettings.SetBool(c4d.OPTIMALMAPPING_STRETCHTOFIT, True)
        uvsettings.SetFloat(c4d.OPTIMALMAPPING_DISTORTION, 0.01)
        uvsettings.SetInt32(c4d.OPTIMALMAPPING_RELAXCOUNT, 0)
        uvsettings.SetFloat(c4d.OPTIMALMAPPING_SPACING, 0.01)

        print("get active uv set")

        uvset = c4d.modules.bodypaint.GetActiveUVSet(doc,
                                                     c4d.GETACTIVEUVSET_ALL)

        uvw = uvset.GetUVW()

        #  if tp.GetName()[-2:] == '_2': #switch these ifs for expensive structures during debugging
        if 1 == 1:
            uv_ok = c4d.modules.bodypaint.CallUVCommand(
                uvset.GetPoints(), uvset.GetPointCount(), uvset.GetPolys(),
                uvset.GetPolyCount(), uvw, uvset.GetPolySel(),
                uvset.GetUVPointSel(), tp, c4d.Mpolygons,
                c4d.UVCOMMAND_OPTIMALMAPPING, uvsettings)
            print("call uv command:", uv_ok)

        uvset.SetUVWFromTextureView(uvw, True, True, True)
        c4d.modules.bodypaint.FreeActiveUVSet(uvset)

        tp = tp.GetNext()

    subdiv = helper.getObject("Subdivision Surface")

    tp = res.GetDown()
    i = 0
    membraneobj = None
    while i < 3:
        if tp.GetName()[-2:] == '_1':
            membraneobj = tp
            break
        tp = tp.GetNext()
        i = i + 1

    children = []
    tp = res.GetDown()
    while tp is not None:  # tp is not None:
        children.append(tp)
        tp = tp.GetNext()

    for tp in children:  # tp is not None:
        if tp.GetName() == membraneobj.GetName():
            # switch object on
            membraneobj[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 2
        else:
            # switch object off
            membraneobj[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 1

        if tp.GetName(
        )[-2:] != '_2':  # do not subdivide the nucleus before baking
            print("reparent to subdiv for baking")
            helper.reParent(tp, subdiv)

        bake = c4d.BaseContainer()
        bake.SetBool(c4d.BAKE_TEX_AMBIENT_OCCLUSION, True)
        bake.SetInt32(c4d.BAKE_TEX_WIDTH, 1024)
        bake.SetInt32(c4d.BAKE_TEX_HEIGHT, 1024)
        bake.SetInt32(c4d.BAKE_TEX_PIXELBORDER, 3)
        bake.SetInt32(c4d.BAKE_TEX_SUPERSAMPLING, 0)
        (bakedoc, result) = c4d.utils.InitBakeTexture(doc,
                                                      tp.GetTag(c4d.Ttexture),
                                                      tp.GetTag(c4d.Tuvw),
                                                      None, bake)
        if result != c4d.BAKE_TEX_ERR_NONE:
            print("InitBakeTexture error")
        else:
            output_bmp = c4d.bitmaps.MultipassBitmap(1024, 1024,
                                                     c4d.COLORMODE_ARGB)
            bakeobj = BakeOneObj(
                output_bmp,
                os.path.join(outputDirectory,
                             fileNames[int(tp.GetName()[-1:])] + '_ao.jpg'))
            print("BakeTexture " + fileNames[int(tp.GetName()[-1:])])
            c4d.utils.BakeTexture(bakedoc, bake, output_bmp, None,
                                  bakeobj.onbakeprogress)
            bakeobj.wait()
            print("done baking, reparenting to done")
            helper.reParent(tp, helper.getObject('done'))

        c4d.EventAdd()

        # print(fileNames[int(tp.GetName()[-1:])] + '_ao')

        # print("reparent to done")
        # helper.reParent(tp, res)

    # done with "res" since everything is reparented to "done"
    doc.SetSelection(res)
    res[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 1
    c4d.EventAdd()
    res.Remove()
    c4d.EventAdd()

    tp = helper.getObject('done').GetDown()
    # while tp is not None: # tp is not None:
    for tp in children:
        # rotate by 90 degrees
        tp.SetAbsRot(c4d.Vector(0, c4d.utils.DegToRad(-90), 0))
        newdoc = c4d.documents.IsolateObjects(doc, [tp])
        c4d.documents.SaveDocument(
            newdoc,
            os.path.join(outputDirectory,
                         fileNames[int(tp.GetName()[-1:])] + '.obj'),
            c4d.SAVEDOCUMENTFLAGS_0, c4d.FORMAT_OBJ2EXPORT)
        print(fileNames[int(tp.GetName()[-1:])] + '.obj')
        c4d.EventAdd()
        c4d.documents.KillDocument(newdoc)
        c4d.EventAdd()

    doc.SetDocumentName('tmp')
    c4d.documents.SaveDocument(doc, os.path.join(current_dir, 'tmp.c4d'),
                               c4d.SAVEDOCUMENTFLAGS_0, c4d.FORMAT_C4DEXPORT)
    c4d.EventAdd()
    c4d.documents.KillDocument(doc)
    c4d.documents.CloseAllDocuments()
def insertObject(pX, pY, pZ, pWidth, pHeight, pDepth, pIndex):
    #INSERT A CUBE
    obj = c4d.BaseObject(c4d.Ocube)
    obj[c4d.PRIM_CUBE_SUBX] = 2
    obj[c4d.PRIM_CUBE_SUBY] = 2
    obj[c4d.PRIM_CUBE_SUBZ] = 2

    obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(pWidth, pHeight, pDepth)
    res = utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
                                    list=[obj],
                                    mode=c4d.MODELINGCOMMANDMODE_ALL,
                                    bc=c4d.BaseContainer(),
                                    doc=doc)[0]
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X] = pX
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Y] = pY
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z] = pZ
    res[c4d.ID_BASELIST_NAME] = "cuby_" + str(pIndex)

    doc.InsertObject(res)
    doc.SetActiveObject(res, c4d.SELECTION_NEW)
    c4d.EventAdd()

    #EXTRUDE THE SURFACES TO RANDOM LENGTHS
    sel = res.GetPolygonS()
    c4d.CallCommand(12187)  # Polygons

    #PASS 1 - CREATE A BASE SHAPE
    for growthCounter in range(0, 100):
        for f in range(0, 23):
            c4d.CallCommand(13324)  # Deselect All
            sel.Select(f)

            c4d.CallCommand(1011183)  # Extrude
            getTool()[c4d.MDATA_EXTRUDE_OFFSET] = randrange(10, 40) * 1.0
            fireAction(obj)

    #PASS 2 - ADD EXTRUSIONS TO RANDOM FACES
    sel = res.GetPolygonS()
    c4d.CallCommand(12187)  # Polygons

    for f in range(0, 500):

        c4d.CallCommand(13324)  # Deselect All
        sel.Select(f)

        #INNER EXTRUDE
        c4d.CallCommand(450000004)  # Extrude Inner
        getTool()[c4d.MDATA_EXTRUDEINNER_OFFSET] = randrange(2, 30) * 1.0
        fireAction(obj)

        #OUTER
        c4d.CallCommand(1011183)  # Extrude
        getTool()[c4d.MDATA_EXTRUDE_OFFSET] = randrange(9, 30) * -1.0
        fireAction(obj)

    #kick out a render
    doc[c4d.RDATA_PATH] = ""
    c4d.CallCommand(12098)  # Save
    c4d.CallCommand(12099)  # Render to Picture Viewer

    return obj
Example #17
0
def sendModCom(obj):
    utils.SendModelingCommand(command=c4d.MCOMMAND_EDGE_TO_SPLINE,
                              list=[obj],
                              mode=c4d.MODELINGCOMMANDMODE_EDGESELECTION,
                              doc=None)
Example #18
0
def main():
    class polys:
        def __init__(self, ind, polygon):
            self.Id = ind
            self.polyst = polygon
            self.triangle = self.polyst.IsTriangle()

    obj = doc.GetActiveObject()
    all_polys = obj.GetAllPolygons()
    select = obj.GetPolygonS().GetAll(obj.GetPolygonCount())
    select_list = []
    for i in range(obj.GetPolygonCount()):  ### make select polys list
        a = polys(i, all_polys[i])
        if select[i] == 1:
            select_list.append(a)
    for i in range(len(select_list)):  ### print select polys
        print select_list[i].Id, "  ", select_list[i].polyst
    new_list = []
    for i in range(len(select_list)):
        polycount = obj.GetPolygonCount()
        pointcount = obj.GetPointCount()
        if select_list[i].triangle == 0:
            n = []
            n.append(obj.GetPoint(select_list[i].polyst.a))
            n.append(obj.GetPoint(select_list[i].polyst.b))
            n.append(obj.GetPoint(select_list[i].polyst.c))
            n.append(obj.GetPoint(select_list[i].polyst.d))
            obj.ResizeObject(pointcount + 4, polycount + 1)
            index = []
            for k in range(len(n)):
                obj.SetPoint(pointcount + k, n[k])
                index.append(pointcount + k)
            poly = c4d.CPolygon(index[0], index[1], index[2], index[3])
            obj.SetPolygon(polycount, poly)
            obj.Message(c4d.MSG_UPDATE)

        else:
            n = []
            n.append(obj.GetPoint(select_list[i].polyst.a))
            n.append(obj.GetPoint(select_list[i].polyst.b))
            n.append(obj.GetPoint(select_list[i].polyst.c))
            obj.ResizeObject(pointcount + 3, polycount + 1)
            index = []
            for k in range(len(n)):
                obj.SetPoint(pointcount + k, n[k])
                index.append(pointcount + k)
            poly = c4d.CPolygon(index[0], index[1], index[2])
            obj.SetPolygon(polycount, poly)
            obj.Message(c4d.MSG_UPDATE)
        new_list.append(polycount)
    print new_list
    select = obj.GetPolygonS()
    select.DeselectAll()
    for i in range(len(new_list)):
        select.Select(new_list[i])
    settings = c4d.BaseContainer()
    settings[c4d.MDATA_OPTIMIZE_TOLERANCE] = 0.01
    settings[c4d.MDATA_OPTIMIZE_POINTS] = True
    settings[c4d.MDATA_OPTIMIZE_POLYGONS] = True
    settings[c4d.MDATA_OPTIMIZE_UNUSEDPOINTS] = True
    utils.SendModelingCommand(command=c4d.MCOMMAND_OPTIMIZE,
                              list=[op],
                              mode=c4d.MODELINGCOMMANDMODE_POLYGONSELECTION,
                              bc=settings,
                              doc=doc)
Example #19
0
def main():
	exportpath = "c:/vbnet"
	user = os.getenv('username') # Windows Loginname
	stlpath= exportpath+"/"+user+"/"
	tree = etree.parse(exportpath+"/"+user+".xml")
	xmlroot = tree.getroot()
	for child in xmlroot:
		Kunde.append(child.find('CUSTOM_PROPERTY_VALUE').text)
		Nummer.append(child.find('DRAWING_NAME').text)
		Blockname.append(child.find('BLOCKNAME').text)
		BlocknameSort.append(child.find('BLOCKNAME').text)
		File.append(child.find('STL_FILENAME').text)
		Shift.append(child.find('SHIFT').text)
		DirNameC4d.append(child.find('SAVEPATHC4DFILE').text)
		DirNameRender.append(child.find('SAVEPATHRENDEROUTPUT').text)
	BlocknameSort.sort()
	BlocknameSort.reverse()
	dirList=os.listdir(stlpath)
	bc = c4d.BaseContainer()
	bc.SetData(c4d.MDATA_UNTRIANGULATE_NGONS, False)
	bc.SetData(c4d.MDATA_UNTRIANGULATE_ANGLE_RAD, .5)

	root = c4d.BaseObject(c4d.Onull) # Create new Null
	root.SetRelPos(c4d.Vector(0))   # Set position
	root.SetName(Kunde[0]+"_"+Nummer[0])
	doc = documents.GetActiveDocument()
	doc.InsertObject(root)
	oldblock = ""
	index = 0
	for item in BlocknameSort:
		if item != oldblock and item != "empty":
			blockroot = c4d.BaseObject(c4d.Onull)
			blockroot.SetRelPos(c4d.Vector(0))
			blockroot.SetName(item)
			doc.InsertObject(blockroot)
			blockroot.InsertUnder(root)
			oldblock = item
	for fname in dirList:
		# print fname
		filepath=stlpath+fname
		c4d.documents.MergeDocument(doc,filepath,c4d.SCENEFILTER_OBJECTS)
		c4d.EventAdd() #refresh the scene.
	for fname in File:
		obj = doc.SearchObject(fname)
		if Blockname[index] == "empty":
			grp = root
		elif Blockname[index] == "__SOLIDS":
			grp = doc.SearchObject(Blockname[index])
		else:
			grp = doc.SearchObject(Blockname[index])
			tmpstring = obj.GetName().replace(grp.GetName() + "_", "")
			tmpstring2 = tmpstring.split("_")
			obj.SetName(tmpstring[len(tmpstring2[0])+1:])
		index = index + 1
		utils.SendModelingCommand(c4d.MCOMMAND_UNTRIANGULATE, list = [obj], mode = c4d.MODIFY_ALL, bc=bc, doc = doc)
		obj.MakeTag(c4d.Tphong)
		obj.SetPhong(True, True, c4d.utils.Rad(20))
		if Shift[0] == "True":
			obj.SetAbsPos(c4d.Vector(-10000,-10000,-10000))
		obj.InsertUnder(grp)
		#tmpstring = obj.GetName().replace(grp.GetName() + "_", "")
		#tmpstring2 = tmpstring.split("_")
		#obj.SetName(tmpstring[len(tmpstring2[0])+1:])
	c4d.EventAdd() #refresh the scene.
	c4d.CallCommand(100004767) # Deselect All
	MessageBox = ctypes.windll.user32.MessageBoxA  # MessageBoxA in Python2, MessageBoxW in Python3
	if(DirNameRender[0] != "" and ("Untitled" in doc.GetDocumentName() or "Ohne Titel" in doc.GetDocumentName())):
		mbid = MessageBox(None, 'In den Rendervoreinstellungen den Dateipfad anpassen...', 'Pfade Anpassen?', MB_YESNO | ICON_INFO)
		if mbid == IDYES:
			rDat = doc.GetActiveRenderData()
			rDat[c4d.RDATA_PATH] = DirNameRender[0]+"\\"+Nummer[0].replace(".", "-")+"-$take"
		else:
			pass
	else:
		print("Keine neues Projekt: "+doc.GetDocumentName())
	num = Nummer[0].replace(".", "-")
	if(os.path.exists(DirNameC4d[0]+"\\"+num)):
		print(DirNameC4d[0]+"\\"+num+" path already exist!!!")
		print("Current Document Name: "+doc.GetDocumentName())
		mbid1 = MessageBox(None, "Ein Projekt mit dieser Nummer existiert bereits: "+num, "Info", MB_OK | ICON_INFO)
		if mbid1 == IDOK:
			print("Datei existiert bereits Meldung bestaetigt.")
			pass
		else:
			pass
	elif("Untitled" in doc.GetDocumentName() or "Ohne Titel" in doc.GetDocumentName()):
		mbid2 = MessageBox(None, "Projekt inkl. Assets Sichern: "+num, "Speichern?", MB_YESNO | ICON_INFO)
		if mbid2 == IDYES:
			print(DirNameC4d[0]+"\\"+num)
			missingAssets = []
			assets = []
			c4d.documents.SaveProject(doc, c4d.SAVEPROJECT_ASSETS | c4d.SAVEPROJECT_SCENEFILE | c4d.SAVEPROJECT_DIALOGSALLOWED, DirNameC4d[0]+"\\"+num, assets, missingAssets)
		else:
			pass
	else:
		print("Projekt ist bereits an einem anderen Ort gespeichert. Current Document Name: "+doc.GetDocumentName())
Example #20
0
def Command_CSTO(op):
    res = utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT, list=[op], doc=doc)
    if res is False:
        return None
    return res[0]
def insertObject(pX, pY, pZ, pWidth, pHeight, pDepth, pIndex):
    #INSERT A CUBE
    obj = c4d.BaseObject(c4d.Ocube)
    obj[c4d.PRIM_CUBE_SUBX] = 2
    obj[c4d.PRIM_CUBE_SUBY] = 2
    obj[c4d.PRIM_CUBE_SUBZ] = 2

    #INITIAL TEXTURE FOR STRUCTURE
    #tex = obj.MakeTag(c4d.Ttexture)
    #tex[c4d.TEXTURETAG_MATERIAL] = doc.SearchMaterial("dk_gray_metal")
    #tex[c4d.TEXTURETAG_PROJECTION] = 6 #UVW

    obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(pWidth, pHeight, pDepth)
    res = utils.SendModelingCommand(command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
                                    list=[obj],
                                    mode=c4d.MODELINGCOMMANDMODE_ALL,
                                    bc=c4d.BaseContainer(),
                                    doc=doc)[0]
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X] = pX
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Y] = pY
    res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z] = pZ
    res[c4d.ID_BASELIST_NAME] = "cuby_" + str(pIndex)

    doc.InsertObject(res)
    doc.SetActiveObject(res, c4d.SELECTION_NEW)
    c4d.EventAdd()

    #EXTRUDE THE SURFACES TO RANDOM LENGTHS
    sel = res.GetPolygonS()
    c4d.CallCommand(12187)  # Polygons

    #PASS 1 - CREATE A BASE SHAPE
    for growthCounter in range(0, 10):
        for f in range(0, 23):
            c4d.CallCommand(13324)  # Deselect All
            sel.Select(f)

            c4d.CallCommand(1011183)  # Extrude
            getTool()[c4d.MDATA_EXTRUDE_OFFSET] = randrange(10, 40) * 1.0
            fireAction(obj)

    #PASS 2 - ADD EXTRUSIONS TO RANDOM FACES
    c4d.CallCommand(12187)  # Polygons
    polygonsList = res.GetPolygonS()

    polygonsList.DeselectAll()

    #USE THIS TO GET A POLY COUNT
    #GetPolygonCount()

    for f in range(0, 120):
        #polygonsList.DeselectAll()
        polygonsList.Select(f)

        #ADD POLYGON SELECTION
        polySelectionTag = res.MakeTag(c4d.Tpolygonselection)
        polySelectionTag[c4d.ID_BASELIST_NAME] = "foo_" + str(f)
        baseSelect = polySelectionTag.GetBaseSelect()

        baseSelect.Select(f)

        newTex = res.MakeTag(c4d.Ttexture)
        newTex[c4d.TEXTURETAG_MATERIAL] = doc.SearchMaterial("lt_gray_metal")
        newTex[c4d.TEXTURETAG_PROJECTION] = 6  #UVW
        newTex[c4d.TEXTURETAG_RESTRICTION] = "foo_" + str(f)

        #INNER EXTRUDE
        c4d.CallCommand(450000004)  # Extrude Inner
        getTool()[c4d.MDATA_EXTRUDEINNER_OFFSET] = randrange(2, 30) * 1.0
        fireAction(obj)

        #OUTER
        c4d.CallCommand(1011183)  # Extrude
        getTool()[c4d.MDATA_EXTRUDE_OFFSET] = randrange(9, 30) * -1.0
        fireAction(obj)

    #kick out a render
    doc[c4d.RDATA_PATH] = ""
    c4d.CallCommand(12098)  # Save
    c4d.CallCommand(12099)  # Render to Picture Viewer

    return obj
def main():
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    doc.StartUndo()  # Start recording undos
    keyMod = GetKeyMod()  # Get keymodifier
    editorMode = doc.GetMode()  # Get editor's active mode
    selection = doc.GetActiveObjects(
        c4d.GETACTIVEOBJECTFLAGS_SELECTIONORDER)  # Get active objects
    cnt = len(selection)  # Count of selected objects

    # Edge selection
    if editorMode == c4d.Medges:
        edgeToSpline = c4d.MCOMMAND_EDGE_TO_SPLINE  # Mcommand 'Edge To Spline'
        modeEdgeSel = c4d.MODELINGCOMMANDMODE_EDGESELECTION  # Modeling command mode 'Edge Selection'
        createUndo = c4d.MODELINGCOMMANDFLAGS_CREATEUNDO  # Modeling command flag 'Create undo'
        bc = c4d.BaseContainer()  # Initialize base container
        u.SendModelingCommand(
            edgeToSpline, selection, modeEdgeSel, bc, doc,
            createUndo)  # Send modeling command 'Edge To Spline'

        obj = selection[0]
        spline = obj.GetDown()
        spline.InsertBefore(obj)
        spline.SetMg(obj.GetMg())
        CenterAxis(spline)

        doc.AddUndo(c4d.UNDOTYPE_BITS,
                    selection[0])  # Add undo command for changing bits
        selection[0].DelBit(c4d.BIT_ACTIVE)  # Deselect object
        doc.AddUndo(c4d.UNDOTYPE_BITS, spline)
        spline.SetBit(c4d.BIT_ACTIVE)
        doc.SetMode(c4d.Mmodel)

    # Object selection
    else:

        # No active objects
        if cnt == 0:
            if keyMod == "None":
                spline = CreateSpline(2, [
                    c4d.Vector(0, 0, 0),
                    c4d.Vector(0, 0, 100),
                ])
                InsertObject(spline)
            if keyMod == "Shift":
                spline = CreateSpline(2, [
                    c4d.Vector(0, 0, 0),
                    c4d.Vector(0, 100, 0),
                ])
                InsertObject(spline)
            if keyMod == "Ctrl":
                spline = CreateSpline(2, [
                    c4d.Vector(0, 0, 0),
                    c4d.Vector(100, 0, 0),
                ])
                InsertObject(spline)

        # Only one selected object
        elif cnt == 1:
            if selection[0].GetType() == 5101:  # If spline object
                subd = gui.InputDialog('Subdivide', "0")
                if keyMod == "None":
                    controllers = CreateControls(selection[0], "Ends")
                elif keyMod == "Shift":
                    controllers = CreateControls(selection[0], "All")
                CreateDynamics(selection[0], controllers, int(subd))
                doc.AddUndo(c4d.UNDOTYPE_BITS,
                            selection[0])  # Add undo command for changing bits
                selection[0].DelBit(c4d.BIT_ACTIVE)  # Deselect object

        # Multiple selected objects
        else:
            # If spline object
            if selection[0].GetType() == 5101:
                subd = gui.InputDialog('Subdivide', "0")
                for s in selection:
                    if keyMod == "None":
                        controllers = CreateControls(s, "Ends")
                    elif keyMod == "Shift":
                        controllers = CreateControls(s, "All")
                    CreateDynamics(s, controllers, int(subd))
                    doc.AddUndo(c4d.UNDOTYPE_BITS,
                                s)  # Add undo command for changing bits

            # No spline object
            else:
                if keyMod == "Alt+Shift" or keyMod == "Alt+Ctrl":
                    TracerFromObjects(selection, keyMod)
                else:
                    SplineFromObjects(selection, keyMod)

            # Deselect old selection
            for s in selection:  # Iterate through selection
                doc.AddUndo(c4d.UNDOTYPE_BITS,
                            s)  # Add undo command for changing bits
                s.DelBit(c4d.BIT_ACTIVE)  # Deselect object

    doc.EndUndo()  # Stop recording undos
    c4d.EventAdd()  # Refresh Cinema 4D
def makeStuff():
    def object():
        return doc.GetActiveObject()

    def tag():
        return doc.GetActiveTag()

    def renderdata():
        return doc.GetActiveRenderData()

    def prefs(id):
        return plugins.FindPlugin(id, c4d.PLUGINTYPE_PREFS)

    def getPosOrNeg():
        tmpNumber = randrange(1, 20)

        if (tmpNumber % 2 == 0):
            return 1
        else:
            return -1

    def getRandPosition(pArg):
        return randrange(1, pArg) * getPosOrNeg()

    def getRandPositionPos(pArg):
        return randrange(1, pArg)

    c4d.CallCommand(12187)  # Polygons
    cubeList = []

    for x in range(0, 4):
        obj = c4d.BaseObject(c4d.Ocube)
        obj[c4d.PRIM_CUBE_LEN] = c4d.Vector(randrange(10, 150),
                                            randrange(10, 150),
                                            randrange(10, 150))
        res = utils.SendModelingCommand(
            command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
            list=[obj],
            mode=c4d.MODELINGCOMMANDMODE_ALL,
            bc=c4d.BaseContainer(),
            doc=doc)[0]
        res[c4d.ID_BASEOBJECT_REL_POSITION,
            c4d.VECTOR_X] = getRandPosition(200)
        res[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Y] = getRandPositionPos(
            200)  #keep it above ground level
        res[c4d.ID_BASEOBJECT_REL_POSITION,
            c4d.VECTOR_Z] = getRandPosition(200)

        doc.InsertObject(res)
        doc.SetActiveObject(res, c4d.SELECTION_NEW)
        c4d.EventAdd()
        sel = res.GetPolygonS()
        sel.Select(2)

        cubeList.append(res)

        if (x > 0):  #connect this with the last cube
            doc.SetActiveObject(cubeList[x - 1], c4d.SELECTION_ADD)

        #send a modeling command here
        settings = c4d.BaseContainer()  # Settings
        settings[c4d.MDATA_EXTRUDE_OFFSET] = 50.0  # Length of the extrusion
        '''
def polyselectionbreak(bdoc, bobj):
    if not bobj: return

    obj = bobj  # the modeling commands change the bobj so we need to store this
    gMatrix = bobj.GetMg()
    tag = obj.GetFirstTag()

    newChildren = []

    while tag:
        if tag.GetType() == c4d.Tpolygonselection:
            # deselect all polygons
            polyselection = obj.GetPolygonS()
            polyselection.DeselectAll()

            # select polygons from selection tag
            tagselection = tag.GetBaseSelect()
            tagselection.CopyTo(polyselection)

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

            if not sec:
                print 'split failed for ' + tag.GetName()
                continue

            sec[0].SetName(tag.GetName())
            sec[0][c4d.ID_BASEOBJECT_REL_POSITION] = c4d.Vector(0, 0, 0)
            sec[0][c4d.ID_BASEOBJECT_REL_ROTATION] = c4d.Vector(0, 0, 0)

            # remove polyselections and textures from the split and find a material to keep
            secTag = sec[0].GetTag(c4d.Tpolygonselection)

            while secTag:
                secTag.Remove()
                secTag = sec[0].GetTag(c4d.Tpolygonselection)

            secTag = sec[0].GetFirstTag()

            while secTag:
                oldSecTag = None
                if secTag.GetType() == c4d.Ttexture:
                    if secTag[c4d.TEXTURETAG_RESTRICTION] == tag.GetName():
                        secTag[c4d.TEXTURETAG_RESTRICTION] = ''
                    else:
                        oldSecTag = secTag

                secTag = secTag.GetNext()
                if oldSecTag:
                    oldSecTag.Remove()

            # loop through tags and find any texture tags that have the selection and delete
            oldMatTag = None
            matTag = obj.GetFirstTag()
            while matTag:
                if matTag.GetType() == c4d.Ttexture:
                    if matTag[c4d.TEXTURETAG_RESTRICTION] == tag.GetName():
                        oldMatTag = matTag

                matTag = matTag.GetNext()

                if oldMatTag:
                    oldMatTag.Remove()

            newChildren.append(sec[0])
            #delete the polygons from selectiontag
            utils.SendModelingCommand(
                command=c4d.MCOMMAND_DELETE,
                list=[obj],
                mode=c4d.MODELINGCOMMANDMODE_POLYGONSELECTION,
                doc=bdoc)

        tag = tag.GetNext()

    # remove selection tags
    tag = obj.GetTag(c4d.Tpolygonselection)

    while tag:
        tag.Remove()
        tag = obj.GetTag(c4d.Tpolygonselection)

    # Optimize in order to remove loose points
    options = c4d.BaseContainer()
    options[c4d.MDATA_OPTIMIZE_TOLERANCE] = 0.001
    options[c4d.MDATA_OPTIMIZE_POINTS] = True
    options[c4d.MDATA_OPTIMIZE_POLYGONS] = False
    options[c4d.MDATA_OPTIMIZE_UNUSEDPOINTS] = True
    utils.SendModelingCommand(c4d.MCOMMAND_OPTIMIZE,
                              list=[obj],
                              mode=c4d.MODELINGCOMMANDMODE_ALL,
                              bc=options,
                              doc=obj.GetDocument())

    if (obj.GetPolygonCount() == 0):  # no more polys
        if (
                obj.GetChildren() > 0
        ):  # there are children remove this and replace with null then readd the children
            objNull = c4d.BaseObject(c4d.Onull)
            objNull.SetName(obj.GetName())
            objParent = obj.GetUp()
            obj.Remove()

            obj = objNull
            bdoc.InsertObject(obj, objParent)
            obj.SetMg(gMatrix)
        elif (
                obj.GetChildren() == 0
        ):  # No children, we don't want a parent remain so let's axe this
            objParent = obj.GetUp()
            obj.Remove()
            obj = objParent

    for child in newChildren:
        child.InsertUnder(obj)

    c4d.EventAdd()
Example #25
0
def main():

    # Get file data
    document = documents.GetActiveDocument()
    path = document.GetDocumentPath()
    name = document.GetDocumentName()
    settings = c4d.BaseContainer()

    obj = document.SearchObject("Connect")
    userDataObject = document.SearchObject("Mordifier")
    objList = document.GetObjects()

    outPutFilename = userDataObject[c4d.ID_USERDATA, 15]
    outPutPath = userDataObject[c4d.ID_USERDATA, 16]

    # C-Model
    return_value = utils.SendModelingCommand(
        command=c4d.MCOMMAND_CURRENTSTATETOOBJECT,
        list=[obj],
        mode=c4d.MODELINGCOMMANDMODE_ALL,
        bc=settings,
        doc=document)

    if return_value:
        document.InsertObject(
            return_value[0])  #return_value is a list in this case
        c4d.EventAdd()

    # del others
    for i in objList:
        i.Remove()

    # change name of the model
    newModel = document.GetFirstObject()
    newModel.SetName(outPutFilename)

    # delete all material
    mat = document.GetMaterials()
    for i in mat:
        i.Remove()

    # save file
    # path = "C:\\newStart\\Assets\\Models\\CutOutModels\\"
    name = outPutFilename + "_forUnity.c4d"
    path = os.path.join(outPutPath, name)
    # 导出模型到原文件路径
    if documents.SaveDocument(doc, path,
                              c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST,
                              c4d.FORMAT_C4DEXPORT):
        print "export document to: " + path
    else:
        print "export failed"

    # open new model


#     try:
#          newDoc = documents.LoadDocument(path, c4d.
# SCENEFILTER_0)
#     except IOError:
#         print "Can't open the new model"

    c4d.EventAdd()