Exemplo n.º 1
0
def CanvasSequence(coloverride):
    img = storage.LoadDialog() 
    if not img:
        return 'Canvas Cancelled.'
    else:
        path, filename = os.path.split(img)
        #gets directory and lists all images - helps calculate total frames.
        imgSeq = os.listdir(path)
        #gets length of frames
        frames = len(imgSeq)
        #user input framerate
        fps = gui.InputDialog('Framerate')
        #get filename
        fname, ext = filename.split('.')
        name = gui.InputDialog('Material Name')
        m = Material(img,coloverride)
        ms = materialShader(m,img,True,frames,fps,coloverride)
        p = ImagePlane(m,name,ms)
        if name in(None,'Material Name?'):
            m[c4d.ID_BASELIST_NAME] = fname
            p[c4d.ID_BASELIST_NAME] = fname
           
        else:
            m[c4d.ID_BASELIST_NAME] = name
            p[c4d.ID_BASELIST_NAME] = name
Exemplo n.º 2
0
def CanvasVideo(coloverride):
    img = storage.LoadDialog() 
    if not img:
        return 'Canvas Cancelled.'
    else:
        path, filename = os.path.split(img)
        #get filename
        fname, ext = filename.split('.')

        #load movie
        if not ext in ('mp4','avi'):
            gui.MessageDialog('file format .' + ext +'  not supported!')
        else:
            mov = c4d.bitmaps.MovieLoader()
            mov.Open(img)

            frame, fps = mov.GetInfo()
            name = gui.InputDialog('Material Name')
            m = Material(img,coloverride)
            ms = materialShader(m,img,True,frame,fps,coloverride)
            p = ImagePlane(m,name,ms)
            if name in(None,'Material Name?'):
                m[c4d.ID_BASELIST_NAME] = fname
                p[c4d.ID_BASELIST_NAME] = fname

            else:
                m[c4d.ID_BASELIST_NAME] = name
                p[c4d.ID_BASELIST_NAME] = name
Exemplo n.º 3
0
def SelectDirectory(default_path=''):
    return storage.LoadDialog(
        type=c4d.FILESELECTTYPE_ANYTHING,
        title=
        'Select directory with file_list.txt or to search c4d files. After then you can convert it to FBX',
        flags=c4d.FILESELECT_DIRECTORY,
        def_path=default_path).decode("utf-8")
def main():
    
    path = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, "Sound file", c4d.FILESELECT_LOAD)
    folderPath, fileName = os.path.split(path)

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

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

    c4d.EventAdd()
Exemplo n.º 5
0
def main():
    doc.StartUndo()
    folder = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, 'Select image folder',
                          c4d.FILESELECT_DIRECTORY, '')
    if not folder: return
    files = os.listdir(folder)

    for f in files:
        mat = c4d.BaseMaterial(c4d.Mmaterial)
        mat[c4d.MATERIAL_USE_REFLECTION] = 0
        mat[c4d.MATERIAL_USE_ALPHA] = 1
        shd = c4d.BaseShader(c4d.Xbitmap)
        shd[c4d.BITMAPSHADER_FILENAME] = folder + "\\" + f
        alpha = c4d.BaseShader(c4d.Xbitmap)
        alpha[c4d.BITMAPSHADER_FILENAME] = folder + "\\" + f
        mat[c4d.MATERIAL_COLOR_SHADER] = shd
        mat[c4d.MATERIAL_ALPHA_SHADER] = alpha
        mat.InsertShader(shd)
        mat.InsertShader(alpha)
        mat.Message(c4d.MSG_UPDATE)
        mat.Update(True, True)
        doc.InsertMaterial(mat)
        doc.AddUndo(c4d.UNDOTYPE_NEW, mat)

        c4d.EventAdd()
        doc.EndUndo()
Exemplo n.º 6
0
def main():
    fn = ''
    fn = storage.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, 'Open .mtl file',
                            c4d.FILESELECT_LOAD, 'mtl')
    if fn != None and fn != '':
        ParseFile(fn.decode("utf8"), doc)
        DebugPrint(' ')
Exemplo n.º 7
0
def main():
    # Get Alembic export plugin, 1028082 is its ID
    plug = plugins.FindPlugin(1028082, c4d.PLUGINTYPE_SCENESAVER)
    if plug is None:
        return
    
    # Get a path to save the exported file
    filePath = storage.LoadDialog(title="Save File for Alembic Export", flags=c4d.FILESELECT_SAVE, force_suffix="abc")
    if filePath is None:
        return
    
    op = {}
    # Send MSG_RETRIEVEPRIVATEDATA to Alembic export plugin
    if plug.Message(c4d.MSG_RETRIEVEPRIVATEDATA, op):
        print op
        if "imexporter" not in op:
            return
        
        # BaseList2D object stored in "imexporter" key hold the settings
        abcExport = op["imexporter"]
        if abcExport is None:
            return
        
        # Change Alembic export settings
        abcExport[c4d.ABCEXPORT_SELECTION_ONLY] = True
        abcExport[c4d.ABCEXPORT_PARTICLES] = True
        abcExport[c4d.ABCEXPORT_PARTICLE_GEOMETRY] = True
        
        # Finally export the document
        if documents.SaveDocument(doc, filePath, c4d.SAVEDOCUMENTFLAGS_DONTADDTORECENTLIST, 1028082):
            print "Document successfully exported to:"
            print filePath
        else:
            print "Export failed!"
Exemplo n.º 8
0
def main():
    
    path = storage.LoadDialog(type=c4d.FILESELECTTYPE_IMAGES, title="Please Choose a 32 Bit Image:")
    #path = "C:\\Users\\tobi\\Desktop\\test.jpg"
    if not path: return

    # Create and initialize selected image
    orig = bitmaps.BaseBitmap()
    if orig.InitWith(path)[0] != c4d.IMAGERESULT_OK:
        gui.MessageDialog("Cannot load image \"" + path + "\".")
        return

    width, height = orig.GetSize()
    bits = orig.GetBt()
    pxColl = []
    
    for x in range (0,width):
        for y in range (0,height):
            pxColl.append( orig.GetPixel(x,y) )

    
    samples = 16
    seed = 500
    pxColl.sort()

        
     
            
    i = 0
    for x in range (0,width):
        for y in range (0,height):
            
            orig.SetPixel(x,y,int(pxColl[i][0]),int(pxColl[i][1]),int(pxColl[i][2]))
            
            i += 1  
            
    bitmaps.ShowBitmap(orig)
    
    
    copy = bitmaps.BaseBitmap() 
    copy.Init(samples, 1, bits)
    collPic = []
    for x in range(0,samples):
        
        #random.seed(x+seed)
        rgb =len(pxColl)/samples*x
        newcoll = pxColl[rgb][0],pxColl[rgb][1],pxColl[rgb][2]
        #print newcoll
        collPic.append( newcoll )

    collPic.sort(key=lambda rgb: colorsys.rgb_to_hsv(*rgb))

    i = 0
    #print collPic
    for item in collPic:
        copy.SetPixel(i,0,item[0],item[1],item[2])        
        
        i += 1
Exemplo n.º 9
0
def main():
    folder = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING,
                          'Select folder to import', c4d.FILESELECT_DIRECTORY,
                          '')
    if not folder: return
    files = os.listdir(folder)
    for f in files:
        c4d.documents.MergeDocument(doc, folder + '\\' + f, 1)
    c4d.EventAdd()
Exemplo n.º 10
0
def main():
    #get selected object
    obj = doc.GetActiveObject()
    if obj is None:
        gui.MessageDialog("An object must be selected")
        return
    #finding where to save json file
    filePath = storage.LoadDialog(
        title="Save JSON file with Objects Positions",
        flags=c4d.FILESELECT_SAVE,
        force_suffix="json")
    if filePath is None:
        return

    #open file
    f = open(filePath, "w")

    #begin Json formatting
    f.write("{")
    #get the children
    children = obj.GetChildren()
    print obj.GetName() + " has " + str(len(obj.GetChildren())) + " children"
    f.write('"name":' + '"' + obj.GetName() + '",\n')
    f.write('\t"objects":[\n')
    for i in range(0, len(children)):
        pos = children[i].GetAbsPos()
        rot = children[i].GetRelRot()
        name = children[i].GetName()
        print "+ " + children[i].GetName()
        print "   +Position:( " + str(pos.x) + "," + str(pos.y) + "," + str(
            pos.z) + ")"
        print "   +Rotation:( " + str(pos.x) + "," + str(pos.y) + "," + str(
            pos.z) + ")"
        f.write('\t{\n')
        f.write('\t\t"name":"' + name + '",')
        f.write('\n\t\t"position":[' + str(pos.x) + ',' + str(pos.y) + ',' +
                str(pos.z) + '],')
        f.write('\n\t\t"rotation":[' + str(rot.x) + ',' + str(rot.y) + ',' +
                str(rot.z) + ']')
        if i == len(children) - 1:
            f.write('\n\t}\n')
        else:
            f.write('\n\t},\n')
    f.write('\t]\n')
    #get path to sive file
    # Get a path to save the exported file

    #saving file
    f.write("}")
    f.close()

    c4d.CopyStringToClipboard("hi")
    gui.MessageDialog(".json file exported with success")
    pos = obj.GetRelPos()
Exemplo n.º 11
0
def main():

    fn = ''
    fn = storage.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, 'Open .mtl file', c4d.FILESELECT_LOAD, 'mtl')
    directory = fn + "/.."
    print 'fn = ' + fn
    dirList = os.listdir(directory)

    for file in dirList:
        if file != None and file != ''and file.endswith(".txt"):

             ParseFile(file.decode("utf8"), doc)
def main():
    extensions = ["obj"]  # File extensions that will be imported
    folder = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING,
                          'Select folder to import', c4d.FILESELECT_DIRECTORY,
                          '')  # Load folder
    if not folder: return  # If there is no folder, stop the script
    files = os.listdir(folder)  # Get files
    for f in files:  # Loop through files
        ext = f.rsplit(".", 1)  # Get file extension
        if ext[1] in extensions:  # If extension matches
            c4d.documents.MergeDocument(doc, folder + '\\' + f,
                                        1)  # Merge file to current project
    c4d.EventAdd()  # Update Cinema 4D
Exemplo n.º 13
0
def main():
    ini_file = p.join(p.split(__file__)[0], 'ini_file.txt')
    c4d_user_dir = st.GeGetStartupWritePath()
    points = [('Active Doc Folder', doc.GetDocumentPath()),
              ('Preferences', st.GeGetC4DPath(c4d.C4D_PATH_PREFS)),
              ('Desktop', st.GeGetC4DPath(c4d.C4D_PATH_DESKTOP)),
              ('Scripts', p.join(c4d_user_dir, 'library', 'scripts')),
              ('Plugins', p.join(c4d_user_dir, 'plugins'))]
    sub_points = []
    if p.exists(ini_file):
        with open(ini_file, 'r') as t_file:
            data = t_file.read()
        for line in data.splitlines():
            name, n_dir = line.split(';')
            sub_points.append((name, n_dir))

    menu = c4d.BaseContainer()
    for x in points:
        menu.SetString(c4d.FIRST_POPUP_ID + len(menu), x[0])
    menu.SetString(0, '')
    if sub_points:
        sub_menu = c4d.BaseContainer()
        sub_menu.SetString(1, 'Custom Folder')
        subID = c4d.FIRST_POPUP_ID + 1000
        for item in sub_points:
            sub_menu.SetString(subID + len(sub_menu), item[0])

        menu.SetContainer(c4d.FIRST_POPUP_ID + len(menu) - 1, sub_menu)

    menu.SetString(c4d.FIRST_POPUP_ID + len(menu), 'Add Custom Folder')

    result = gui.ShowPopupDialog(
        cd=None, bc=menu, x=c4d.MOUSEPOS, y=c4d.MOUSEPOS) - c4d.FIRST_POPUP_ID
    print result
    if result == c4d.FIRST_POPUP_ID * -1: return
    if result == len(menu) - 1:
        c_dir = st.LoadDialog(type=c4d.FILESELECTTYPE_ANYTHING,
                              title="Add New Directory to list",
                              flags=c4d.FILESELECT_DIRECTORY,
                              force_suffix="")
        if c_dir:
            with open(ini_file, 'a') as t_file:
                t_file.write(p.split(c_dir)[1] + ';' + c_dir + '\n')
        return
    if result > 1000:
        st.ShowInFinder(sub_points[result - 1001][1], False)
        return

    st.ShowInFinder(points[result][1], False)
def main():
    fn = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, "Select reference file",
                      c4d.FILESELECT_LOAD)
    if fn == None: return None
    res = g.InputDialog("Resolution", "1280x720")
    width = float(res.split("x")[0])
    height = float(res.split("x")[1])
    ren = doc.GetActiveRenderData()
    zpos = ren[c4d.RDATA_XRES_VIRTUAL]
    c4d.CallCommand(12544)  # Create new viewport
    bd = doc.GetActiveBaseDraw()
    cam = c4d.BaseObject(c4d.Ocamera)
    cam.SetName("REFERENCE_CAMERA")
    cam[c4d.CAMERAOBJECT_TARGETDISTANCE] = width
    cam[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 2
    doc.InsertObject(cam)
    plane = c4d.BaseObject(c4d.Oplane)
    plane[c4d.ID_BASEOBJECT_VISIBILITY_RENDER] = 2
    plane.SetName("REFERENCE_PLANE")
    plane[c4d.PRIM_AXIS] = 5
    plane[c4d.PRIM_PLANE_SUBW] = 1
    plane[c4d.PRIM_PLANE_SUBH] = 1
    plane[c4d.PRIM_PLANE_WIDTH] = width
    plane[c4d.PRIM_PLANE_HEIGHT] = height
    plane[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z] = zpos
    plane.InsertUnder(cam)
    mat = c4d.BaseMaterial(c4d.Mmaterial)
    mat.SetName("REFERENCE_MATERIAL")
    mat[c4d.MATERIAL_USE_REFLECTION] = 0
    mat[c4d.MATERIAL_ANIMATEPREVIEW] = 1
    color = c4d.BaseShader(c4d.Xbitmap)
    color[c4d.BITMAPSHADER_FILENAME] = fn
    doc.ExecutePasses(None, 0, 1, 1, 0)
    c4d.CallButton(color, c4d.BITMAPSHADER_CALCULATE)
    mat[c4d.MATERIAL_COLOR_SHADER] = color
    mat.InsertShader(color)
    mat.Message(c4d.MSG_UPDATE)
    mat.Update(True, True)
    doc.InsertMaterial(mat)
    t = c4d.BaseTag(5616)
    plane.InsertTag(t)
    tag = plane.GetFirstTag()
    tag[c4d.TEXTURETAG_MATERIAL] = mat
    tag[c4d.TEXTURETAG_PROJECTION] = 6
    bd[c4d.BASEDRAW_DATA_TINTBORDER_OPACITY] = 1
    bd[c4d.BASEDRAW_DATA_CAMERA] = cam
    bd[c4d.BASEDRAW_TITLE] = "REFERENCE_VIEWPORT"
    cam[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X] = 5000000
    c4d.EventAdd()
Exemplo n.º 15
0
def main():
    path = storage.LoadDialog(type=c4d.FILESELECTTYPE_IMAGES,
                              title="Please Choose an Image:")
    if not path: return

    # Create and initialize selected image
    img = bitmaps.BaseBitmap()
    if img.InitWith(path)[0] != c4d.IMAGERESULT_OK:
        gui.MessageDialog("Cannot load image \"" + path + "\".")
        return

    byteseq, size = WriteBitmap(
        img)  # Save image to hyper file in byte sequence
    bmp = ReadBitmap(byteseq)  # Read image from the byte sequence

    bitmaps.ShowBitmap(bmp)
Exemplo n.º 16
0
def main():
    doc.StartUndo()
    folder = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, 'Select image folder',
                          c4d.FILESELECT_DIRECTORY, '')
    if not folder: return
    files = os.listdir(folder)

    for f in files:
        mat = c4d.BaseMaterial(c4d.Mmaterial)
        path = folder + "\\" + f

        # enable or disable channels
        mat[c4d.MATERIAL_USE_REFLECTION] = 0
        mat[c4d.MATERIAL_USE_LUMINANCE] = 1
        mat[c4d.MATERIAL_USE_ALPHA] = 1

        # color channel
        color = c4d.BaseShader(c4d.Xbitmap)
        color[c4d.BITMAPSHADER_FILENAME] = path
        mat[c4d.MATERIAL_COLOR_SHADER] = color

        # luminance channel
        luminance = c4d.BaseShader(c4d.Xbitmap)
        luminance[c4d.BITMAPSHADER_FILENAME] = path
        mat[c4d.MATERIAL_LUMINANCE_SHADER] = luminance

        # alpha channel
        alpha = c4d.BaseShader(c4d.Xbitmap)
        alpha[c4d.BITMAPSHADER_FILENAME] = path
        mat[c4d.MATERIAL_ALPHA_SHADER] = alpha

        # assign shaders to material
        mat.InsertShader(color)
        mat.InsertShader(luminance)
        mat.InsertShader(alpha)

        # other stuff
        mat.Message(c4d.MSG_UPDATE)
        mat.Update(True, True)
        matname = f.split(".")[0]
        mat.SetName(matname)
        doc.InsertMaterial(mat)
        doc.AddUndo(c4d.UNDOTYPE_NEW, mat)

        c4d.EventAdd()
        doc.EndUndo()
Exemplo n.º 17
0
def main():
    path = storage.LoadDialog(type=c4d.FILESELECTTYPE_IMAGES, title="Please Choose a 32-bit Image:")
    if not path: return
    
    # Create and initialize selected image
    orig = bitmaps.BaseBitmap()
    if orig.InitWith(path)[0] != c4d.IMAGERESULT_OK:
        gui.MessageDialog("Cannot load image \"" + path + "\".")
        return
    
    # Check if channel depth is really 32 bit
    if orig.GetBt()/3 != 32:
        gui.MessageDialog("The image \"" + path + "\" is not a 32 bit per-channel image.")
        return
    
    # Get selected image infos
    width, height = orig.GetSize()
    bits = orig.GetBt()
    
    # Create the copy and initialize it
    copy = bitmaps.BaseBitmap()
    copy.Init(width, height, bits)
    
    # Calculate the number of bytes per pixel
    inc = orig.GetBt()/8 # Each pixel has RGB bits, so we need an offset of 'inc' bytes per pixel
                         # the image has 32 bits per-channel : (32*3)/8 = 12 bytes per pixel (1 byte = 8 bits)
                         # the image has 3 channels per pixel (RGB) : 12/3 = 4 bytes per component = 1 float
    
    # Create a byte sequence buffer large enough to store the copied image pixels
    sq = storage.ByteSeq(None, width*height*inc)
    
    for row in xrange(height):
        offset = sq.GetOffset(row*(width*inc)) # Offset on bitmap row + offset bytes per pixel
        orig.GetPixelCnt(0, row, width, offset, inc, c4d.COLORMODE_RGBf, c4d.PIXELCNT_0) # Read pixels from the original bitmap into the buffer
    
    #Example: RGB value of first pixel (only for 32 bits)
    #import struct
    #r, g, b = struct.unpack("fff", sq[0:12])
    #print r, g, b
    
    for row in xrange(height):
        offset = sq.GetOffset(row*(width*inc)) # Offset on bitmap row + offset bytes per pixel
        copy.SetPixelCnt(0, row, width, offset, inc, c4d.COLORMODE_RGBf, c4d.PIXELCNT_0) # Set pixels in bitmap copy
    
    bitmaps.ShowBitmap(orig) # Show original
    bitmaps.ShowBitmap(copy) # Show copied image
Exemplo n.º 18
0
def main():
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    doc.StartUndo()  # Start recording undos
    folder = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, 'Select image folder',
                          c4d.FILESELECT_DIRECTORY, '')
    if not folder: return
    try:  # Try to execute following script
        files = os.listdir(folder)
        for f in files:  # Loop through files
            mat = c4d.BaseMaterial(c4d.Mmaterial)
            path = folder + "\\" + f
            mat[c4d.MATERIAL_USE_REFLECTION] = 0  # Disable reflection channel

            # Color channel
            color = c4d.BaseShader(c4d.Xbitmap)
            color[c4d.BITMAPSHADER_FILENAME] = path
            mat[c4d.MATERIAL_COLOR_SHADER] = color

            # Luminance channel
            luminance = c4d.BaseShader(c4d.Xbitmap)
            luminance[c4d.BITMAPSHADER_FILENAME] = path
            mat[c4d.MATERIAL_LUMINANCE_SHADER] = luminance

            # Alpha channel
            alpha = c4d.BaseShader(c4d.Xbitmap)
            alpha[c4d.BITMAPSHADER_FILENAME] = path
            mat[c4d.MATERIAL_ALPHA_SHADER] = alpha

            # Assign shaders to material
            mat.InsertShader(color)  # Insert shader to color channel
            mat.InsertShader(luminance)  # Insert shader to luminance channel
            mat.InsertShader(alpha)  # Insert shader to alpha channel

            # Other stuff
            mat.Message(c4d.MSG_UPDATE)
            mat.Update(True, True)  # Update material
            matname = f.split(".")[0]  # Get material name from file path
            mat.SetName(matname)  # Set material name
            doc.InsertMaterial(mat)  # Insert new 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
Exemplo n.º 19
0
def CanvasImage(coloverride):
     img = storage.LoadDialog() 
     if not img:
        return 'Canvas Cancelled.'
     else:
        path, filename = os.path.split(img)
        #get filename
        fname, ext = filename.split('.')
        name = gui.InputDialog('Material Name')
        m = Material(img,coloverride)
        ms = materialShader(m,img,False,0,0,coloverride)
        p = ImagePlane(m,name,ms)
        if name in(None,'Material Name?'):
            m[c4d.ID_BASELIST_NAME] = fname
            p[c4d.ID_BASELIST_NAME] = fname
           
        else:
            m[c4d.ID_BASELIST_NAME] = name
            p[c4d.ID_BASELIST_NAME] = name
def main():
    doc.StartUndo()
    fn = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING,'Select pixeur palette',c4d.FILESELECT_LOAD,'')
    f = open(fn.decode("utf-8"))
    
    for line in f:
        if line.startswith("R"):
            line = line.split(" ")
            r = line[0][2:]
            g = line[1][2:]
            line = line[2].split(",")
            b = line[0][2:]
            mat = c4d.BaseMaterial(c4d.Mmaterial)
            color = c4d.Vector(float(r)/255,float(g)/255,float(b)/255)
            mat[c4d.MATERIAL_COLOR_COLOR] = color
            mat.Message(c4d.MSG_UPDATE)
            mat.Update(True, True)
            doc.InsertMaterial(mat)
            doc.AddUndo(c4d.UNDOTYPE_NEW, mat)
                    
    doc.EndUndo()
    c4d.EventAdd()
Exemplo n.º 21
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
    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
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
Exemplo n.º 23
0
def main():

    dlg = Dialog()
    dlg.Open(c4d.DLG_TYPE_MODAL_RESIZEABLE, defaultw=500)

    if not dlg.didPressOK:
        return

    DOCUMENT_FPS = dlg.document_fps
    CAMERA_FOV = dlg.camera_fov

    path = storage.LoadDialog(flags=2)

    if not path:
        print "No path found"
        return

    camInfoArr = parseXML(path)
    lastEl = camInfoArr[len(camInfoArr) - 1]

    pprint.pprint(camInfoArr)

    # Setup document
    doc = documents.GetActiveDocument()
    doc.SetFps(DOCUMENT_FPS)
    doc.SetMaxTime(c4d.BaseTime(lastEl['startTime'] + lastEl['length']))

    rd = doc.GetActiveRenderData()
    rd[c4d.RDATA_FRAMERATE] = DOCUMENT_FPS

    # Create, setup and insert Camera object
    camera = c4d.BaseObject(c4d.Ocamera)
    camera[c4d.CAMERAOBJECT_FOV_VERTICAL] = CAMERA_FOV * math.pi / 180
    doc.InsertObject(camera)

    posXtrack = c4d.CTrack(camera,
                           [c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X])
    posYtrack = c4d.CTrack(camera,
                           [c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Y])
    posZtrack = c4d.CTrack(camera,
                           [c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z])
    rotXtrack = c4d.CTrack(camera,
                           [c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_X])
    rotYtrack = c4d.CTrack(camera,
                           [c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Y])
    rotZtrack = c4d.CTrack(camera,
                           [c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Z])

    camera.InsertTrackSorted(posXtrack)
    camera.InsertTrackSorted(posYtrack)
    camera.InsertTrackSorted(posZtrack)
    camera.InsertTrackSorted(rotXtrack)
    camera.InsertTrackSorted(rotYtrack)
    camera.InsertTrackSorted(rotZtrack)

    posXcurve = posXtrack.GetCurve()
    posYcurve = posYtrack.GetCurve()
    posZcurve = posZtrack.GetCurve()
    rotXcurve = rotXtrack.GetCurve()
    rotYcurve = rotYtrack.GetCurve()
    rotZcurve = rotZtrack.GetCurve()

    previousTransform = [0, 0, 0, 0, 0, 0]
    previousEndTime = 0

    for camInfo in camInfoArr:

        startTime = camInfo['startTime']
        length = camInfo['length']
        endTime = startTime + length

        curveType = camInfo['curveType']

        if round(previousEndTime, 5) != round(startTime, 5):

            # Set StartTime values
            posXkeyStart = c4d.CKey()
            posYkeyStart = c4d.CKey()
            posZkeyStart = c4d.CKey()
            rotXkeyStart = c4d.CKey()
            rotYkeyStart = c4d.CKey()
            rotZkeyStart = c4d.CKey()

            posXkeyStart.SetTime(posXcurve, c4d.BaseTime(startTime))
            posXkeyStart.SetValue(posXcurve, previousTransform[0])
            posYkeyStart.SetTime(posYcurve, c4d.BaseTime(startTime))
            posYkeyStart.SetValue(posYcurve, previousTransform[1])
            posZkeyStart.SetTime(posZcurve, c4d.BaseTime(startTime))
            posZkeyStart.SetValue(posZcurve, previousTransform[2])
            rotXkeyStart.SetTime(rotXcurve, c4d.BaseTime(startTime))
            rotXkeyStart.SetValue(rotXcurve, previousTransform[3])
            rotYkeyStart.SetTime(rotYcurve, c4d.BaseTime(startTime))
            rotYkeyStart.SetValue(rotYcurve, previousTransform[4])
            rotZkeyStart.SetTime(rotZcurve, c4d.BaseTime(startTime))
            rotZkeyStart.SetValue(rotZcurve, previousTransform[5])

            if (curveType == "Sinus"):
                tangentLength = c4d.BaseTime(length * (4.0 / 15.0))
                nTangentLength = c4d.BaseTime(length * (4.0 / 15.0) * -1)

                # posXkeyStart.SetTimeLeft(posXcurve, nTangentLength)
                posXkeyStart.SetTimeRight(posXcurve, tangentLength)
                # posYkeyStart.SetTimeLeft(posYcurve, nTangentLength)
                posYkeyStart.SetTimeRight(posYcurve, tangentLength)
                # posZkeyStart.SetTimeLeft(posZcurve, nTangentLength)
                posZkeyStart.SetTimeRight(posZcurve, tangentLength)
                # rotXkeyStart.SetTimeLeft(rotXcurve, nTangentLength)
                rotXkeyStart.SetTimeRight(rotXcurve, tangentLength)
                # rotYkeyStart.SetTimeLeft(rotYcurve, nTangentLength)
                rotYkeyStart.SetTimeRight(rotYcurve, tangentLength)
                # rotZkeyStart.SetTimeLeft(rotZcurve, nTangentLength)
                rotZkeyStart.SetTimeRight(rotZcurve, tangentLength)

            posXcurve.InsertKey(posXkeyStart)
            posYcurve.InsertKey(posYkeyStart)
            posZcurve.InsertKey(posZkeyStart)
            rotXcurve.InsertKey(rotXkeyStart)
            rotYcurve.InsertKey(rotYkeyStart)
            rotZcurve.InsertKey(rotZkeyStart)

        # Set EndTime values
        posXkeyEnd = c4d.CKey()
        posYkeyEnd = c4d.CKey()
        posZkeyEnd = c4d.CKey()
        rotXkeyEnd = c4d.CKey()
        rotYkeyEnd = c4d.CKey()
        rotZkeyEnd = c4d.CKey()

        posXkeyEnd.SetTime(posXcurve, c4d.BaseTime(endTime))
        posXkeyEnd.SetValue(posXcurve, camInfo['transform'][0])
        posYkeyEnd.SetTime(posYcurve, c4d.BaseTime(endTime))
        posYkeyEnd.SetValue(posYcurve, camInfo['transform'][1])
        posZkeyEnd.SetTime(posZcurve, c4d.BaseTime(endTime))
        posZkeyEnd.SetValue(posZcurve, camInfo['transform'][2])
        rotXkeyEnd.SetTime(rotXcurve, c4d.BaseTime(endTime))
        rotXkeyEnd.SetValue(rotXcurve, camInfo['transform'][3])
        rotYkeyEnd.SetTime(rotYcurve, c4d.BaseTime(endTime))
        rotYkeyEnd.SetValue(rotYcurve, camInfo['transform'][4])
        rotZkeyEnd.SetTime(rotZcurve, c4d.BaseTime(endTime))
        rotZkeyEnd.SetValue(rotZcurve, camInfo['transform'][5])

        if (curveType == "Sinus"):
            tangentLength = c4d.BaseTime(length * (4.0 / 15.0))
            nTangentLength = c4d.BaseTime(length * (4.0 / 15.0) * -1)

            posXkeyEnd.SetTimeLeft(posXcurve, nTangentLength)
            # posXkeyEnd.SetTimeRight(posXcurve, tangentLength)
            posYkeyEnd.SetTimeLeft(posYcurve, nTangentLength)
            # posYkeyEnd.SetTimeRight(posYcurve, tangentLength)
            posZkeyEnd.SetTimeLeft(posZcurve, nTangentLength)
            # posZkeyEnd.SetTimeRight(posZcurve, tangentLength)
            rotXkeyEnd.SetTimeLeft(rotXcurve, nTangentLength)
            # rotXkeyEnd.SetTimeRight(rotXcurve, tangentLength)
            rotYkeyEnd.SetTimeLeft(rotYcurve, nTangentLength)
            # rotYkeyEnd.SetTimeRight(rotYcurve, tangentLength)
            rotZkeyEnd.SetTimeLeft(rotZcurve, nTangentLength)
            # rotZkeyEnd.SetTimeRight(rotZcurve, tangentLength)

        posXcurve.InsertKey(posXkeyEnd)
        posYcurve.InsertKey(posYkeyEnd)
        posZcurve.InsertKey(posZkeyEnd)
        rotXcurve.InsertKey(rotXkeyEnd)
        rotYcurve.InsertKey(rotYkeyEnd)
        rotZcurve.InsertKey(rotZkeyEnd)

        # Set previousTransform to endTime values
        previousTransform = [
            camInfo['transform'][0], camInfo['transform'][1],
            camInfo['transform'][2], camInfo['transform'][3],
            camInfo['transform'][4], camInfo['transform'][5]
        ]

        previousEndTime = endTime
Exemplo n.º 24
0
def main():
    #load image from file loaction
    img = storage.LoadDialog() 
    if not img:
        return 'Canvas Cancelled.'
    else:
        path, filename = os.path.split(img)
        #get filename
        fname, ext = filename.split('.')

        #load movie
        if not ext in ('mp4','avi'):
            gui.MessageDialog('file format .' + ext +'  not supported!')
        else:
            mov = c4d.bitmaps.MovieLoader()
            mov.Open(img)

            frame, fps = mov.GetInfo()
            

            #create material
            mat = c4d.BaseMaterial(5703)   
            msg = gui.InputDialog('Material Name')
            mat[c4d.MATERIAL_USE_COLOR] = False
            mat[c4d.MATERIAL_USE_LUMINANCE] = True
            mat[c4d.MATERIAL_USE_REFLECTION] = False
            mat[c4d.MATERIAL_PREVIEWSIZE] = + 12
            mat[c4d.MATERIAL_ANIMATEPREVIEW] = True
            doc.StartUndo()
            doc.InsertMaterial(mat)    


            #create shader & add movie file
            mov_texture = c4d.BaseList2D(c4d.Xbitmap)    
            mov_texture[c4d.BITMAPSHADER_FILENAME] = img
            mov_texture[c4d.BITMAPSHADER_TIMING_TO] = frame
            mov_texture[c4d.BITMAPSHADER_TIMING_FPS] = fps     
            mat[c4d.MATERIAL_LUMINANCE_SHADER]= mov_texture        
            mat.InsertShader(mov_texture)
            
            #load bitmap from movie
            bm = c4d.bitmaps.BaseBitmap()
            bm.InitWith(img)
            getsize = bm.GetSize()
            x = getsize[0]
            y = getsize[1]
            
            alphaCheck = bm.GetChannelCount()

            # check if image has alpha channel
            if alphaCheck > 0:
                # Create alpha shader
                alpha_texture = c4d.BaseList2D(c4d.Xbitmap) 
                alpha_texture[c4d.BITMAPSHADER_FILENAME] = img  
                mat[c4d.MATERIAL_USE_ALPHA] = True    
                mat[c4d.MATERIAL_ALPHA_SHADER]= alpha_texture        
                mat.InsertShader(alpha_texture)
                doc.AddUndo(c4d.UNDOTYPE_NEW, alpha_texture)
            else:
                pass

            # create plane
            plane = c4d.BaseObject(5168)
            plane[c4d.PRIM_PLANE_SUBW] = 1
            plane[c4d.PRIM_PLANE_SUBH] = 1
            plane[c4d.PRIM_PLANE_WIDTH] = x
            plane[c4d.PRIM_PLANE_HEIGHT] = y
            doc.InsertObject(plane)
            # assign texture tag to plane
            tag = plane.MakeTag(c4d.Ttexture)
            tag[c4d.TEXTURETAG_PROJECTION] = 6
            tag[c4d.TEXTURETAG_MATERIAL]= mat
            
            # edit name
            if msg in(None,'Material Name?'):
                mat[c4d.ID_BASELIST_NAME] = fname
                plane[c4d.ID_BASELIST_NAME] = fname
            else:
                mat[c4d.ID_BASELIST_NAME] = msg
                plane[c4d.ID_BASELIST_NAME] = msg
            
            # update undos
            doc.AddUndo(c4d.UNDOTYPE_NEW, plane)
            doc.AddUndo(c4d.UNDOTYPE_NEW, mat)
            doc.AddUndo(c4d.UNDOTYPE_NEW, mov_texture)
            doc.EndUndo()
            # add to file
            c4d.EventAdd()
Exemplo n.º 25
0
def main():
    #load image from file loaction
    img = storage.LoadDialog()
    if not img:
        return 'Canvas Cancelled.'
    else:
        path, filename = os.path.split(img)
        #gets directory and lists all images - helps calculate total frames.
        imgSeq = os.listdir(path)
        #gets length of frames
        frames = len(imgSeq)
        #user input framerate
        fps = gui.InputDialog('Framerate')
        #get filename
        fname, ext = filename.split('.')

        #create material
        mat = c4d.BaseMaterial(5703)
        msg = gui.InputDialog('Material Name')
        mat[c4d.MATERIAL_USE_COLOR] = False
        mat[c4d.MATERIAL_USE_LUMINANCE] = True
        mat[c4d.MATERIAL_USE_ALPHA] = True
        mat[c4d.MATERIAL_USE_REFLECTION] = False
        mat[c4d.MATERIAL_PREVIEWSIZE] = +12
        mat[c4d.MATERIAL_ANIMATEPREVIEW] = True
        doc.StartUndo()
        doc.InsertMaterial(mat)

        shdr_texture = c4d.BaseList2D(c4d.Xbitmap)
        shdr_texture[c4d.BITMAPSHADER_FILENAME] = img
        mat[c4d.MATERIAL_LUMINANCE_SHADER] = shdr_texture
        shdr_texture[c4d.BITMAPSHADER_TIMING_TO] = frames
        shdr_texture[c4d.BITMAPSHADER_TIMING_FPS] = float(fps)
        mat.InsertShader(shdr_texture)

        #create bitmap
        bm = c4d.bitmaps.BaseBitmap()
        bm.InitWith(img)
        getsize = bm.GetSize()
        x = getsize[0]
        y = getsize[1]

        alphaCheck = bm.GetChannelCount()

        ### check if image has alpha channel
        if alphaCheck > 0:
            ### Create alpha shader
            alpha_texture = c4d.BaseList2D(c4d.Xbitmap)
            alpha_texture[c4d.BITMAPSHADER_FILENAME] = img
            alpha_texture[c4d.BITMAPSHADER_TIMING_TO] = frames
            alpha_texture[c4d.BITMAPSHADER_TIMING_FPS] = float(fps)
            mat[c4d.MATERIAL_ALPHA_SHADER] = alpha_texture
            mat.InsertShader(alpha_texture)
            doc.AddUndo(c4d.UNDOTYPE_NEW, alpha_texture)
        else:
            pass

        ### create plane
        plane = c4d.BaseObject(5168)
        plane[c4d.PRIM_PLANE_SUBW] = 1
        plane[c4d.PRIM_PLANE_SUBH] = 1
        plane[c4d.PRIM_PLANE_WIDTH] = x
        plane[c4d.PRIM_PLANE_HEIGHT] = y
        doc.InsertObject(plane)
        ##assign texture tag to plane
        tag = plane.MakeTag(c4d.Ttexture)
        tag[c4d.TEXTURETAG_PROJECTION] = 6
        tag[c4d.TEXTURETAG_MATERIAL] = mat

        ## edit name
        if msg == None:
            mat[c4d.ID_BASELIST_NAME] = fname
            plane[c4d.ID_BASELIST_NAME] = fname
        else:
            mat[c4d.ID_BASELIST_NAME] = msg
            plane[c4d.ID_BASELIST_NAME] = msg

        ##update undos
        doc.AddUndo(c4d.UNDOTYPE_NEW, plane)
        doc.AddUndo(c4d.UNDOTYPE_NEW, mat)
        doc.AddUndo(c4d.UNDOTYPE_NEW, shdr_texture)
        doc.EndUndo()
        ##add to file
        c4d.EventAdd()
def main():
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    doc.StartUndo()  # Start recording undos
    folder = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, 'Select image folder',
                          c4d.FILESELECT_DIRECTORY, '')
    if not folder: return  # If no folder, quit the script

    bc = c4d.BaseContainer()  # Initialize a base container
    keyMod = "None"  # Initialize a keyboard modifier status
    # Button is pressed
    if c4d.gui.GetInputState(c4d.BFM_INPUT_KEYBOARD, c4d.BFM_INPUT_CHANNEL,
                             bc):
        if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QSHIFT:
            if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL:  # Ctrl + Shift
                if bc[c4d.
                      BFM_INPUT_QUALIFIER] & c4d.QALT:  # Alt + Ctrl + Shift
                    keyMod = 'Alt+Ctrl+Shift'
                else:  # Shift + Ctrl
                    keyMod = 'Ctrl+Shift'
            elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT:  # Alt + Shift
                keyMod = 'Alt+Shift'
            else:  # Shift
                keyMod = 'Shift'
        elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QCTRL:
            if bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT:  # Alt + Ctrl
                keyMod = 'Alt+Ctrl'
            else:  # Ctrl
                keyMod = 'Ctrl'
        elif bc[c4d.BFM_INPUT_QUALIFIER] & c4d.QALT:  # Alt
            keyMod = 'Alt'
        else:  # No keyboard modifiers used
            keyMod = 'None'

    try:  # Try to execute following script
        files = os.listdir(folder)
        for f in files:  # Loop through files
            extension = f.rpartition(".")[-1].lower()
            formats = [
                "tif", "tiff", "psd", "jpg", "jpeg", "png", "exr", "tga"
            ]  # Supported file formats
            if extension in formats:  # If file is supported
                mat = c4d.BaseMaterial(c4d.Mmaterial)
                path = os.path.join(folder, f)  #path = folder+"\\"+f
                mat[c4d.
                    MATERIAL_USE_REFLECTION] = 0  # Disable reflection channel

                # Color channel
                color = c4d.BaseShader(c4d.Xbitmap)
                color[c4d.BITMAPSHADER_FILENAME] = path
                mat[c4d.MATERIAL_COLOR_SHADER] = color

                # Get bitmap size
                irs = c4d.modules.render.InitRenderStruct(
                )  # Needed to get shader's bitmap info
                if color.InitRender(irs) == c4d.INITRENDERRESULT_OK:
                    bitmap = color.GetBitmap()  # Get bitmap
                    color.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

                # Luminance channel
                luminance = c4d.BaseShader(c4d.Xbitmap)
                luminance[c4d.BITMAPSHADER_FILENAME] = path
                mat[c4d.MATERIAL_LUMINANCE_SHADER] = luminance

                # Alpha channel
                alpha = c4d.BaseShader(c4d.Xbitmap)
                alpha[c4d.BITMAPSHADER_FILENAME] = path
                mat[c4d.MATERIAL_ALPHA_SHADER] = alpha

                # Assign shaders to material
                mat.InsertShader(color)  # Insert shader to color channel
                mat.InsertShader(
                    luminance)  # Insert shader to luminance channel
                mat.InsertShader(alpha)  # Insert shader to alpha channel

                # Other stuff
                mat.Message(c4d.MSG_UPDATE)
                mat.Update(True, True)  # Update material
                matname = f.rpartition(".")[
                    0]  # Get material name from file path
                mat.SetName(matname)  # Set material name
                doc.InsertMaterial(mat)  # Insert new material to document
                doc.AddUndo(c4d.UNDOTYPE_NEW,
                            mat)  # Add undo command for inserting new material

                if keyMod == "Shift":  # If Shift key pressed - Generate planes and assign materials to them
                    # Create plane
                    plane = c4d.BaseObject(
                        c4d.Oplane)  # Initialize plane object
                    plane.SetName(
                        matname)  # Set plane's name same as the material 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
                    doc.InsertObject(plane)  # Insert plane to document
                    doc.AddUndo(
                        c4d.UNDOTYPE_NEW, plane
                    )  # Add undo command for inserting plane to document

                    # Texture tag
                    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
                    doc.AddUndo(
                        c4d.UNDOTYPE_NEW, tag
                    )  # Add undo command for inserting texture tag to object

    except:  # If something went wrong
        pass  # Do nothing

    doc.EndUndo()  # Stop recording undos
    c4d.EventAdd()  # Refresh Cinema 4D
Exemplo n.º 27
0
def main():
    global path, rangeStart, rangeEnd

    doc = documents.GetActiveDocument()
    docFPS = doc[c4d.DOCUMENT_FPS]

    d_print("Document FPS: " + str(docFPS))

    try:
        cam = doc.GetSelection()[0]
        if not cam.GetType() == 5103:
            gui.MessageDialog("Please select a Camera to export")
            return
    except IndexError:
        gui.MessageDialog("Please select a Camera to export")
        return

    camTracks = []

    for i in range(903, 905):
        for j in range(1000, 1003):
            track = cam.FindCTrack(
                c4d.DescID(c4d.DescLevel(i), c4d.DescLevel(j)))
            camTracks.append(track)

    rangeStart = camTracks[0].GetCurve().GetKey(0).GetTime().GetFrame(docFPS)
    rangeEnd = camTracks[0].GetCurve().GetKey(
        camTracks[0].GetCurve().GetKeyCount() - 1).GetTime().GetFrame(docFPS)

    dlg = Dialog()
    dlg.startFrame = rangeStart
    dlg.endFrame = rangeEnd
    dlg.Open(c4d.DLG_TYPE_MODAL_RESIZEABLE, defaultw=500)

    if not dlg.didPressOK:
        return

    keyFrameInterval = dlg.keyFrameInterval
    timeOffsetInFrames = dlg.timeOffsetInFrames
    sceneScale = dlg.sceneScale
    frameSpaceInS = dlg.frameSpaceInS
    startFrame = dlg.startFrame
    endFrame = dlg.endFrame
    targetFPS = dlg.targetFPS

    d_print("Keyframe Interval: " + str(keyFrameInterval))
    d_print("Time Offset: " + str(timeOffsetInFrames))
    d_print("Scene Scale: " + str(sceneScale))
    d_print("Frame Space: " + str(frameSpaceInS))
    d_print("Range Start: " + str(rangeStart))
    d_print("Range End: " + str(rangeEnd))
    d_print("Target FPS: " + str(targetFPS))

    path = storage.LoadDialog(flags=2)

    if not path:
        print "No path found"
        return

    if not os.path.exists(path + '/fullsequence_empty.xml'):
        os.rename(path + '/fullsequence.xml', path + '/fullsequence_empty.xml')

    f = open(path + '/fullsequence_empty.xml', 'r')
    xmlText = f.read()
    f.close()

    split1 = string.rfind(xmlText, "</Syncronorm_ShowSequence_V1.0>")
    split2 = string.rfind(xmlText, "</blocks>")

    string1 = xmlText[:split2 - 1]
    string2 = xmlText[split2:split1 - 1]
    string3 = xmlText[split1:]

    insertString1 = ""
    insertString2 = "<SceneList>"

    for frame in range(startFrame, endFrame + keyFrameInterval,
                       keyFrameInterval):

        d_print("\n\n---------- Frame: " + str(frame) + ' ----------')

        ID = str(uuid.uuid4())

        startTime = (frame / targetFPS) + (timeOffsetInFrames / targetFPS) - (
            keyFrameInterval / targetFPS) + (1 / docFPS)
        startTime = string.replace(str(startTime), ".", ",")

        d_print("Start Time: " + str(startTime))

        length = (keyFrameInterval / targetFPS) - frameSpaceInS
        length = string.replace(str(length), ".", ",")

        d_print("Length: " + str(length))

        doc.SetTime(c4d.BaseTime(frame, docFPS))

        c4d.DrawViews(c4d.DA_ONLY_ACTIVE_VIEW | c4d.DA_NO_THREAD
                      | c4d.DA_NO_REDUCTION | c4d.DA_STATICBREAK)
        c4d.GeSyncMessage(c4d.EVMSG_TIMECHANGED)

        posX = cam.GetMg().off.x * sceneScale
        posY = cam.GetMg().off.y * sceneScale
        posZ = -cam.GetMg().off.z * sceneScale
        rotX = -MatrixToHPB(cam.GetMg()).x * 180 / math.pi
        rotY = -MatrixToHPB(cam.GetMg()).y * 180 / math.pi
        rotZ = MatrixToHPB(cam.GetMg()).z * 180 / math.pi

        if (rotX <= -180):
            rotX = rotX + 360
        if (rotX >= 180):
            rotX = rotX - 360

        if (rotY <= -180):
            rotY = rotY + 360
        if (rotY >= 180):
            rotY = rotY - 360

        if (rotZ <= -180):
            rotZ = rotZ + 360
        if (rotZ >= 180):
            rotZ = rotZ - 360

        # posX = round(posX, 6)
        # posY = round(posY, 6)
        # posZ = round(posZ, 6)
        rotX = round(rotX, 3)
        rotY = round(rotY, 3)
        rotZ = round(rotZ, 3)

        posX = string.replace(str(posX), ".", ",")
        posY = string.replace(str(posY), ".", ",")
        posZ = string.replace(str(posZ), ".", ",")
        rotX = string.replace(str(rotX), ".", ",")
        rotY = string.replace(str(rotY), ".", ",")
        rotZ = string.replace(str(rotZ), ".", ",")

        d_print(posX)
        d_print(posY)
        d_print(posZ)
        d_print(rotX)
        d_print(rotY)
        d_print(rotZ)

        insertString1 = (
            insertString1 + '\n<block Name="CamPos" StartTime="' + startTime +
            '" Lenght="' + length + '" FadeInTime="' + length +
            '" FadeOutTime="0" DelayInTime="0" DelayOutTime="0" BeatsPerMinute="120" UseACD="False" ACD_InDelay="0" ACD_InFade="0" ACD_OutDelay="0" ACD_OutFade="0" Mute="False" Freeze="False" Tracking="True" EffectSpeedOffset="0" MultiSceneGUID="'
            + ID +
            '" CueListGUID="" FadeCenter="True" FadeAmplitude="True" FadePhase="True" FadeRpM="False" UsedCenter="True" UsedAmplitude="True" UsedPhase="True" UsedRpM="True" InFadeRate="100" OutFadeRate="100" FadeType="0" DelayType="0" LightColor="-1">\n'
            +
            '  <LightColorX red="255" green="255" blue="255" amber="0" white="0" intensity="255" CellX="0" CellY="0"></LightColorX>\n'
            + '</block>')

        insertString2 = (
            insertString2 + '<scene GroupGUID="" GUID="' + ID +
            '" AggTypeGUID="" InDelayTime="0" InFadeTime="0" Name="CamPos" OutDelayTime="0" OutFadeTime="0" IsUniqueBlockScene="False" UsedSplines="True">\n'
            + '  <Items>\n' +
            '    <Item UID="65500" PatternGUID="" Amplitude="0" Center="0" EffectGUID="" InDelayPoint="0" InFadePoint="100" Offset="0" OutDelayPoint="0" OutFadePoint="100" MaxPhase="0" Phase="'
            + posX +
            '" RpM="0" NumWaves="1" GoOut="0" CutAfter="1" SelectionIndex="0" Direction="0" TogleWinkelLeft="0" TogleWinkelRight="360" VisibleWaves="1" BNC_StartReverse="False" ValueOffset="0" FadeCenter="True" FadeAmplitude="True" FadePhase="True" FadeRpM="False" UsedCenter="True" UsedAmplitude="True" UsedPhase="True" UsedRpM="True" InFadeRate="100" OutFadeRate="100" FadeType="0" DelayType="0"></Item>\n'
            +
            '      <Item UID="65504" PatternGUID="" Amplitude="0" Center="0" EffectGUID="" InDelayPoint="0" InFadePoint="100" Offset="0" OutDelayPoint="0" OutFadePoint="100" MaxPhase="0" Phase="'
            + posY +
            '" RpM="0" NumWaves="1" GoOut="0" CutAfter="1" SelectionIndex="0" Direction="0" TogleWinkelLeft="0" TogleWinkelRight="360" VisibleWaves="1" BNC_StartReverse="False" ValueOffset="0" FadeCenter="True" FadeAmplitude="True" FadePhase="True" FadeRpM="False" UsedCenter="True" UsedAmplitude="True" UsedPhase="True" UsedRpM="True" InFadeRate="100" OutFadeRate="100" FadeType="0" DelayType="0"></Item>\n'
            +
            '      <Item UID="65508" PatternGUID="" Amplitude="0" Center="0" EffectGUID="" InDelayPoint="0" InFadePoint="100" Offset="0" OutDelayPoint="0" OutFadePoint="100" MaxPhase="0" Phase="'
            + posZ +
            '" RpM="0" NumWaves="1" GoOut="0" CutAfter="1" SelectionIndex="0" Direction="0" TogleWinkelLeft="0" TogleWinkelRight="360" VisibleWaves="1" BNC_StartReverse="False" ValueOffset="0" FadeCenter="True" FadeAmplitude="True" FadePhase="True" FadeRpM="False" UsedCenter="True" UsedAmplitude="True" UsedPhase="True" UsedRpM="True" InFadeRate="100" OutFadeRate="100" FadeType="0" DelayType="0"></Item>\n'
            +
            '      <Item UID="65512" PatternGUID="" Amplitude="0" Center="0" EffectGUID="" InDelayPoint="0" InFadePoint="100" Offset="0" OutDelayPoint="0" OutFadePoint="100" MaxPhase="0" Phase="'
            + rotX +
            '" RpM="0" NumWaves="1" GoOut="0" CutAfter="1" SelectionIndex="0" Direction="0" TogleWinkelLeft="0" TogleWinkelRight="360" VisibleWaves="1" BNC_StartReverse="False" ValueOffset="0" FadeCenter="True" FadeAmplitude="True" FadePhase="True" FadeRpM="False" UsedCenter="True" UsedAmplitude="True" UsedPhase="True" UsedRpM="True" InFadeRate="100" OutFadeRate="100" FadeType="0" DelayType="0"></Item>\n'
            +
            '      <Item UID="65516" PatternGUID="" Amplitude="0" Center="0" EffectGUID="" InDelayPoint="0" InFadePoint="100" Offset="0" OutDelayPoint="0" OutFadePoint="100" MaxPhase="0" Phase="'
            + rotY +
            '" RpM="0" NumWaves="1" GoOut="0" CutAfter="1" SelectionIndex="0" Direction="0" TogleWinkelLeft="0" TogleWinkelRight="360" VisibleWaves="1" BNC_StartReverse="False" ValueOffset="0" FadeCenter="True" FadeAmplitude="True" FadePhase="True" FadeRpM="False" UsedCenter="True" UsedAmplitude="True" UsedPhase="True" UsedRpM="True" InFadeRate="100" OutFadeRate="100" FadeType="0" DelayType="0"></Item>\n'
            +
            '      <Item UID="65520" PatternGUID="" Amplitude="0" Center="0" EffectGUID="" InDelayPoint="0" InFadePoint="100" Offset="0" OutDelayPoint="0" OutFadePoint="100" MaxPhase="0" Phase="'
            + rotZ +
            '" RpM="0" NumWaves="1" GoOut="0" CutAfter="1" SelectionIndex="0" Direction="0" TogleWinkelLeft="0" TogleWinkelRight="360" VisibleWaves="1" BNC_StartReverse="False" ValueOffset="0" FadeCenter="True" FadeAmplitude="True" FadePhase="True" FadeRpM="False" UsedCenter="True" UsedAmplitude="True" UsedPhase="True" UsedRpM="True" InFadeRate="100" OutFadeRate="100" FadeType="0" DelayType="0"></Item>\n'
            + '    </Items>\n' + '  <WayPoints PointData=""></WayPoints>\n' +
            '</scene>\n')

    insertString1 = insertString1 + ""
    insertString2 = insertString2 + "</SceneList>"

    f = open(path + '/fullsequence.xml', 'w')
    f.write(string1 + insertString1 + string2 + insertString2 + string3)
    f.close()

    gui.MessageDialog("Camera Export Successful")
Exemplo n.º 28
0
def main():
    doc = c4d.documents.GetActiveDocument()  # Get active Cinema 4D document
    doc.StartUndo()  # Start recording undos
    folder = s.LoadDialog(c4d.FILESELECTTYPE_ANYTHING, 'Select image folder',
                          c4d.FILESELECT_DIRECTORY, '')
    if not folder: return
    try:  # Try to execute following script
        files = os.listdir(folder)
        for f in files:  # Loop through files
            mat = c4d.BaseMaterial(c4d.Mmaterial)
            path = folder + "\\" + f
            mat[c4d.MATERIAL_USE_REFLECTION] = 0  # Disable reflection channel

            # Color channel
            color = c4d.BaseShader(c4d.Xbitmap)
            color[c4d.BITMAPSHADER_FILENAME] = path
            mat[c4d.MATERIAL_COLOR_SHADER] = color

            # Get bitmap size
            irs = c4d.modules.render.InitRenderStruct(
            )  # Needed to get shader's bitmap info
            if color.InitRender(irs) == c4d.INITRENDERRESULT_OK:
                bitmap = color.GetBitmap()  # Get bitmap
                color.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

            # Luminance channel
            luminance = c4d.BaseShader(c4d.Xbitmap)
            luminance[c4d.BITMAPSHADER_FILENAME] = path
            mat[c4d.MATERIAL_LUMINANCE_SHADER] = luminance

            # Alpha channel
            alpha = c4d.BaseShader(c4d.Xbitmap)
            alpha[c4d.BITMAPSHADER_FILENAME] = path
            mat[c4d.MATERIAL_ALPHA_SHADER] = alpha

            # Assign shaders to material
            mat.InsertShader(color)  # Insert shader to color channel
            mat.InsertShader(luminance)  # Insert shader to luminance channel
            mat.InsertShader(alpha)  # Insert shader to alpha channel

            # Other stuff
            mat.Message(c4d.MSG_UPDATE)
            mat.Update(True, True)  # Update material
            matname = f.split(".")[0]  # Get material name from file path
            mat.SetName(matname)  # Set material name
            doc.InsertMaterial(mat)  # Insert new material to document
            doc.AddUndo(c4d.UNDOTYPE_NEW,
                        mat)  # Add undo command for inserting new material

            # Create plane
            plane = c4d.BaseObject(c4d.Oplane)  # Initialize plane object
            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
            doc.InsertObject(plane)  # Insert plane to document
            doc.AddUndo(
                c4d.UNDOTYPE_NEW,
                plane)  # Add undo command for inserting plane to document

            # Texture tag
            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
            doc.AddUndo(
                c4d.UNDOTYPE_NEW,
                tag)  # Add undo command for inserting texture tag to object

    except:  # If something went wrong
        pass  # Do nothing
    doc.EndUndo()  # Stop recording undos
    c4d.EventAdd()  # Refresh Cinema 4D
Exemplo n.º 29
0
def load_dialog(title="Load file"):
    win = storage.LoadDialog(title=title)
    return win.decode("utf-8") if win else ""