Esempio n. 1
0
def StartConverting(root_directory=''):
    root_dir = os.path.join(SelectDirectory(root_directory), '')
    if os.path.isdir(root_dir):
        rvalue = gui.QuestionDialog(
            '"' + root_dir + '" was selected. Start search for c4d files?')
    else:
        rvalue = gui.QuestionDialog(
            'Path "' + root_dir +
            '" is not an existing directory. Continue anyway?')
    if rvalue:
        ExportAllC4DFiles(root_dir)
    gui.MessageDialog('Exiting from script')
Esempio n. 2
0
def GetC4DFiles(root_directory):
    filelist_path = os.path.join(root_directory, 'file_list.txt')
    if os.path.exists(filelist_path):
        rvalue = gui.QuestionDialog('File list "' + filelist_path +
                                    '" was found. Load files from there?')
        if rvalue:
            FileList = []
            flp = open(filelist_path, 'r')
            for fline in flp:
                cur_line = fline.strip().decode('utf-8')
                if cur_line == '':
                    continue
                FileList.append(cur_line)
            flp.close()
        else:
            FileList = ListC4DFiles(root_directory)
    else:
        FileList = ListC4DFiles(root_directory)
    FileDict = {}
    for filepath in FileList:
        if FileDict.get(filepath, None) is None:
            if not os.path.exists(os.path.splitext(filepath)[0] + '.fbx'):
                FileDict.setdefault(filepath, True)
    FileList = FileDict.keys()
    FileList.sort()
    flp = open(filelist_path, 'w')
    for name in FileList:
        print >> flp, name.encode('utf-8')
    flp.close()
    return FileList
Esempio n. 3
0
def main():

    doc = c4d.documents.GetActiveDocument()
    activeMaterials = doc.GetActiveMaterials()
    qSwapMat = gui.QuestionDialog("Do you want to sawp the material assignments?")

    for material in activeMaterials:
        VtoA(material, qSwapMat)
    def __init__(self, curObj, wasSelected=None, printErrors=True):
        self.doc = c4d.documents.GetActiveDocument()
        if wasSelected is None:
            wasSelected = curObj
        self.allWeightTags = []
        self.curObj = curObj
        doc = c4d.documents.GetActiveDocument()
        allobjects = doc.GetObjects()
        messageStr = "OK"
        self.getAllWeightTags(allobjects)
        self.expressionTagsToRestore = []
        self.disableExpressionsOnJoints([curObj], self.expressionTagsToRestore)
        c4d.DrawViews(c4d.DRAWFLAGS_FORCEFULLREDRAW)
        c4d.EventAdd()
        self.resetBindPose(curObj, wasSelected)
        if self.isRightScale([curObj]) == False:
            rvalue = gui.QuestionDialog(
                "Skeleton contains Joints with other Scale than '1,1,1'.\n\n Fix automatically?"
            )
            if rvalue == True:
                self.setRightScale([self.curObj])
                self.setNewBindPose(curObj, wasSelected)
            if rvalue == False:
                messageStr = "ERROR: Some Joints have Scale-Values other than '1,1,1' !!!\n\n"
        skinnedMatrices = self.checkBind()
        rvalue1 = False
        if len(skinnedMatrices) >= 1:
            rvalue1 = gui.QuestionDialog(
                "Joints are bound to a 'Skinning-Matrix' thats not the Global Matrix of the C4D-Scene.\nTo prevent errors all meshes should be skinned to the GLobal-C4D-Matrix.\nFix automaticcaly ?"
            )
            if rvalue1 == True:
                self.setSkinMgToGlobal()
                self.setNewBindPose(curObj, wasSelected)
            if rvalue1 == False:
                if messageStr == "OK":
                    messageStr = ""
                messageStr += "ERROR: Joints are bound to a 'Skinning-Matrix', thats not the Global Matrix of the C4D-Scene.\nTo prevent Errors all Objects should be skinned to the GLobal-C4D-Matrix.\n\n"

        #print ("Skeleton Status\n"+str(messageStr))
        if printErrors == True:
            gui.MessageDialog("Skeleton Status\n" + str(messageStr))
            for tag in self.expressionTagsToRestore:
                tag[c4d.EXPRESSION_ENABLE] = True
Esempio n. 5
0
def report():
    err = None
    try:
        yield
    except Exception:
        if gui.QuestionDialog(
                "There was an error running the script. Would you like to send a brief report?"
        ):
            # Generate Report
            webbrowser.open(
                "mailto:{email}?subject={subject}&body={body}".format(
                    email=REPORT_ADDR,
                    subject=urllib.quote(REPORT_SUBJ),
                    body=urllib.quote("\n".join(
                        (str(datetime.datetime.now()), platform.platform(),
                         "C4D version %s" % c4d.GetC4DVersion(), __file__,
                         traceback.format_exc())))))
        raise
Esempio n. 6
0
def main():

    confirm = gui.QuestionDialog('Download and install scripts from github?')

    if confirm:

        # c4d script folder
        scriptFolder = c4d.storage.GeGetC4DPath(1)[:-6] + '/library/scripts/'

        # download github repo
        url = 'https://github.com/hanswillem/c4dquicktools/archive/master.zip'
        targetDir = os.path.expanduser('~/Desktop/')
        target = targetDir + '/master.zip'
        urllib.urlretrieve(url, target)

        # unzip
        zip_ref = zipfile.ZipFile(target, mode='r')
        zip_ref.extractall(targetDir)
        zip_ref.close()
        extractdDir = os.path.expanduser('~/Desktop/c4dquicktools-master')

        # copy
        allScriptFiles = [
            f for f in os.listdir(extractdDir) if
            os.path.splitext(f)[1] == '.py' or os.path.splitext(f)[1] == '.tif'
        ]
        for i in allScriptFiles:
            fullPath = os.path.join(extractdDir, i)
            fullPathTarget = os.path.join(scriptFolder, i)
            shutil.copy(fullPath, fullPathTarget)

        # clean up
        os.remove(target)
        shutil.rmtree(extractdDir)

        # message
        c4d.gui.MessageDialog('Scripts downloaded and installed!')
Esempio n. 7
0
def main():
    #Check Modifiers
    ctrl, shift, alt = GetModifiers()

    #Get String from Clipboard
    clipboard = c4d.GetStringFromClipboard()
    if not clipboard.startswith('AE-C4D-CopyPasteColors'):
        gui.MessageDialog(
            'Please, use "copy-colors.jsx" for After Effects first...')
        return

    myName, myColors, my4DColors = GetColors(clipboard)

    #Import only Planes with Colors, without any questions...
    if alt:
        InsertColorPlanes(myName, myColors)
        return

    #Handle Pre R18 Releases
    if c4d.GetC4DVersion() <= 18011:
        gui.MessageDialog("Sorry, Swatches haven't been introduced yet!")
        question = gui.QuestionDialog(
            "Do you want to Create Planes with Colors?")
        if question:
            InsertColorPlanes(myName, myColors)
        return

    #Handle Post R18 Pre R20 Releases
    if c4d.GetC4DVersion() >= 18011 and c4d.GetC4DVersion() <= 20000:
        InsertSwatchesR18(doc, myName, myColors)

    #Handle Post R20 Releases
    if c4d.GetC4DVersion() >= 20000:
        InsertSwatchesR20(doc, myName, my4DColors)

    c4d.EventAdd()
Esempio n. 8
0
    def genesis_import(self, file_path, dtu, sss_value, normal_value,
                       bump_value):
        mat = StandardMaterials.StdMaterials()
        morph = Morphs.Morphs()
        var = Utilities.Variables()
        jnt_fixes = DazRig.JointFixes()
        wgt = Weights()
        anim = Animations.Animations()
        pose = Poses()

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

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

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

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

        print("Starting Material Updates")

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

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

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

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

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

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

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

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

        self.dialog = guiASKtoSave()
        self.dialog.Open(
            dlgtype=c4d.DLG_TYPE_MODAL,
            xpos=screen["sx2"] // 2 - 210,
            ypos=screen["sy2"] // 2 - 100,
            defaultw=200,
            defaulth=150,
        )
Esempio n. 9
0
def main(doc):
    options = [
        "Import Animation (absolute)", "Import Animation (relative)",
        "Export Animation"
    ]
    picked = choice(*options)

    if picked == options[0] or picked == options[1]:  # Import
        file_path = load_dialog(title="Load Animation")
        if file_path:
            with open(file_path, "r") as f:
                data = json.load(f)
            selection = get_selection(doc)
            if not selection: return gui.MessageDialog("Nothing Selected. :(")
            curves = dict(b for a in get_selection(doc) for b in get_tracks(a))
            exists = [(a, b) for a, b in data.iteritems() if a in curves]
            if not exists:
                return gui.MessageDialog(
                    "Nothing selected can have animation applied. :(")

            do_offset = gui.QuestionDialog(
                "Would you like to import your Animation starting at the current time?"
            )
            relative = picked == options[1]
            curr_time = doc.GetTime()
            fps = doc.GetFps()

            if do_offset:
                exists = zero_time(
                    exists)  # Zero out our time so we can offset successfully
                time_offset = curr_time.Get()
            else:
                time_offset = 0

            for name, keys in exists:
                curve = curves[name].GetCurve()

                if relative:
                    print name, curve.GetValue(c4d.BaseTime(keys[0][0]),
                                               fps), keys[0][1]
                    value_offset = curve.GetValue(c4d.BaseTime(keys[0][0]),
                                                  fps) - keys[0][1]
                else:
                    value_offset = 0

                for key in keys:
                    offset_key(key, time=time_offset, value=value_offset)
                    set_key(curve, key)

                # Remove existing keyframes
                # times = set(a[0] for a in keys)
                # min_, max_ = min(times), max(times)
                # existing_keys = get_keys(curve)
                # for key in existing_keys: # Remove existing keys that eat into new animation space
                #     if min_ <= key[0] <= max_:
                #         key = curve.FindKey(c4d.BaseTime(key[0]))
                #         curve.DelKey(key["idx"])

    elif picked == options[2]:  # Export
        data = dict((b, list(get_keys(c.GetCurve())))
                    for a in get_selection(doc) for b, c in get_tracks(a))
        if not data: return gui.MessageDialog("No Animation to Export. :(")
        # zero_time(data) # Zero time
        file_path = save_dialog("Save Animation")
        if file_path:
            _, ext = os.path.splitext(file_path)
            if ext != EXTENSION:
                file_path += EXTENSION
            with open(file_path, "w") as f:
                json.dump(data, f, indent=4)
            print "Animation Exported to ", file_path
Esempio n. 10
0
    def gather(self, init=False, *a):
        # INITIALIZATION
        # This branch pulls in raw data from the scene.  The user will have the option
        # to modify it in the UI, which is parsed in the "not init" branch below.

        # RenderData container object
        doc = c4d.documents.GetActiveDocument()
        rd = doc.GetActiveRenderData()

        # Get C4D version
        version = c4d.GetC4DVersion() / 1000
        version_map = {
            17: "R:\\Program Files\\MAXON\\CINEMA 4D R17\\CINEMA 4D.exe",
            15:
            "R:\\Program Files\\MAXON\\CINEMA 4D R15\\CINEMA 4D 64 Bit.exe",
            14: "R:\\Program Files\\MAXON\\CINEMA 4D R14\\CINEMA 4D 64 Bit.exe"
        }

        if (init):
            # Scene name / location
            scene_name = doc.GetDocumentName()
            scene_path = doc.GetDocumentPath() + '\\' + scene_name

            # Getting frame range in cinema is a PITA
            fps = rd[c4d.RDATA_FRAMERATE]
            step = rd[c4d.RDATA_FRAMESTEP]
            start = rd[c4d.RDATA_FRAMEFROM]
            end = rd[c4d.RDATA_FRAMETO]
            start_frame = start.Get() * fps
            end_frame = end.Get() * fps
            # Additional steps for frame step formatting
            frame_range = str(int(start_frame)) + "-" + str(int(end_frame))
            if step > 1:
                frame_range += ("x" + str(step))

            # Is saving output files enabled?
            self.save_main_bool = rd[c4d.RDATA_SAVEIMAGE]
            self.save_multi_bool = rd[c4d.RDATA_MULTIPASS_SAVEIMAGE]

            # Get output paths.
            output_path = {
                True: rd[c4d.RDATA_PATH],
                False: ""
            }[self.save_main_bool]
            output_multi_path = {
                True: rd[c4d.RDATA_MULTIPASS_FILENAME],
                False: ""
            }[self.save_multi_bool]

            # Default placeholder values
            cluster = ""
            restrictions = ""
            priority = 0

        # POST-LAUNCH PARSING
        # This branch parses the UI for any overrides or changes the user has made.
        if not (init):
            # Scene data
            scene_name = self.GetString(TXT_JOB_NAME)
            scene_path = self.GetString(TXT_SCENE_FILE)
            output_path = self.GetString(TXT_RENDER_PATH)
            output_multi_path = self.GetString(TXT_MULTI_PATH)
            frame_range = self.GetString(TXT_FRAME_RANGE)
            # Farm data
            priority = self.GetString(TXT_PRIORITY)
            cluster = self.GetString(TXT_CLUSTER)
            restrictions = self.GetString(TXT_RESTRICTIONS)

        # Timestamp
        timestamp = datetime.datetime.fromtimestamp(
            time.time()).strftime('%Y-%m-%d %H:%M:%S') + " " + str(
                int(uniform(100, 300)))

        # FORMATTING / CLEANUP / DEPENDENT FLAGS
        # Pathing everything to \\cagenas from Y/W:
        for letter in mapped_drives:
            scene_path = scene_path.replace(letter, nas_unc)
            output_path = output_path.replace(letter, nas_unc)
            output_multi_path = output_multi_path.replace(letter, nas_unc)

        # Dealing with threads
        if self.GetBool(BOOL_ALL_THREADS):
            threads = 0
            reservations = 'host.processors=1+'
            requirements = 'host.processors.used==0'
            useAllCores = 1
            rtc = 1
        else:
            threads = self.GetString(TXT_NUM_THREADS)
            reservations = 'host.processors=' + str(threads)
            requirements = ''
            useAllCores = 0
            rtc = threads

        # SANITY CHECKS --
        # 1.  Is saving render output enabled?
        if not rd[c4d.RDATA_GLOBALSAVE]:
            chk = gui.QuestionDialog(
                "Saving is not enabled for rendering!  You'll need to turn that on in Render Settings."
            )
            self.Close()

        if not self.save_main_bool:
            chk = gui.QuestionDialog(
                "Saving is not enabled for your beauty render.  Do you want to proceed?"
            )
            if chk: pass
            else: self.Close()

        if not self.save_multi_bool:
            chk = gui.QuestionDialog(
                "Saving is not enabled for your multi-passes.  Do you want to proceed?"
            )
            if chk: pass
            else: self.Close()

        # 2.  Is the full path to the scene file too long to render?
        if len(scene_path) > 199:
            chk = gui.QuestionDialog(
                "The full path to your scene file...:\n" + str(scene_path) +
                "\n...Is too long.  You'll need to shorten it before you submit."
            )
            self.Close()

        # 3. Is the user attempting to submit a scene saved locally, or trying to output renders to a local drive?
        for d in local_drives:
            if d in scene_path or d in output_path or d in output_multi_path:
                chk = gui.QuestionDialog(
                    "Your scene file or render output are set to a local drive.  You'll need to change this before you submit."
                )
                self.Close()

        # 4. Are there unsaved changes in the scene?
        unsaved_changes = c4d.documents.GetActiveDocument().GetChanged()
        if (unsaved_changes):
            chk = gui.QuestionDialog(
                "Your scene has unsaved changes. Proceed anyway?")
            if (chk): pass
            else: self.Close()

        # The Qube submission dictionary
        submit_dict = {
            'name': scene_name,
            'prototype': 'cmdrange',
            'package': {
                'simpleCmdType': 'Cinema4d (Win)',
                'c4dExe': version_map[version],
                'c4dVersion': [version, '0', None],
                '-render': scene_path,
                '-oimage': output_path,
                '-omultipass': output_multi_path,
                'range': frame_range,
                'threads': threads,
                'useAllCores': useAllCores,
                'renderThreadCount': rtc
            },
            'label': timestamp,
            'cluster': cluster,
            'restrictions': restrictions,
            'priority': priority,
            'cpus': cpu_limit,
            'reservations': reservations,
            'requirements': requirements,
            'flagsstring': 'auto_wrangling,disable_windows_job_object'
        }

        return submit_dict
Esempio n. 11
0
    def checkIfPosedResetPose(self, checkAndReset=True):
        def checkIfPosed():
            obj = doc.GetFirstObject()
            scene = ObjectIterator(obj)
            jointsList = [
                "Collar",
                "head",
                "ShldrTwist",
                "Forearm",
                "pelvis",
                "abdomen",
                "Shldr",
            ]
            caca = False

            def checkJoint(jointName):
                joint = doc.SearchObject(jointName)
                if joint:
                    rotRX = abs(joint[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_X])
                    rotRY = abs(joint[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Y])
                    rotRZ = abs(joint[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Z])
                    if rotRX == rotRY == rotRZ == 0.0:
                        return False
                    else:
                        return True

            def compareJoints(jointName):
                jointR = doc.SearchObject("r" + jointName)
                jointL = doc.SearchObject("l" + jointName)
                if jointR:
                    rotRX = abs(jointR[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_X])
                    rotRY = abs(jointR[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Y])
                    rotRZ = abs(jointR[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Z])
                    rotLX = abs(jointL[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_X])
                    rotLY = abs(jointL[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Y])
                    rotLZ = abs(jointL[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Z])
                    rotRX = round(rotRX, 2)
                    rotRY = round(rotRY, 2)
                    rotRZ = round(rotRZ, 2)
                    rotLX = round(rotLX, 2)
                    rotLY = round(rotLY, 2)
                    rotLZ = round(rotLZ, 2)
                    if rotRX == rotLX and rotRY == rotLY and rotRZ == rotLZ:
                        return False
                    else:
                        return True

            isPosed = False

            if compareJoints("ForeArm"):
                isPosed = True
            if compareJoints("Shldr"):
                isPosed = True
            if compareJoints("ShldrBend"):
                isPosed = True
            if compareJoints("ForearmBend"):
                isPosed = True
            if compareJoints("Hand"):
                isPosed = True
            if compareJoints("ThighBend"):
                isPosed = True
            if checkJoint("chestUpper"):
                isPosed = True
            if checkJoint("chestLower"):
                isPosed = True
            if checkJoint("abdomenLower"):
                isPosed = True
            if checkJoint("abdomenUpper"):
                isPosed = True
            if checkJoint("neckLower"):
                isPosed = True

            return isPosed

        doc = documents.GetActiveDocument()
        if checkAndReset == False:
            return checkIfPosed()
        jointHip = doc.SearchObject("hip")
        jointRig = ObjectIterator(jointHip)
        if checkIfPosed():
            answer = gui.QuestionDialog(
                "Reset Pose first before Auto-Ik.\nReset Pose now?\n\nWarning: No Undo"
            )
            if answer:
                for x in jointRig:
                    x[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_X] = 0.0
                    x[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Y] = 0.0
                    x[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Z] = 0.0
                jointHip[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_X] = 0.0
                jointHip[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Y] = 0.0
                jointHip[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Z] = 0.0

                try:
                    mainJoint = jointHip.GetUp()
                    mainJoint[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_X] = 0.0
                    mainJoint[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Y] = 0.0
                    mainJoint[c4d.ID_BASEOBJECT_REL_ROTATION, c4d.VECTOR_Z] = 0.0
                    mainJoint[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_X] = 0.0
                    mainJoint[c4d.ID_BASEOBJECT_REL_POSITION, c4d.VECTOR_Z] = 0.0
                except:
                    pass

                self.dazManualRotationFixTpose()

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

                AllSceneToZero().sceneToZero()
                answer = gui.QuestionDialog("Would You Like to Run\nAUTO-IK")
                if answer:
                    return True
                else:
                    return False

        else:
            return True
Esempio n. 12
0
def popup( title='', msg='', type='ok', defaultInput='', pyside=False, _list=[], selNum=0, winPrnt=None ) :
    'Attempts to build a simple dialog window in either native application calls, or PySide'
    app=F.get_app()
    userInput=''
    
    #  Create PySide window :
    if pyside :
        try :
            if type=='comboBox' :
                userInput, ok=QtGui.QInputDialog.getItem( winPrnt, title, msg, _list, 0, False )
                if not ok :
                    userInput=None
        except :
            P.error( 'Sorry, problem loading the dialog.' )
    
    # Cinesync Window :        
    elif app == 'Cinesync':
        try:
            if type == 'input' or type == 'okCancel':
                userInput, ok = QtGui.QInputDialog.getText(winPrnt, title, msg, QtGui.QLineEdit.Normal, defaultInput)
                if not ok:
                    userInput = None

        except Exception as err:
            P.error('Error with dialog: %s' % str(err))
    
    #  Maya Window :
    elif app=='Maya' :
        import maya.cmds as mc
        if type=='ok' :
            userInput=mc.confirmDialog( title=title, message=msg, button=['OK'], \
                defaultButton='OK' )
        elif type=='okCancel' :
            userInput=mc.confirmDialog( title=title, message=msg, button=['OK', 'Cancel'], \
                defaultButton='OK', cancelButton='Cancel', dismissString='Cancel' )
        elif type=='input' :
            userInput=mc.promptDialog( title=title, message=msg, text=defaultInput, \
                button=['OK', 'Cancel'], defaultButton='OK', cancelButton='Cancel', dismissString='Cancel' )
            if userInput=='OK' :
                userInput=str(mc.promptDialog( query=True, text=True ))
            else :
                userInput=''
    
    #  Nuke Window :
    elif app=='Nuke' :
        import nuke
        if type=='ok' :
            userInput=nuke.message( msg )
        elif type=='okCancel' :
            userInput=nuke.ask( msg )
            if userInput :
                userInput='OK'
            else :
                userInput='Cancel'
        elif type=='input' :
            userInput=nuke.getInput( msg, defaultInput )
    
    #  Hiero Window :
    elif app=='Hiero' :
        import hiero.ui
        from hiero.core import log
        if type=='ok' :
            dialog=QtGui.QMessageBox.information( hiero.ui.mainWindow(), title, msg, \
                QtGui.QMessageBox.Ok)
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
        elif type=='okCancel' :
            dialog=QtGui.QMessageBox.question( hiero.ui.mainWindow(), title, msg, \
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok )
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
            elif dialog==QtGui.QMessageBox.Cancel :
                userInput='Cancel'
        elif type=='input' :
            dialog=QtGui.QInputDialog.getText( QtGui.QInputDialog(), title, msg, \
                QtGui.QLineEdit.Normal )
            if dialog[1] :
                userInput=dialog[0]
            else :
                userInput=None
    
    #  C4D Window :
    elif app=='C4D' :
        import c4d
        from c4d import gui
        if type=='ok' :
            userInput=gui.MessageDialog( msg )
        elif type=='okCancel' :
            userInput=gui.QuestionDialog( text=msg )
            if userInput : userInput='OK'
        elif type=='input' :
            userInput=gui.InputDialog( msg )
    
    #  3dsMax :
    elif app=='3dsMax' :
        import MaxPlus
        #maxWin=MaxPlus.Win32_GetMAXHWnd()

        if type=='ok' :
            dialog=QtGui.QMessageBox.information( None, title, msg, \
                QtGui.QMessageBox.Ok)
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
        elif type=='okCancel' :
            dialog=QtGui.QMessageBox.question( None, title, msg, \
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok )
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
            elif dialog==QtGui.QMessageBox.Cancel :
                userInput='Cancel'
        elif type=='input' :
            dialog=QtGui.QInputDialog.getText( QtGui.QInputDialog(), title, msg, \
                QtGui.QLineEdit.Normal )
            if dialog[1] :
                userInput=dialog[0]
            else :
                userInput=None

    #  Houdini :
    elif app=='Houdini' :
        import hou
        if type=='ok' :
            dialog=QtGui.QMessageBox.information( None, title, msg, \
                QtGui.QMessageBox.Ok)
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
        elif type=='okCancel' :
            dialog=QtGui.QMessageBox.question( None, title, msg, \
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok )
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
            elif dialog==QtGui.QMessageBox.Cancel :
                userInput='Cancel'
        elif type=='input' :
            inputFont = QtGui2.QFont()
            inputFont.setFamily("Ariel")
            inputFont.setPointSize(20)
            inputDialog = QtGui.QInputDialog(None)
            inputDialog.setStyleSheet( "* {background-color: #333333; color: white;}" );
            inputDialog.setInputMode(QtGui.QInputDialog.TextInput)
            inputDialog.setWindowTitle(title)
            inputDialog.setLabelText(msg)
            inputDialog.setFont(inputFont)
            ok = inputDialog.exec_()
            if(ok):
                userInput = inputDialog.textValue()
            else :
                userInput = None

    #  Flame :
    elif app=='Flame' :
        if type=='ok' :
            dialog=QtGui.QMessageBox.information( None, title, msg, \
                QtGui.QMessageBox.Ok)
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
        elif type=='okCancel' :
            dialog=QtGui.QMessageBox.question( None, title, msg, \
                QtGui.QMessageBox.Cancel, QtGui.QMessageBox.Ok )
            if dialog==QtGui.QMessageBox.Ok :
                userInput='OK'
            elif dialog==QtGui.QMessageBox.Cancel :
                userInput='Cancel'
        elif type=='input' :
            dialog=QtGui.QInputDialog.getText( QtGui.QInputDialog(), title, msg, \
                QtGui.QLineEdit.Normal )
            if dialog[1] :
                userInput=dialog[0]
            else :
                userInput=None

    #P.info('Returning PopUP INFO: %s' % userInput)
    return userInput
def main():
    #Get Active Document
    ActiveDocument = documents.GetActiveDocument()

    #Get Document Path & Name
    increment = 0
    DocPathBase = ActiveDocument.GetDocumentPath()
    DocName = ActiveDocument.GetDocumentName()
    DocNameLength = len(DocName) - 4
    DocNameShort = DocName[0:DocNameLength]
    DocPathBase += "\\" + "Render" + "\\" + DocNameShort + "_"
    DocPath = DocPathBase + str(increment)

    fps = doc.GetFps()

    ###
    helpMessage = """Enter the first frame, enter the second frame. (There is an extra pop up window for the first and last frame, respectively.)

Now the Script will run and automatically set your 'Setting, Frame-Range' to 'Current Frame'.

Sets yor 'Preferences, Texture Paths' to your working Directory (The Directory of your current C4D working File).

Checks if a 'Render' Folder exists in the same Directory, and creates it if necessary.

Checks if a Folder inside 'Render' with the name of your current C4D File exists and then create an incremented Folder.

Saves a new C4D File inside this Folder for every Frame."""
    ###

    #Get User Framerange input
    startFrameIn = c4d.gui.InputDialog("Enter Start Frame - or type 'help'")
    if startFrameIn.lower() == "help":
        c4d.gui.MessageDialog(helpMessage)
    endFrameIn = c4d.gui.InputDialog("Enter End Frame - or type 'help'")
    if endFrameIn.lower() == "help":
        c4d.gui.MessageDialog(helpMessage)

    #Check User Input
    if not startFrameIn or not endFrameIn:  #Is there any User Onput?
        c4d.gui.MessageDialog(
            "No valid Framerange was given. Script cancelled without Effect.")
        return
    else:  #if there is User Input
        try:  #Is the User Input an Integer?
            startFrame = int(startFrameIn)
            endFrame = int(endFrameIn)
        except ValueError:
            c4d.gui.MessageDialog(
                "Only Integer values allowed. Script cancelled without Effect."
            )
            return

    setTexturesPaths()

    setCurrentFrame()  #Rendersettings current Frame

    fps = doc[c4d.DOCUMENT_FPS]
    frame = startFrame
    Time = c4d.BaseTime(frame, fps)
    doc.SetTime(Time)
    c4d.EventAdd()
    rDat = doc.GetActiveRenderData()
    octane = rDat.GetFirstVideoPost()
    rDatIncr = rDat[c4d.RDATA_PATH]

    try:  #If the user didn't choose the Octane Renderer, python can't find this setting
        rOctIncr = octane[c4d.SET_PASSES_SAVEPATH]
    except TypeError:
        rOctIncr = None
        print("Octane Renderer not selected")

    rvalue = True
    folderExists = False

    if not os.path.exists(DocPath):
        os.makedirs(DocPath)
    else:
        while not folderExists:  # if the folder already exists, increment and create a new one
            increment += 1
            DocPath = DocPathBase + str(increment)
            if not os.path.exists(DocPath):
                os.makedirs(DocPath)
                folderExists = True
            if increment > 500:  #To prevent infinite loop if something goes wrong
                rvalue = gui.QuestionDialog(
                    "A Folder with the name " + DocName +
                    " already exists. Overwirte frames with the same name? This message appears, if more than 500 Folder exist inside the Render Folder."
                )
                break

    if rvalue:
        if startFrame <= endFrame:  # Loop from StartFrame to EndFrame
            for curFrame in xrange(startFrame, endFrame + 1):
                CreateC4DDocs(DocPath, DocNameShort, curFrame, rDat, rDatIncr,
                              rOctIncr, octane)
        else:  # Loop from EndFrame to StartFrame
            for curFrame in xrange(startFrame, endFrame - 1, -1):
                CreateC4DDocs(DocPath, DocNameShort, curFrame, rDat, rDatIncr,
                              rOctIncr, octane, False)
        rDat[
            c4d.
            RDATA_PATH] = rDatIncr  # After the loop, reset the Save File Name back to the original value, for the original C4D File
    else:
        exit = gui.MessageDialog(
            "Please save the project with a different name, or choose a new frame range"
        )