Пример #1
0
    def slice(cls, camera, slices_in_x, slices_in_y):
        """slices all renderable cameras
        """
        # set render resolution
        # self.unslice_scene()
        # self.is_sliced = True
        # self._store_data()

        sx = slices_in_x
        sy = slices_in_y

        # set render resolution
        # use the camera for that

        h_res = camera.evalParm("resx")
        v_res = camera.evalParm("resy")

        # this system only works when the
        camera.setParms({
            "resx": int(h_res / float(sx)),
            "resy": int(v_res / float(sy)),
            "aspect": 1
        })

        camera.setParms({
            'winsizex': 1.0 / float(sx),
            'winsizey': 1.0 / float(sx),
        })

        t = 0
        for i in range(sy):
            v_pan = 1.0 / (2.0 * sy) * (1 + 2 * i - sy)
            for j in range(sx):
                h_pan = 1.0 / (2.0 * sx) * (1 + 2 * j - sx)

                winx_parm = camera.parm("winx")
                winy_parm = camera.parm("winy")

                keyframe = hou.Keyframe()
                keyframe.setFrame(t)  # or myKey.setTime()
                keyframe.setValue(h_pan)
                winx_parm.setKeyframe(keyframe)

                keyframe = hou.Keyframe()
                keyframe.setFrame(t)  # or myKey.setTime()
                keyframe.setValue(v_pan)
                winy_parm.setKeyframe(keyframe)

                t += 1
Пример #2
0
    def _load_euler_quat(self, valParm, rOrd):
        self.type = ChTypes.QUATERNION

        frames = []
        for i in xrange(0, self.size):
            for k in valParm[i].keyframes():
                frames.append(k.frame())

        frames = sorted(set(frames))

        components = []
        self.size = 4
        for i in xrange(0, self.size):
            components.append(Component())

        for frame in frames:
            v = [valParm[i].evalAtFrame(frame) for i in xrange(0, 3)]
            q = hou.Quaternion()
            q.setToEulerRotates(v, rOrd)

            for i in xrange(0, 4):
                c = components[i]
                kq = hou.Keyframe()
                kq.setFrame(frame)
                kq.setValue(q[i])
                kq.setExpression("qlinear()", hou.exprLanguage.Hscript)
                c.keyframes.append(Component.Keyframe(kq))

        self._set_components(components)
Пример #3
0
    def set_world_space_rotation_and_translation_at_time(
            node_obj, time, rotation, translation):
        q = hou.Quaternion()
        q[0] = rotation[0]
        q[1] = rotation[1]
        q[2] = rotation[2]
        q[3] = rotation[3]

        m3 = q.extractRotationMatrix3()
        m4 = hou.Matrix4()

        for r in range(3):
            for c in range(3):
                m4.setAt(r, c, m3.at(r, c))

        m4.setAt(3, 0, translation[0])
        m4.setAt(3, 1, translation[1])
        m4.setAt(3, 2, translation[2])

        node_obj.setWorldTransform(m4)

        parms = ["tx", "ty", "tz", "rx", "ry", "rz"]
        for p in parms:
            parm = node_obj.parm(p)
            v = parm.eval()

            k = hou.Keyframe()
            k.setFrame(time)
            k.setValue(v)
            parm.setKeyframe(k)
Пример #4
0
def bakeObjectToWorld(startFrame, endFrame):
    selectedNode = hou.selectedNodes()
    selectedNodeName = selectedNode[0].name()
    parent = selectedNode[0].parent()
    bakeNode = hou.copyNodesTo(selectedNode, parent)
    bakeNode[0].setName(selectedNodeName + "_bake")
    bakeNode[0].parm("keeppos").set(0)
    fetchNode = hou.node(parent.path()).createNode("fetch",
                                                   "fetch_" + selectedNodeName)
    hou.node(fetchNode.path()).parm("fetchobjpath").set(selectedNode[0].path())
    hou.node(fetchNode.path()).parm("useinputoffetched").set(1)
    nullNode = hou.node(parent.path()).createNode("null")
    nullNode.setFirstInput(fetchNode)
    nullNodeName = nullNode.name()

    parms = ["tx", "ty", "tz", "rx", "ry", "rz"]
    constant = ["TX", "TY", "TZ", "RX", "RY", "RZ"]

    bakeNode[0].setInput(0, None)

    #delete expresssion in parms and set to 0
    for p in parms:
        bakeNode[0].parm(p).deleteAllKeyframes()
        hou.hscript('objextractpretransform ' + bakeNode[0].path())
        bakeNode[0].parm(p).set(0)

    for p, c in zip(parms, constant):
        #bakeNode[0].parm(p).deleteAllKeyframes()
        hou.node(bakeNode[0].path()).parm(p).setExpression('origin("","../' +
                                                           nullNodeName +
                                                           '",' + c + ')')

    #add dict for hou.Keyframe and values
    key = dict([(x, hou.Keyframe()) for x in parms])
    values = dict([(x, []) for x in constant])

    #bake time range
    timeRange = xrange(startFrame, endFrame + 1)

    #fill values dict
    for t in timeRange:
        hou.setFrame(t)
        for v, p in zip(constant, parms):
            values[v].append(bakeNode[0].parm(p).eval())

    for p in parms:
        bakeNode[0].parm(p).deleteAllKeyframes()
        bakeNode[0].parm(p).set(0)

    #set key by keyframes

    for t in timeRange:
        hou.setFrame(t)
        for v, p, k in zip(constant, parms, key):
            key[k].setValue(values[v][t - startFrame])
            bakeNode[0].parm(p).setKeyframe(key[k])

    fetchNode.destroy()
    nullNode.destroy()
Пример #5
0
def bake_values(start, end, parm, values):
    for frame in range(start, end):
        keyframe = hou.Keyframe()
        keyframe.setValue(values[frame - start])
        keyframe.setFrame(frame)
        keyframe.setExpression('spline()')

        parm.setKeyframe(keyframe)
Пример #6
0
 def set_channel_key_frames_in_bulk(k_channel_obj, times, values):
     keys = []
     for i in range(len(times)):
         k = hou.Keyframe()
         k.setFrame(times[i])
         k.setValue(values[i])
         keys.append(k)
     k_channel_obj.setKeyframes(keys)
Пример #7
0
def bakeTranslation(pathToSource, pathToDest, startSampleFrame, endSampleFrame,
                    stepFrame):
    #sample chop:
    frameValList = []
    for frame in range(startSampleFrame, endSampleFrame, stepFrame):
        hexprTX = 'chf(\"' + pathToSource + '\"/tx,' + str(frame) + ')'
        hexprTY = 'chf(\"' + pathToSource + '\"/ty,' + str(frame) + ')'
        hexprTZ = 'chf(\"' + pathToSource + '\"/tz,' + str(frame) + ')'
        retvalTX = hou.hscriptExpression(hexprTX)
        retvalTY = hou.hscriptExpression(hexprTY)
        retvalTZ = hou.hscriptExpression(hexprTZ)
        valTX = float(retvalTX)
        valTY = float(retvalTY)
        valTZ = float(retvalTZ)
        frameValList.append((frame, (valTX, valTY, valTZ)))
    #make keys:
    pathToDestTX = pathToDest + "/tx"
    pathToDestTY = pathToDest + "/ty"
    pathToDestTZ = pathToDest + "/tz"

    parmTX = hou.parm(pathToDestTX)
    parmTX.deleteAllKeyframes()

    parmTY = hou.parm(pathToDestTY)
    parmTY.deleteAllKeyframes()

    parmTZ = hou.parm(pathToDestTZ)
    parmTZ.deleteAllKeyframes()

    keyList = []
    for frameVal in frameValList:
        key = hou.Keyframe()
        key.setFrame(frameVal[0])
        key.setValue(frameVal[1][0])
        parmTX.setKeyframe(key)

        key = hou.Keyframe()
        key.setFrame(frameVal[0])
        key.setValue(frameVal[1][1])
        parmTY.setKeyframe(key)

        key = hou.Keyframe()
        key.setFrame(frameVal[0])
        key.setValue(frameVal[1][2])
        parmTZ.setKeyframe(key)
    def setKframePref(self):
        self.hou_keyframe = hou.Keyframe()
        self.hou_keyframe.setSlope(0)
        self.hou_keyframe.setInSlope(0)

        self.hou_keyframe.setAccel(1)
        self.hou_keyframe.setInAccel(1)
        self.hou_keyframe.interpretAccelAsRatio(False)
        self.hou_keyframe.setExpression("bezier()", hou.exprLanguage.Hscript)
Пример #9
0
 def set_channel_key_frame(k_channel_obj, time, value):
     k = hou.Keyframe()
     k.setFrame(time)
     k.setValue(value)
     k_channel_obj.setKeyframe(k)
     keys = k_channel_obj.keyframes()
     for i in range(len(keys)):
         if keys[i].frame() == time:
             return i
Пример #10
0
def processMesh(nodes, nodePieces, numPieces):
    PARMS = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'px', 'py', 'pz']
    RFSTART = int(hou.expandString('$RFSTART'))
    RFEND = int(hou.expandString('$RFEND'))

    for frame in range(RFSTART, RFEND + 1):
        hou.setFrame(frame)
        print 'Processing Frame: {}'.format(frame)

        for objectToProcess in range(0, len(numPieces)):
            #If at the creation frame, skip keyframe
            if frame == nodes[objectToProcess].parm('createframe').eval():
                continue

            for index in range(0, numPieces[objectToProcess]):
                for index_parm in range(0, 3):
                    hou_keyed_parm = nodePieces[objectToProcess][index].parm(
                        PARMS[index_parm])
                    hou_keyframe = hou.Keyframe()
                    hou_keyframe.setFrame(frame)
                    hou_keyframe.setValue(
                        nodes[objectToProcess].simulation().findObject(
                            nodes[objectToProcess].name()).geometry(
                            ).iterPoints()[index].attribValue('P')[index_parm])
                    hou_keyed_parm.setKeyframe(hou_keyframe)

                for index_parm in range(0, 3):
                    hou_keyed_parm = nodePieces[objectToProcess][index].parm(
                        PARMS[index_parm + 3])
                    hou_keyframe = hou.Keyframe()
                    hou_keyframe.setFrame(frame)
                    hou_keyframe.setValue(
                        hou.Quaternion(
                            nodes[objectToProcess].simulation().findObject(
                                nodes[objectToProcess].name()).geometry().
                            iterPoints()[index].attribValue(
                                'orient')).extractEulerRotates()[index_parm])
                    hou_keyed_parm.setKeyframe(hou_keyframe)

    print 'Processing Complete!'
Пример #11
0
def make_bbox(node, enable_expr_links):
    '''
    Create a box sop with dimensions mathcing the bounding box of the input node
    enable_expr_links will toggle between hardcoded values or relative references of the bounding box dimensions
    '''
    bb = node.parent().createNode('box', 'bbox1', run_init_scripts=True, load_contents=True, exact_type_name=True)
    bb.setPosition(node.position())
    #bb.moveToGoodPosition()
    bb.move(hou.Vector2(1, -1))

    if enable_expr_links == 0:
        bbox_scale = node.geometry().boundingBox().sizevec()
        bbox_center = node.geometry().boundingBox().center()
        for i in range(3):
            bb.parmTuple('size')[i].set(bbox_scale[i])
        for i in range(3):
            bb.parmTuple('t')[i].set(bbox_center[i])
    
    if enable_expr_links == 1:
        for i in range(3):
            expr_keyframe = hou.Keyframe()
            expr_keyframe.setTime(0)
            component = ''
            if i == 1:
                component = 'D_YSIZE'
            elif i == 2:
                component = 'D_ZSIZE'
            else:
                component = 'D_XSIZE'
            expr_keyframe.setExpression("bbox('" + bb.relativePathTo(node) + "'," + component + ")", hou.exprLanguage.Hscript)
            bb.parmTuple('size')[i].setKeyframe(expr_keyframe)
        for i in range(3):
            expr_keyframe = hou.Keyframe()
            expr_keyframe.setTime(0)
            expr_keyframe.setExpression("centroid('" + bb.relativePathTo(node) + "'," + str(i) + ")", hou.exprLanguage.Hscript)
            bb.parmTuple('t')[i].setKeyframe(expr_keyframe)
    
    bb.parm('vertexnormals').set(True)
Пример #12
0
def yoga_save_pose() :
    # parm_store.deleteAllKeyframes()
    node_edit  = hou.node("/obj/edit")
    node_store = hou.node("/obj/store")
    parms      = node_edit.parms()

    for parm in parms :
        name       = parm.name()
        parm_store = node_store.parm(name)

        if len(parm_store.keyframes()) > 0 :
            value      = parm.eval()
            key        = hou.Keyframe(value)
            parm_store.setKeyframe(key)
Пример #13
0
    def endElement(self, _name):
        # extract the m_meshName and save it
        if _name == "MeshName":
            self.m_meshName = self.m_charData
        # get the number of vertices and set this to the channel
        elif _name == "NumVerts":
            # store value
            self.m_numVerts = int(self.m_charData)

            # now set the Channel to have this number of channels (may be large)
            self.m_channel.parm("numchannels").set(self.m_numVerts)
            # now we traverse all the elements and re-size to 3 and rename the data to a translate
            # we need to change this later for other attribute types (rot etc etc)
            for i in range(0, self.m_numVerts):
                channel.parm("size%d" % (i)).set(3)
                channel.parm("name%d" % (i)).set("t")
        # parse and sel the m_startFrame
        elif _name == "StartFrame":
            self.m_startFrame = int(self.m_charData)
            self.m_channel.parm("start").set(self.m_startFrame)
        ## found an end frame value
        elif _name == "EndFrame":
            self.m_endFrame = int(self.m_charData)
            self.m_channel.parm("end").set(self.m_endFrame)
        ## found the number of frames
        elif _name == "NumFrames":
            self.m_numFrames = int(self.m_charData)
        ## found the vertex
        elif _name == "Vertex":
            hou.ui.setStatusMessage(
                "Processing Frame %d channel %d" %
                (self.m_currentFrame, self.m_offset), hou.severityType.Message)
            self.m_charData = self.m_charData.strip()
            data = self.m_charData.split(" ")
            ## now we check to see if there are enough values to parse
            if len(data) == 3:
                hou_parm_tuple = self.m_channel.parmTuple("value%d" %
                                                          (self.m_offset))
                hou_keyframe = hou.Keyframe()
                hou_keyframe.setExpression(str(data[0]),
                                           hou.exprLanguage.Hscript)
                hou_parm_tuple[0].setKeyframe(hou_keyframe)
                hou_keyframe.setExpression(str(data[1]),
                                           hou.exprLanguage.Hscript)
                hou_parm_tuple[1].setKeyframe(hou_keyframe)
                hou_keyframe.setExpression(str(data[2]),
                                           hou.exprLanguage.Hscript)
                hou_parm_tuple[2].setKeyframe(hou_keyframe)
Пример #14
0
def importTransformFromClipboard(_o):
    error_count = 0
    is_tuple = False
    clipboard = QtWidgets.QApplication.clipboard()
    text = clipboard.text()
    lines = text.splitlines()

    if lines[0].startswith('#copytransform'):
        ls = lines[0].split(',', 2)
        fps = ls[1]
        range = ls[2]

        if fps != str(hou.fps()):
            print('warning: fps differs from export')
        if range != str(hou.playbar.timelineRange()):
            print('warning: animation range differs from export')

        for p in (_o.parms()):
            p.deleteAllKeyframes()

        for line in lines[1:]:
            ls = line.split(',', 1)
            if len(ls) == 2:
                parm_name = ls[0]
                parm_val = eval(ls[1])
                is_tuple = isinstance(parm_val, tuple)
                try:
                    if is_tuple:
                        for k in parm_val:
                            setKey = hou.Keyframe()
                            setKey.setFrame(k[0])
                            setKey.setValue(k[1])
                            _o.parm(parm_name).setKeyframe(setKey)
                    else:
                        _o.parm(parm_name).set(parm_val)

                except:
                    print('cannot setting parameter: ' + ls[0])
                    error_count += 1

        if error_count > 0:
            print('transform values imported with: ' + str(error_count) + ' errors')
        else:
            print('all transform values successfully imported')
    else:
        print('cannot apply clipboad values, wrong type!')
    def bakeCamAnim(self, node, frameRange):
        ''' Bake camera to World Space '''
        if 'cam' in node.type().name():
            bkNd = hou.node('/obj').createNode(
                'cam', '%s_bake' % node.name())

            for x in ['resx', 'resy']:
                bkNd.parm(x).set(node.parm(x).eval())

        for frame in xrange(int(frameRange[0]), (int(frameRange[1]) + 1)):
            time = (frame - 1) / hou.fps()
            tsrMtx = node.worldTransformAtTime(time).explode()

            for parm in tsrMtx:
                if 'shear' not in parm:
                    for x, p in enumerate(bkNd.parmTuple(parm[0])):
                        p.setKeyframe(hou.Keyframe(tsrMtx[parm][x], time))

        return bkNd
Пример #16
0
def bakeChop(pathToChop, pathToParm, startSampleFrame, endSampleFrame,
             stepFrame):
    #sample chop:
    frameValList = []
    for frame in range(startSampleFrame, endSampleFrame, stepFrame):
        hexpr = 'chopf(\"' + pathToChop + '\",' + str(frame) + ')'
        retval = hou.hscriptExpression(hexpr)
        val = float(retval)
        frameValList.append((frame, val))
    #make keys:
    parm = hou.parm(pathToParm)
    parm.deleteAllKeyframes()

    keyList = []
    for frameVal in frameValList:
        key = hou.Keyframe()
        key.setFrame(frameVal[0])
        key.setValue(frameVal[1])
        parm.setKeyframe(key)
Пример #17
0
def keyParmTuple(tup, frame, value=None, onlykeyed=False):
    """Set keys on all parms within a given parm tuple."""

    is_string = isinstance(tup.parmTemplate(), hou.StringParmTemplate)

    # Removing support for string parms temporarily until everything else is locked down
    if is_string:
        return

    with hou.undos.group("Key ParmTuple"):

        if not isinstance(value, tuple):
            value = (value, ) * len(tup)

        for idx, p in enumerate(tup):
            if onlykeyed and not p.keyframes():
                continue

            if is_string:
                key = hou.StringKeyframe()
            else:
                key = hou.Keyframe()

            if len(value) > idx and value[idx] is not None:
                if is_string:
                    key.setExpression(value[idx])
                else:
                    key.setValue(value[idx])
            else:
                if is_string:
                    key.setExpression(p.evalAtFrame(frame))
                else:
                    key.setValue(p.evalAtFrame(frame))

            key.setFrame(frame)

            if not is_string:
                key.setInSlopeAuto(True)
                key.setSlopeAuto(True)
            p.setKeyframe(key)

    return key
Пример #18
0
 def setBetweenKey(self):
     """Set a new key with the new value."""
     controls = hou.selectedNodes()  #initiate currently selected objects
     with hou.undos.group("Set Between Key"
                          ):  #record changes as single action for one undo
         for control in controls:  #iterate between selected objects
             for parm in control.parms(
             ):  #for every object iterate between its parameters
                 parm = parm.getReferencedParm()
                 if len(parm.keyframes()) > 0 and type(
                         parm.eval()
                 ) == float:  #if parameter is animated and its type is float
                     currentFrame = hou.frame()  #get current frame number
                     key = hou.Keyframe()  #instantiate new keyframe object
                     key.setFrame(currentFrame)  #set frame for the new key
                     key.setValue(self.getBetweenKeyValue(
                         parm))  #set value for the new key
                     key.setSlopeAuto(True)
                     key.setInSlopeAuto(True)
                     parm.setKeyframe(key)  #set the new key on timeline
Пример #19
0
    def convertKeys(self, key, param, exp_type):
        """Convert keyframe type.
        
        INPUTS:
        key -- current key
        param -- parameter to set a new keyframe on
        type -- new keyframe type

        OUTPUTS:
        newKey -- converted key
        """
        newKey = hou.Keyframe()  #instantiate new keyframe object
        newKey.setFrame(key.frame())  #set frame for the new key
        newKey.setValue(key.value())
        newKey.setExpression(exp_type + "()")  #set key interpolation
        newKey.setSlopeAuto(True)
        newKey.setInSlopeAuto(True)
        param = param.getReferencedParm()
        param.setKeyframe(newKey)
        return newKey
def processSkeleton(clothNode, boneList):
    PARMS   =   ["tx", "ty", "tz"]
    RFSTART = int(hou.expandString('$RFSTART'))
    RFEND = int(hou.expandString('$RFEND'))

    for frame in range(RFSTART, RFEND+1):
        hou.setFrame(frame)
        print 'Processing Frame: {}'.format(frame)

        for idx, bone in enumerate(boneList):
            for indexParm in range(0,3):
                hou_keyed_parm = bone.parm(PARMS[indexParm])
                hou_keyframe = hou.Keyframe()
                hou_keyframe.setFrame(frame)
                hou_keyframe.setValue(clothNode.geometry().iterPoints()[idx].attribValue('P')[indexParm])
                hou_keyed_parm.setKeyframe(hou_keyframe)

    hou.setFrame(RFSTART)

    print "Processing Complete!"
Пример #21
0
    def create_hda(subnet, hda_name='default'):
        tmp = subnet.createDigitalAsset(name=hda_name, description=hda_name)
        parent = tmp.parent()
        tmp.destroy()

        hda_instance = parent.createNode(hda_name, hda_name)
        source_tuple = hda_instance.parmTuple('./xform/r')
        definition = hda_instance.type().definition()
        definition.addParmTuple(source_tuple.parmTemplate())
        target_tuple = hda_instance.parmTuple('r')

        hda_instance.allowEditingOfContents()
        source_tuple.set(target_tuple)
        definition.updateFromNode(hda_instance)

        keyframe = hou.Keyframe()
        keyframe.setExpression('$FF', hou.exprLanguage.Hscript)
        target_tuple[0].setKeyframe(keyframe)
        target_tuple[1].setKeyframe(keyframe)
        target_tuple[2].setKeyframe(keyframe)
        hda_instance.matchCurrentDefinition()
        return hda_instance
Пример #22
0
 def copyKeyframe(self, frame_step):
     """Copy all current keyframes on all selected objects to a specified frame.
     
     INPUTS:
     frame_step -- frame interval
     """
     current_frame = hou.frame()
     nodes = hou.selectedNodes()
     with hou.undos.group("Copy Keys"):
         for node in nodes:
             for parm in node.parms():
                 parm = parm.getReferencedParm()
                 if parm.keyframesBefore(current_frame) != (
                 ) and len(parm.keyframes()) > 0 and type(
                         parm.eval()) == float and parm.isLocked() == False:
                     new_key = hou.Keyframe()
                     new_key.setValue(parm.eval())
                     new_key.setSlopeAuto(1)
                     new_key.setFrame(current_frame + float(frame_step))
                     parm.setKeyframe(new_key)
                 else:
                     pass
         hou.setFrame(current_frame + frame_step)
Пример #23
0
    def loadHDASets_main(self, **connections):
        try:
            nameOverride = str(connections["nameOverride"])
        except:
            nameOverride = ""
        try:
            dbPath = connections["dbPath"]
        except:
            dbPath = ""
        try:
            Name = str(connections["Name"])
        except:
            Name = ""
        try:
            Type = str(connections["Type"])
        except:
            Type = ""
        try:
            Version = str(connections["Version"])
        except:
            Version = ""
        try:
            oas_output = connections["oas_output"]
        except:
            oas_output = "version"

        if str(geT(dbPath)) == "" or str(geT(dbPath)) == "0":
            return 0

        if Type == "Model":
            return LHD(Name, Type, Version, dbPath, nameOverride)
        elif Type == "Engine":
            return LHD(Name, Type, Version, dbPath, nameOverride)
            #hou.node("/obj/"+nameOverride).setDisplayFlag(False)
            #hou.node("/obj/"+nameOverride).setDisplayFlag(True)
        elif Type == "Setup":
            ret = LHD(Name, "Model", "latest", dbPath, Name + "_Model")
            try:
                ret2 = LHD(Name, "Deform", "latest", dbPath, Name + "_Deform")
            except:
                pass
            return LHD(Name, Type, Version, dbPath, Name + "_Setup")
        elif Type == "Material":
            hou.hipFile.clear()
            ret1 = LHD(Name, "Model", "latest", dbPath, Name + "_Model")
            par = hou.node("/obj/" + Name + "_Model").parm("ry")
            coll = ""
            for item in hou.node("/obj/" + Name + "_Model").children():
                coll += str(item.path()) + " "

            for item in hou.node("/obj/" + Name + "_Model").parmsInFolder(
                ("Materials", )):
                try:
                    item.set("/obj/" + Name + "_Material/" +
                             str(item.name().split("_shop")[0]) + "/out")
                except:
                    pass
            hou.setFrame(1)
            par.setKeyframe(hou.Keyframe(0))
            hou.setFrame(101)
            par.setKeyframe(hou.Keyframe(360))
            hou.setFrame(1)
            ret2 = LHD("LookdevLightRig", "Lightrig", "latest",
                       ":General:Assets:LightSetups:LookdevLightRig",
                       "Lookdev_Lightrig")
            hou.node("/obj/" + "Lookdev_Lightrig").parm("models").set(coll)
            ret3 = LHD("LookdevLightRig", "RenderSetup", "latest",
                       ":General:Assets:LightSetups:LookdevLightRig",
                       "Lookdev_RenderSetup")
            ret4 = LHD("autoscaleCamera", "Camera", "latest",
                       ":General:Assets:CameraSetups:autoscaleCamera",
                       "Lookdev_LookdevCamera")
            hou.node("/obj/" +
                     "Lookdev_LookdevCamera").parm("models").set(coll)
            return LHD(Name, Type, Version, dbPath, Name + "_Material")
        elif Type == "everything":
            ret = LHD(Name, "Model", "latest", dbPath, Name + "_Model")
            hou.node("/obj/" + Name + "_Model").setDisplayFlag(False)
            hou.node("/obj/" + Name + "_Model").matchCurrentDefinition()
            LHD(Name, "Setup", "latest", dbPath, Name + "_Setup")
            hou.node("/obj/" + Name + "_Setup").setDisplayFlag(False)
            hou.node("/obj/" + Name + "_Setup").matchCurrentDefinition()
            for item in hou.node("/obj/" + Name + "_Model").parmsInFolder(
                ("Materials", )):
                try:
                    item.set("/obj/" + Name + "_Material/" +
                             str(item.name().split("_shop")[0]) + "/out")
                except:
                    pass
            try:
                ret2 = LHD(Name, "Deform", "latest", dbPath, Name + "_Deform")
                hou.node("/obj/" + Name + "_Deform").matchCurrentDefinition()
                hou.node("/obj/" + Name + "_Deform").setDisplayFlag(False)
            except:
                pass

            LHD(Name, "Material", "latest", dbPath, Name + "_Material")
            hou.node("/obj/" + Name + "_Material").matchCurrentDefinition()
            hou.node("/obj/" + Name + "_Material").setDisplayFlag(False)
            return "latest"
Пример #24
0
mathNode.parm('chopop').set(1)
mathNode.setInput(0, channel)
mathNode.setInput(1, noise)

# 02
limit = chop.createNode('limit')
limit.parm('type').set(1)
limit.parm('min').set(0)
limit.parm('max').set(5)
limit.setInput(0, mathNode)
limit.setDisplayFlag(True)
limit.setExportFlag(True)

# 03
frameRange = hou.playbar.frameRange()
key = hou.Keyframe()
key.setFrame(frameRange[0])
key.setValue(0)

noise_amp = noise.parm('amp')
noise_amp.setKeyframe(key)
key.setFrame(frameRange[1])
key.setValue(1)
noise_amp.setKeyframe(key)

# 04
scene = toolutils.sceneViewer()
# ビューアの現行Flipbook設定をコピーします。
flipbook_options = scene.flipbookSettings().stash()

# 必要に応じて設定を変更します
def createMutagenSetup():

    #topnet_glob
    hou_parent = hou.node("obj/")
    hou_node = hou_parent.createNode("topnet", "topnet_glob")
    topnet_name = hou_node.name()
    topnet_path = hou_node.path()

    hou_parm = hou_node.parm("topscheduler")
    hou_parm.set("localscheduler")
    hou_parent = hou_node

    #topnet_glob/localscheduler
    hou_node = hou_parent.node(hou_parent.path() + "/localscheduler")
    hou_node.move(hou.Vector2(0, 6))

    #topnet_glob/CTRL_WEDGES
    hou_node = hou_parent.createNode("null", "CTRL_WEDGES")
    hou_node.move(hou.Vector2(0, 4))
    hou_node.setColor(hou.Color([0, 0, 0]))
    hou_node.setExpressionLanguage(hou.exprLanguage.Hscript)

    hou_parm_template_group = hou.ParmTemplateGroup()
    # Code for parameter template
    hou_parm_template = hou.StringParmTemplate(
        "wedge_expr",
        "Wedge IDX Exp.Python",
        1,
        default_value=([""]),
        naming_scheme=hou.parmNamingScheme.Base1,
        string_type=hou.stringParmType.Regular,
        menu_items=([]),
        menu_labels=([]),
        icon_names=([]),
        item_generator_script="",
        item_generator_script_language=hou.scriptLanguage.Python,
        menu_type=hou.menuType.Normal)
    hou_parm_template_group.append(hou_parm_template)
    hou_node.setParmTemplateGroup(hou_parm_template_group)

    hou_parm = hou_node.parm("wedge_expr")
    hou_parm.set("")
    hou_parm.setAutoscope(True)

    hou_keyframe = hou.StringKeyframe()
    hou_keyframe.setTime(0)
    hou_keyframe.setExpression(
        "import pdg\n\nwork_item = pdg.workItem()\nwdg_idx_l = pdg.intDataArray(work_item, \"wedgenum\")\n\nwdg_idx_s = \"\"\nfor wdg_idx in wdg_idx_l:\n    wdg_idx_s += str(wdg_idx) + \"_\"\n    \nwdg_idx_s = wdg_idx_s[0:-1]\n\n\n#print wdg_idx_s\nreturn wdg_idx_s\n    \n",
        hou.exprLanguage.Python)
    hou_parm.setKeyframe(hou_keyframe)

    hou_node.setColor(hou.Color([0, 0, 0]))
    hou_node.setExpressionLanguage(hou.exprLanguage.Hscript)

    #topnet_glob/wedge_root
    hou_node = hou_parent.createNode("wedge", "wedge_root")
    hou_node.move(hou.Vector2(0, 0.42))
    hou_parm = hou_node.parm("wedgecount")
    hou_parm.set(2)
    hou_parm = hou_node.parm("seed")
    hou_parm.set(2042)
    hou_parm = hou_node.parm("preservenum")
    hou_parm.set(1)
    hou_parm = hou_node.parm("previewselection")
    hou_parm.set(1)

    #topnet_glob/wedge_var1
    hou_node = hou_parent.createNode("wedge", "wedge_var1")
    hou_node.move(hou.Vector2(0, -1.2))
    hou_parm = hou_node.parm("wedgecount")
    hou_parm.set(2)
    hou_parm = hou_node.parm("seed")
    hou_parm.set(8215)
    hou_parm = hou_node.parm("preservenum")
    hou_parm.set(1)
    hou_parm = hou_node.parm("previewselection")
    hou_parm.set(1)

    #topnet_glob/wedge_var2
    hou_node = hou_parent.createNode("wedge", "wedge_var2")
    hou_node.move(hou.Vector2(0, -2.9))
    hou_parm = hou_node.parm("wedgecount")
    hou_parm.set(2)
    hou_parm = hou_node.parm("seed")
    hou_parm.set(8215)
    hou_parm = hou_node.parm("preservenum")
    hou_parm.set(1)
    hou_parm = hou_node.parm("previewselection")
    hou_parm.set(1)

    hou_node.setColor(hou.Color([0.306, 0.306, 0.306]))

    #topnet_glob/ropfetch_geo
    hou_node = hou_parent.createNode("ropfetch", "ropfetch_geo")
    hou_node.move(hou.Vector2(0, -6.14))
    hou_parm = hou_node.parm("roppath")
    hou_parm.set(topnet_path + "/ropnet/geometry_rop")
    hou_parm = hou_node.parm("framegeneration")
    hou_parm.set("1")

    hou_parm = hou_node.parm("batchall")
    hou_parm.set(1)
    hou_node.setColor(hou.Color([1, 0.529, 0.624]))

    #topnet_glob/ropfetch_render
    hou_node = hou_parent.createNode("ropfetch", "ropfetch_render")
    hou_node.move(hou.Vector2(0, -8.64618))
    hou_parm = hou_node.parm("roppath")
    hou_parm.set(topnet_path + "/ropnet/mantra_rop")

    hou_parm = hou_node.parm("framesperbatch")
    hou_parm.set(5)
    hou_node.setColor(hou.Color([0.624, 0.329, 0.396]))

    #topnet_glob/partitionbyframe
    hou_node = hou_parent.createNode("partitionbyframe", "partitionbyframe")
    hou_node.move(hou.Vector2(0, -11.3))

    #topnet_glob/im_montage_p0
    hou_node = hou_parent.createNode("imagemagick", "im_montage_p0")
    hou_node.move(hou.Vector2(0, -14.16))
    hou_parm = hou_node.parm("overlayexpr")
    hou_parm.setAutoscope(True)
    hou_parm = hou_node.parm("usecustomcommand")
    hou_parm.set(1)
    hou_parm = hou_node.parm("customcommand")
    hou_parm.set(
        "{imagemagick} -fill grey -label '%t' -background \"rgb(20,20,20)\" -mode concatenate {input_images} -geometry 256x256+2+2 \"{output_image}\""
    )
    hou_parm = hou_node.parm("filename")
    hou_parm.set("$HIP/img/$HIPNAME/$OS/$HIPNAME.$OS.$F4.jpg")
    hou_node.setColor(hou.Color([0.451, 0.369, 0.796]))

    #topnet_glob/waitforall
    hou_node = hou_parent.createNode("waitforall", "waitforall")
    hou_node.move(hou.Vector2(0, -17.1))

    #topnet_glob/ffmpeg_montage_p0
    hou_node = hou_parent.createNode("ffmpegencodevideo", "ffmpeg_montage_p0")
    hou_node.move(hou.Vector2(0, -20.0))
    hou_parm = hou_node.parm("fps")
    hou_keyframe = hou.Keyframe()
    hou_keyframe.setTime(0)
    hou_keyframe.setExpression("$FPS", hou.exprLanguage.Hscript)
    hou_parm.setKeyframe(hou_keyframe)
    hou_parm = hou_node.parm("outputfilename")
    hou_parm.set("$HIP/img/$HIPNAME/$OS/$HIPNAME.$OS.webm")
    hou_parm = hou_node.parm("customcommand")
    hou_parm.set(1)
    hou_parm = hou_node.parm("expr")
    hou_parm.set(
        "\"{ffmpeg}\" -y -r {frames_per_sec}/1 -f concat -safe 0 -apply_trc iec61966_2_1 -i \"{frame_list_file}\" -c:v libvpx-vp9 -crf 32 -b:v 0 -vf \"fps={frames_per_sec},format=yuv420p\" -movflags faststart \"{output_file}\""
    )
    hou_parm = hou_node.parm("topscheduler")
    hou_parm.set("../localscheduler")

    hou_node.setColor(hou.Color([0.188, 0.529, 0.459]))

    hou_node.setSelected(True, clear_all_selected=True)

    #topnet_glob/ropnet
    hou_node = hou_parent.createNode("ropnet", "ropnet")
    hou_node.move(hou.Vector2(-3.29748, -7.22574))
    hou_node.setColor(hou.Color([0.996, 0.682, 0.682]))
    # Update the parent node.
    hou_parent = hou_node

    #topnet_glob/ropnet/geometry_rop
    hou_node = hou_parent.createNode("geometry", "geometry_rop")
    hou_node.move(hou.Vector2(1.4, -8.0))
    hou_parm = hou_node.parm("trange")
    hou_parm.set("normal")
    hou_parm = hou_node.parm("sopoutput")
    hou_parm.set("$HIP/geo/$HIPNAME/$OS/wdg_`chs('" + topnet_path +
                 "/CTRL_WEDGES/wedge_expr')`/wdg_`chs('" + topnet_path +
                 "/CTRL_WEDGES/wedge_expr')`.$F4.bgeo.sc")
    hou_node.setColor(hou.Color([1, 0.529, 0.624]))

    # Restore the parent and current nodes.
    hou_parent = hou_node.parent()

    #topnet_glob/ropnet/mantra_rop
    hou_node = hou_parent.createNode("ifd", "mantra_rop")
    hou_node.move(hou.Vector2(1.4, -12.5))
    hou_parm = hou_node.parm("trange")
    hou_parm.set("normal")
    hou_parm = hou_node.parm("override_camerares")
    hou_parm.set(1)
    hou_parm = hou_node.parm("res_fraction")
    hou_parm.set("specific")
    hou_parm_tuple = hou_node.parmTuple("res_override")
    hou_parm_tuple.set((512, 512))
    hou_parm = hou_node.parm("vm_picture")
    hou_parm.set("$HIP/render/$HIPNAME/$OS/wdg_`chs('" + topnet_path +
                 "/CTRL_WEDGES/wedge_expr')`/wdg_`chs('" + topnet_path +
                 "/CTRL_WEDGES/wedge_expr')`.$F4.jpg")
    hou_node.setColor(hou.Color([0.624, 0.329, 0.396]))

    # Restore the parent and current nodes.
    hou_parent = hou_node.parent().parent()

    # Code to establish connections for /obj/topnet_glob/wedge_var1
    hou_node = hou_parent.node("wedge_var1")
    hou_node.setInput(0, hou_parent.node("wedge_root"), 0)
    # Code to establish connections for /obj/topnet_glob/wedge_var2
    hou_node = hou_parent.node("wedge_var2")
    hou_node.setInput(0, hou_parent.node("wedge_var1"), 0)
    # Code to establish connections for /obj/topnet_glob/ropfetch_geo
    hou_node = hou_parent.node("ropfetch_geo")
    hou_node.setInput(0, hou_parent.node("wedge_var2"), 0)
    # Code to establish connections for /obj/topnet_glob/ropfetch_render
    hou_node = hou_parent.node("ropfetch_render")
    hou_node.setInput(0, hou_parent.node("ropfetch_geo"), 0)
    # Code to establish connections for /obj/topnet_glob/partitionbyframe
    hou_node = hou_parent.node("partitionbyframe")
    hou_node.setInput(0, hou_parent.node("ropfetch_render"), 0)
    # Code to establish connections for /obj/topnet_glob/im_montage_p0
    hou_node = hou_parent.node("im_montage_p0")
    hou_node.setInput(0, hou_parent.node("partitionbyframe"), 0)
    # Code to establish connections for /obj/topnet_glob/waitforall
    hou_node = hou_parent.node("waitforall")
    hou_node.setInput(0, hou_parent.node("im_montage_p0"), 0)
    # Code to establish connections for /obj/topnet_glob/ffmpeg_montage_p0
    hou_node = hou_parent.node("ffmpeg_montage_p0")
    hou_node.setInput(0, hou_parent.node("waitforall"), 0)

    #sticky notes

    #topnet_glob/__stickynote1
    hou_sticky = hou_parent.createStickyNote("__stickynote1")
    hou_sticky.setText(
        "Important to set Geo Ropfetch Node to 'All Frames in One Batch' for Simulations."
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0, 0, 0)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(4.3129, -6.62927))
    hou_sticky.setSize(hou.Vector2(8.17024, 0.922362))
    hou_sticky.setColor(hou.Color([1, 0.529, 0.624]))

    #topnet_glob/__stickynote2
    hou_sticky = hou_parent.createStickyNote("__stickynote2")
    hou_sticky.setText(
        "The 'Preserve Wedge Numbers' option is important to be turned on.\nThis will append each @wedgenum in an array and allow for explicit mapping.\n\n'Overwrite Target Parm on Item Selection' (Push Refrences) is optional, but very convinient with the Mutagen Setup opposed to \"Pull References\".\n\nAdd as many Wedges as you like.\n\nUse the Shelf Tool 'Convert Takes to Wedge' from the 'PDG Mutagen' Shelf to convert variations you have set up in the \"classical Take style\" to a single Wedge TOP that holds all the edited parameters. The Takes will be redundant from then\nAppend additional Wedge TOPs as you like to generate further variation.\n"
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0, 0, 0)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(4.31289, -3.24063))
    hou_sticky.setSize(hou.Vector2(8.17024, 3.99192))
    hou_sticky.setColor(hou.Color([0.6, 0.6, 0.6]))

    #topnet_glob/__stickynote3
    hou_sticky = hou_parent.createStickyNote("__stickynote3")
    hou_sticky.setText(
        "You can add a explicit tiling varibale like: \"-tile 8x8\" or \"-tile 12x\"\nThat would give 8x8 Tiles or 12 Tiles in X and Y calculated automatically.\nChange style variables as you like.\n\nChangeOutput  'Filename' as you like.\n\nIf you inserted a \"Split\" to split up the whole setup in 2 or more  seperate Contact Sheets, use _p0, _p1, ... nodename postfix."
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0, 0, 0)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(4.31289, -15.8599))
    hou_sticky.setSize(hou.Vector2(8.17024, 2.7729))
    hou_sticky.setColor(hou.Color([0.451, 0.369, 0.796]))

    #topnet_glob/__stickynote4
    hou_sticky = hou_parent.createStickyNote("__stickynote4")
    hou_sticky.setText(
        "Important to export as .webm video. Only supported format in Mutagen Viewer Panel. If you need another format, just split off another branch with another FFmpeg TOP:\n\nExplicitly set to LocalScheduler, mostly faster then on the farm.\n\nIf you inserted a \"Split\" to split up the whole setup in 2 or more  seperate Contact Sheets, use _p0, _p1, ... nodename postfix."
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0, 0, 0)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(4.31289, -21.0536))
    hou_sticky.setSize(hou.Vector2(8.17024, 2.34767))
    hou_sticky.setColor(hou.Color([0.145, 0.667, 0.557]))

    #topnet_glob/__stickynote5
    hou_sticky = hou_parent.createStickyNote("__stickynote5")
    hou_sticky.setText(
        "Node just grabs the current wedgenum array as string in Python Expression, should be referenced in all Output Paths in ROPs. See Example in ROPNET."
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0.4, 0.4, 0.4)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(4.31289, 4.05587))
    hou_sticky.setSize(hou.Vector2(8.17024, 1.59761))
    hou_sticky.setColor(hou.Color([0, 0, 0]))

    #topnet_glob/__stickynote6
    hou_sticky = hou_parent.createStickyNote("__stickynote6")
    hou_sticky.setText(
        "Mostly more efficient to set it to render a couple Frames per Batch for very fast and small preview renders. Set to 'Single Frame', as it inherits Frame Range from Geo Ropfetch."
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0, 0, 0)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(4.3129, -9.58676))
    hou_sticky.setSize(hou.Vector2(8.17024, 1.39102))
    hou_sticky.setColor(hou.Color([0.624, 0.329, 0.396]))

    #topnet_glob/__stickynote7
    hou_sticky = hou_parent.createStickyNote("__stickynote7")
    hou_sticky.setText(
        "ROP Nodes just as templates for Output Filepath expressions.\nFetch ROPs from wherever you like..."
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0, 0, 0)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(-9.39003, -7.67198))
    hou_sticky.setSize(hou.Vector2(5.16529, 1.17925))
    hou_sticky.setColor(hou.Color([0.996, 0.682, 0.682]))

    #set hou_parent
    hou_parent = hou.node(hou_parent.path() + "/ropnet")

    #topnet_glob/ropnet/__stickynote1
    hou_sticky = hou_parent.createStickyNote("__stickynote1")
    hou_sticky.setText(
        "The expression\n`chs(\"/obj/topnet_glob/CTRL_WEDGES/wedge_expr\")`\nreferences the unique Wedge Index Array currently used in the variation.\n\nUse \"wdg_\" Prefix, which is needed in Mutagen Viewer."
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0, 0, 0)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(6.23358, -9.58655))
    hou_sticky.setSize(hou.Vector2(9.16572, 2.03749))
    hou_sticky.setColor(hou.Color([1, 0.529, 0.624]))

    #topnet_glob/ropnet/__stickynote2
    hou_sticky = hou_parent.createStickyNote("__stickynote2")
    hou_sticky.setText(
        "Load output from Geometry ROP with File Node to read back the disk cached results.\nJust use relative channel reference from \"Geometry ROP\" \"Output File\" Parameter."
    )
    hou_sticky.setTextSize(0)
    hou_sticky.setTextColor(hou.Color((0, 0, 0)))
    hou_sticky.setDrawBackground(True)
    hou_sticky.setPosition(hou.Vector2(6.23358, -13.2533))
    hou_sticky.setSize(hou.Vector2(9.16572, 1.68094))
    hou_sticky.setColor(hou.Color([0.624, 0.329, 0.396]))
Пример #26
0
def export_animation():
    print "\n"
    print "_" * 50
    print "Starting Export of Edited Mandelbulber Animation..."
    print "Please Note that the export only exports to Mandelbulber Flight Animation..."
    print "_" * 50
    print "\n"

    fract_filepath = hou.ui.selectFile(title="Select Original Source .fract File (Will not be overwritten)",
                                       pattern="*.fract")

    if fract_filepath == "":
        print "Export cancelled."
        sys.exit()

    fract_filepath_edit = "{}_edit.fract".format(fract_filepath.split(".fract")[0])

    print "Mandelbulber Source File:\n{}\n".format(fract_filepath)
    print "Mandelbulber Target File:\n{}\n".format(fract_filepath_edit)

    fract_file = open(fract_filepath, "r")
    fract_string = fract_file.read()
    fract_file.close()
    # print fract_string

    # export edited anim as .chan file

    anim_null = hou.node("/obj/mdb_anim_null")
    parms = anim_null.parmsInFolder((folder_name,))
    parm_tuples = anim_null.parmTuplesInFolder((folder_name,))

    precision_scale_parm = anim_null.parm("precision_scale")
    precision_scale = precision_scale_parm.eval()

    parm_pattern = []
    for parm in parms:
        parm_exceptions = ["display_size", "precision_scale"]
        if parm.name() not in parm_exceptions:
            parm.setAutoscope(1)
            parm.setScope(1)
            parm.setKeyframe(hou.Keyframe(0))
            parm_pattern.append(parm.path())
    parm_pattern = " ".join(parm_pattern)
    # print "\nParm Pattern: " + parm_pattern

    chan_filepath = fract_filepath_edit.replace(".fract", ".chan")

    # set frame to -1 so export doesn't kill first frame (houdini bug)
    hou.hscript("fcur -1")

    hou.hscript("chwrite {} {}".format(parm_pattern, chan_filepath))
    print "Exported .chan File from Houdini succesfully:\n{}".format(chan_filepath)

    # read data from .chan file back in

    chan_file = open(chan_filepath, "r")
    chan_string = chan_file.read()
    chan_file.close()

    chan_string_lines = chan_string.split("\n")[:-1]

    chan_string_out = []

    i = 0
    for line in chan_string_lines:
        vals = []
        nums = []
        # precision fixing
        vals = line.split("\t")[1:]
        for num in vals:
            num = float(num) / precision_scale
            num = str(num)
            nums.append(num)

        line = ";".join(nums)
        line = line.replace(".", ",")

        line = "{};{}".format(i, line)
        chan_string_out.append(line)
        i += 1
        
    flight_anim_out = "\n".join(chan_string_out)

    # print "\n.chan String:"
    # print chan_string_out
    # print "\n"

    # check if flight anim present in file
    fract_string_edit = ""
    if "[frames]" in fract_string:
        flight_anim = fract_string.split("[frames]")[-1]
        try:
            flight_anim = flight_anim.split("[keyframes]")[0]
        except:
            pass
        flight_anim = "\n".join(flight_anim.split("\n")[2:-1])
        fract_string_edit = fract_string.replace(flight_anim, flight_anim_out)

    # if not present, insert
    else:
        anim_parms = (fract_string.split("[keyframes]")[-1]).split("\n")[1]
        flight_anim_out = "[frames]\n" + anim_parms + "\n" + flight_anim_out + "\n[keyframes]"
        fract_string_edit = fract_string.replace("[keyframes]", flight_anim_out)

    split_last_to_render = fract_string_edit.split("flight_last_to_render ")
    fract_string_edit = split_last_to_render[0] + "flight_last_to_render " + str(
        int(hou.expandString("$FEND")) + 1) + ";" + ";".join(split_last_to_render[-1].split(";")[1:])

    # write new edited .fract file

    fract_file_edit = open(fract_filepath_edit, "w")
    fract_file_edit.write(fract_string_edit)
    fract_file_edit.close()
    print "\nEdited and saved new .fract File succesfully:\n{}".format(fract_filepath_edit)

    print "\n"
    print "_" * 50
    print "Finished Export of Edited Mandelbulber Animation..."
    print "Open edited File in Mandelbulber..."
    print "_" * 50
    print "\n"
Пример #27
0
def import_animation():
    print "\n"
    print "_" * 50
    print "Starting Import of Mandelbulber Animation..."
    print "_" * 50
    print "\n"


    # precision fixing
    precision_scale = 1000000.0


    fract_filepath = hou.ui.selectFile(title="Source .fract File", pattern="*.fract")
    if fract_filepath == "":
        print "Import cancelled."
        sys.exit()

    precision_scale = hou.ui.readInput("Please enter 'Value Scale Scale Factor' for easier editing of small values in Houdini",
                                        close_choice=1,
                                        buttons=('OK', 'Cancel'),
                                        title="Value Scale",
                                        initial_contents="1000.0")

    if precision_scale[0] == 1:
        print "Import cancelled."
        sys.exit()

    precision_scale = float(precision_scale[1])

    print "Mandelbulber File:\n{}\n".format(fract_filepath)

    print "Precision Scale fior Import: {}\n".format(precision_scale)

    fract_file = open(fract_filepath, "r")
    fract_string = fract_file.read()
    fract_file.close()
    # print fract_string

    mode = ""
    if "[frames]" in fract_string and "[keyframes]" not in fract_string:
        print "Only Flight Animation available for import..."
        mode = "flight"

    if "[keyframes]" in fract_string and "[frames]" not in fract_string:
        print "Only Keyframe Animation available for import..."
        mode = "keyframes"

    if "[keyframes]" in fract_string and "[frames]" in fract_string:
        print "Keyframe and Flight Animation available for import. Please choose."
        mode_int = hou.ui.selectFromList(("Flight Animation", "Keyframe Animation"),
                                         default_choices=(0,),
                                         exclusive=True,
                                         message="Choose Animation Type to import",
                                         title="Animation Type",
                                         column_header="Choices",
                                         num_visible_rows=2,
                                         clear_on_cancel=True,
                                         width=400,
                                         height=200)

        if mode_int == ():
            print "Import cancelled."
            sys.exit()

        if mode_int[0] == 0:
            mode = "flight"
            print "Flight Animation Chosen, starting Import...\n"

        if mode_int[0] == 1:
            mode = "keyframes"
            print "Keyframe Animation Chosen, starting Import..."
            print "Please Note that Keyframe Interpolation will be ignored...\n"

    # init variables
    anim_start = 0
    anim_end = 100
    flight_anim_out = ""
    keyframes_anim_out = ""
    flight_anim_parms = ""
    keyframes_anim_parms = ""

    # flight mode
    if mode == "flight":
        flight_anim = fract_string.split("[frames]")[-1]
        try:
            flight_anim = flight_anim.split("[keyframes]")[0]
        except:
            pass

        flight_anim_out = ""
        for line in flight_anim.split("\n"):
            line = " ".join(line.split(";")[1:])
            line = line.replace(",", ".")

            # precision fixing
            nums = []
            try:
                for num in line.split(" "):
                    num = float(num) * precision_scale
                    num = str(num)
                    nums.append(num)
                line = " ".join(nums)
            except:
                pass

            flight_anim_out += line + "\n"

        flight_anim_parms = flight_anim_out.split("\n")[1]
        flight_anim_out = flight_anim_out.split("\n")[2:-2]
        flight_anim_out = "\n".join(flight_anim_out)

        # print "Flight Animation String:"
        # print flight_anim_out
        # print "End Flight Animation String"

        if "flight_first_to_render" in fract_string:
            anim_start = int((fract_string.split("flight_first_to_render ")[-1]).split(";")[0])
        anim_end = int((fract_string.split("flight_last_to_render ")[-1]).split(";")[0]) - 1

    # keyframes mode
    if mode == "keyframes":
        keyframes_anim = fract_string.split("[keyframes]")[-1]

        keyframes_anim_out = ""
        for line in keyframes_anim.split("\n"):
            line = " ".join(line.split(";")[1:])
            line = line.replace(",", ".")

            # precision fixing
            nums = []
            try:
                for num in line.split(" "):
                    num = float(num) * precision_scale
                    num = str(num)
                    nums.append(num)
                line = " ".join(nums)
            except:
                pass

            keyframes_anim_out += line + "\n"
        keyframes_anim_out = "\n".join(keyframes_anim_out.split("\n")[1:-2])

        keyframes_anim_parms = keyframes_anim_out.split("\n")[0]

        keyframes_anim_interpolation = keyframes_anim_out.split("\n")[-1]
        keyframes_anim_out = keyframes_anim_out.split("\n")[1:-1]
        keyframes_anim_out = "\n".join(keyframes_anim_out)

        '''
        print "Keyframes Animation String:"
        print keyframes_anim_out
        print "Keyframes Anim Parms:"
        print keyframes_anim_parms
        print "Keyframes Interpolation"
        print keyframes_anim_interpolation
        print "End Strings\n"
        '''

        if "keyframe_first_to_render" in fract_string:
            anim_start = int((fract_string.split("keyframe_first_to_render ")[-1]).split(";")[0])
        anim_end = int((fract_string.split("keyframe_last_to_render ")[-1]).split(";")[0]) - 1

    # write to .chan file
    chan_filepath = fract_filepath.replace(".fract", ".chan")
    chan_file = open(chan_filepath, "w")
    # flight mode
    if mode == "flight":
        chan_file.write(flight_anim_out)
    if mode == "keyframes":
        chan_file.write(keyframes_anim_out)
    chan_file.close()
    print "Converted to .chan File succesfully:\n{}".format(chan_filepath)

    # set up houdini scene

    fps = 30
    if "keyframe_frames_per_second" in fract_string:
        fps = fract_string.split("keyframe_frames_per_second ")
        fps = (fps[-1].split(";"))[0]
        fps = int(fps)

    print "Anim Start: {}".format(anim_start)
    print "Anim End: {}".format(anim_end)
    print "FPS: {}".format(fps)
    print "\n"

    hou.hipFile.clear()
    hou.hscript("fps {}".format(fps))
    hou.hscript("tset {} {}".format(float(-1) / float(fps), float(anim_end) / float(fps)))
    hou.hscript("frange {} {}".format(anim_start, anim_end))
    print "Animation Range and FPS set in Houdini Scene\n"

    # create null object and extract parms
    anim_null = hou.node("/obj/").createNode("null", "mdb_anim_null")
    anim_null.setSelected(1, 1)
    anim_null.setDisplayFlag(0)

    if mode == "flight":
        anim_parms = flight_anim_parms
    if mode == "keyframes":
        anim_parms = keyframes_anim_parms

    anim_parms = anim_parms.split(" ")

    extensions = ["x", "y", "z", "w"]
    anim_parms_split = []
    for parm in anim_parms:
        
        split = parm.rsplit("_", 1)
        if parm[-1] in extensions:
            if len(split) > 1:
                anim_parms_split.append(split[0])
        else:
            anim_parms_split.append(parm)

    unique_list = []
    for item in anim_parms_split:
        if item not in unique_list:
            unique_list.append(item)

    parms_dict = OrderedDict()
    for item in unique_list:
        parms_dict[item] = anim_parms_split.count(item)

    print "\nAnimation Parameters:"
    for item in parms_dict:
        print "SIZE: {}; NAME: {}".format(parms_dict[item], item)

    # create parms
    parm_group = anim_null.parmTemplateGroup()
    parm_folder = hou.FolderParmTemplate("folder", folder_name)

    i = 0
    for item in parms_dict:
        size = parms_dict[item]
        if size > 1:
            name = "_{}_{}_".format(i, item).format(item)
            parm_folder.addParmTemplate(hou.FloatParmTemplate(name, name, size))
        else:
            name = "_{}_{}".format(i, item).format(item)
            parm_folder.addParmTemplate(hou.FloatParmTemplate(name, name, size))
        i += 1

    parm_folder.addParmTemplate(hou.FloatParmTemplate("display_size", "Display Size", 1))
    parm_folder.addParmTemplate(hou.FloatParmTemplate("precision_scale", "Precision Scale", 1))
    parm_group.append(parm_folder)
    anim_null.setParmTemplateGroup(parm_group)

    # set parms to animated

    xform_parms = anim_null.parmsInFolder(("Transform",))
    for parm in xform_parms:
        parm.setAutoscope(0)
        parm.setScope(0)

    parms = anim_null.parmsInFolder((folder_name,))
    parm_tuples = anim_null.parmTuplesInFolder((folder_name,))

    parm_pattern = []
    for parm in parms:
        parm_exceptions = ["display_size", "precision_scale"]
        if parm.name() not in parm_exceptions:
            parm.setAutoscope(1)
            parm.setScope(1)
            parm.setKeyframe(hou.Keyframe(0))
            parm_pattern.append(parm.path())
    parm_pattern = " ".join(parm_pattern)
    #print "\nParm Pattern: " + parm_pattern

    # load data from .chan file

    hou.hscript("chread -f {} {} -n {} {}".format(anim_start, anim_end, parm_pattern, chan_filepath))
    print "\nAnimation Data read back from .chan File and applied to Parameters on Animation Null."

    # create helper nulls

    display_size_parm = anim_null.parm("display_size")
    display_size_parm.set(0.025)

    precision_scale_parm = anim_null.parm("precision_scale")
    precision_scale_parm.set(precision_scale)

    # cam null
    cam_null = hou.node("/obj/").createNode("null", "cam_null")
    cam_null.move([-2, -2])
    cam_null_col = (1, 0, 0)
    cam_null_col_parm = cam_null.parmTuple("dcolor")
    cam_null_col_parm.set(cam_null_col)
    cam_null.setColor(hou.Color(cam_null_col))
    cam_null_scale = cam_null.parm("geoscale")
    cam_null_scale.setExpression('ch("../mdb_anim_null/display_size")')
    cam_null.parm("tx").setExpression('ch("../mdb_anim_null/_0_main_camera_x")')
    cam_null.parm("ty").setExpression('ch("../mdb_anim_null/_0_main_camera_y")')
    cam_null.parm("tz").setExpression('ch("../mdb_anim_null/_0_main_camera_z")')

    # target null
    target_null = hou.node("/obj/").createNode("null", "target_null")
    target_null.move([2, -2])
    target_null_col = (0, 0, 1)
    target_null_col_parm = target_null.parmTuple("dcolor")
    target_null_col_parm.set(target_null_col)
    target_null.setColor(hou.Color(target_null_col))
    target_null_scale = target_null.parm("geoscale")
    target_null_scale.setExpression('ch("../mdb_anim_null/display_size")')
    target_null.parm("tx").setExpression('ch("../mdb_anim_null/_1_main_target_x")')
    target_null.parm("ty").setExpression('ch("../mdb_anim_null/_1_main_target_y")')
    target_null.parm("tz").setExpression('ch("../mdb_anim_null/_1_main_target_z")')

    ### save hipFile
    hip_filepath = fract_filepath.replace(".fract", ".hip")
    hou.hipFile.save(hip_filepath)

    print "\n"
    print "_" * 50
    print "Finished Import of Mandelbulber Animation..."
    print "Hip File saved:"
    print hip_filepath
    print "Edit Animation and then Export..."
    print "_" * 50
    print "\n"
Пример #28
0
def setLinKey(prm, val, fno):
    key = hou.Keyframe()
    key.setExpression("linear()")
    key.setFrame(fno)
    key.setValue(val)
    prm.setKeyframe(key)
Пример #29
0
def importLightFromClipboard():
    obj = hou.node('/obj')
    light = None
    light_name = ''
    light_type = ''
    light_target = None
    is_tuple = False
    clipboard = QtWidgets.QApplication.clipboard()
    text = clipboard.text()
    lines = text.splitlines()

    error_count = 0

    if lines[0].startswith('#light_export'):
        ls = lines[0].split(',', 2)
        fps = ls[1]
        range = ls[2]

        if fps != str(hou.fps()):
            print('warning: fps differs from export')
        if range != str(hou.playbar.timelineRange()):
            print('warning: animation range differs from export')

        for line in lines[1:]:
            ls = line.split(',', 1)
            if len(ls) == 2:
                parm_name = ls[0]
                parm_val = ls[1]
                if parm_val.startswith('\'') and parm_val.endswith('\''):
                    parm_val = parm_val[1:-1]
                else:
                    parm_val = eval(parm_val)

                is_tuple = isinstance(parm_val, tuple)
                if parm_name == 'name':
                    light_name = parm_val
                elif line.startswith('type'):
                    light_type = parm_val
                    light = obj.node(light_name)
                    if light == None:
                        light = obj.createNode(light_type)
                        light.setName(light_name)
                        light.setColor(hou.Color(1, 0.898039, 0))
                        light.setUserData('nodeshape', 'light')
                        light.moveToGoodPosition()

                        out_node = None
                        for n in light.children():
                            if n.isGenericFlagSet(hou.nodeFlag.Render) == True:
                                out_node = n
                        color = out_node.createOutputNode('color')
                        color.parm('colorr').set(1)
                        color.parm('colorg').set(0.898039)
                        color.parm('colorb').set(0)
                        color.setDisplayFlag(True)

                        if light_type == 'VRayNodeLightSphere':
                            light.node('sphere1').parm('type').set(4)
                            light.node('sphere1').parm('imperfect').set(0)

                        if light_type == 'VRayNodeLightRectangle':
                            light.node('line1').parm('dist').setExpression(
                                '(ch("../u_size") + ch("../v_size")) * 0.333')
                            light.node('grid1').parm('type').set(2)
                            light.node('grid1').parm('orderu').set(2)
                            light.node('grid1').parm('orderv').set(2)
                            switch = light.node('grid1').createOutputNode(
                                'switch')
                            switch.parm('input').setExpression(
                                'ch("../is_disc")')
                            circle = light.createNode('circle')
                            circle.parm('type').set(2)
                            circle.parm('radx').setExpression(
                                'ch("../u_size") / 2')
                            circle.parm('rady').setExpression(
                                'ch("../v_size") / 2')
                            # light.parm('v_size').setExpression('ch("u_size")')
                            switch.setNextInput(circle)
                            light.node('merge1').setInput(0, switch)
                            # light.layoutChildren()

                        if light_type == 'VRayNodeSunLight':
                            '''
                            light.node('transform1').parm('sx').setExpression('ch("../size_multiplier")')
                            light.node('transform1').parm('sy').setExpression('ch("../size_multiplier")')
                            light.node('transform1').parm('sz').setExpression('ch("../size_multiplier")')
                            '''

                            light_target = obj.node(light_name + '_target')
                            if light_target == None:
                                light_target = createLightTarget(obj, light)
                            else:
                                for p in (light_target.parms()):
                                    p.deleteAllKeyframes()

                    else:
                        if light.type().name() != light_type:
                            light.changeNodeType(light_type)
                        for p in (light.parms()):
                            p.deleteAllKeyframes()
                            p.revertToDefaults()

                        light.parm('constraints_on').set(1)
                        light.parm('constraints_path').set('constraints')

                elif parm_name == 'type':
                    light_type = parm_val
                    if light_type == 'target':
                        light_target = obj.node(light_name + '_target')
                        if light_target == None:
                            light_target = createLightTarget(obj, light)
                        else:
                            for p in (light_target.parms()):
                                p.deleteAllKeyframes()

                elif line.startswith('target_'):
                    if is_tuple:
                        for k in parm_val:
                            setKey = hou.Keyframe()
                            setKey.setFrame(k[0])
                            setKey.setValue(k[1])
                            light_target.parm(
                                parm_name[7:]).setKeyframe(setKey)
                    else:
                        light_target.parm(parm_name[7:]).set(parm_val)

                else:
                    try:
                        if is_tuple:
                            for k in parm_val:
                                setKey = hou.Keyframe()
                                setKey.setFrame(k[0])
                                setKey.setValue(k[1])
                                light.parm(parm_name).setKeyframe(setKey)
                        else:
                            light.parm(parm_name).set(parm_val)
                    except:
                        print('cannot setting parameter: ' + parm_name)
                        error_count += 1

        if error_count == 0:
            print('light successfully imported')
        else:
            print('light imported with ' + str(error_count) + " errors")

    else:
        print('cannot apply clipboad values, wrong type!')
Пример #30
0
def create_cam():

    seq = hou.ui.selectFile(title="Select first frame of EXR Sequence",
                            collapse_sequences=True,
                            pattern="*.exr",
                            width=800,
                            height=600)

    if seq == "":
        print "Cancelled..."
        sys.exit()
    seq = hou.expandString(seq)

    fps = hou.ui.readInput("Set FPS for Image Sequence",
                           buttons=(
                               'OK',
                               'Cancel',
                           ),
                           default_choice=0,
                           close_choice=1,
                           title=None,
                           initial_contents="60")

    if fps[0] == 1:
        print "Cancelled..."
        sys.exit()
    else:
        fps = int(fps[1])

    print "\nStart Camera creation from EXR Sequence..."
    print "First Frame:"
    print seq
    print "\n"

    #create copnet
    img = hou.node("/img").createNode("img", "img")
    cop = img.createNode("file", "read_seq")
    cop.parm("nodename").set(0)

    fileparm = cop.parm("filename1")
    fileparm.set("")

    split = os.path.split(seq)
    dir = split[0]
    start = split[1].split("_")[0]
    temp = split[1].split("_")[-1]
    mid = temp.split(".")[0]
    end = temp.split(".")[-1]

    pad = len(mid)
    start_frame = int(mid)
    num_frames = len(os.listdir(dir))
    end_frame = num_frames - 1

    print "Start Frame: {}".format(start_frame)
    print "End Frame: {}".format(end_frame)
    print "Number of Frames: {}".format(num_frames)
    print "FPS: {}\n".format(fps)

    #houdini scene setup
    hou.hscript("fps {}".format(fps))
    hou.hscript("tset {} {}".format(
        float(-1) / float(fps),
        float(end_frame) / float(fps)))
    hou.hscript("frange {} {}".format(start_frame, end_frame))
    hou.hscript("fcur 0")

    #static metadata
    fileparm.set(seq)

    meta = cop.getMetaDataString("attributes")
    meta = eval(meta)
    width = cop.xRes()
    height = cop.yRes()
    aspect = float(height) / float(width)

    perspective_type = meta[
        "perspective_type"]  #"persp_three_point", "persp_equirectangular",
    stereo_enabled = meta["stereo_enabled"]  #"yes", "no"
    stereo_infinite_correction = int(
        meta["stereo_infinite_correction"])  #[0, 1]

    print "Perspective Type: {}".format(perspective_type)
    print "Stereo Enabled: {}".format(stereo_enabled)
    print "Stereo Infinite Correction: {}".format(stereo_infinite_correction)
    print "Width: {}".format(width)
    print "Height: {}".format(height)
    print "Aspect: {}".format(aspect)

    #create camera
    cam = ""

    vr_cam_typename_to_create = "vrcam"
    cam_aperture_base = 36
    cam_vr_focal = 18

    def create_vr_cam():
        cam = hou.node("/obj").createNode(vr_cam_typename_to_create)
        cam.parm("vrmergemode").set(2)
        cam.parm("vrmergeangle").set(90)
        cam.parm("vreyetoneckdistance").set(0)
        vr_layout_parm = cam.parm("vrlayout")
        if aspect == 0.5:
            vr_layout_parm.set(2)
        if aspect == 1:
            vr_layout_parm.set(1)
        if aspect == 0.25:
            vr_layout_parm.set(0)

        return cam

    if stereo_enabled == "yes":
        if perspective_type == "persp_equirectangular":
            cam = create_vr_cam()
        elif perspective_type == "persp_three_point":
            cam = hou.node("/obj").createNode("stereocamrig")
        else:
            raise Exception(
                "Perspective Type '{}' not supported by Houdini.".format(
                    perspective_type))

    if stereo_enabled == "no":
        if perspective_type == "persp_equirectangular":
            cam = create_vr_cam()
        elif perspective_type == "persp_three_point":
            cam = hou.node("/obj").createNode("cam")
        else:
            raise Exception(
                "Perspective Type '{}' not supported by Houdini.".format(
                    perspective_type))

    #set res
    cam.parm("resx").set(width)
    cam.parm("resy").set(height)

    # start loop
    print "\nStart iterating over frames...\n"

    keys_tx = []
    keys_ty = []
    keys_tz = []

    keys_rx = []
    keys_ry = []
    keys_rz = []

    keys_targetx = []
    keys_targety = []
    keys_targetz = []

    keys_topx = []
    keys_topy = []
    keys_topz = []

    keys_focal = []
    keys_stereo = []

    for i in range(num_frames):
        frame = str(i).zfill(pad)
        file = "{}/{}_{}.{}".format(dir, start, frame, end)
        #print "Current File: {}".format(file)
        fileparm.set(file)

        meta = cop.getMetaDataString("attributes")
        meta = eval(meta)

        #get values from metadata

        #camera position
        translate_x = float(meta["camera.x"])
        translate_y = float(meta["camera.y"])
        translate_z = float(meta["camera.z"])
        translate = hou.Vector3(translate_x, translate_y, translate_z)

        key_tx = hou.Keyframe(translate_x, hou.frameToTime(i))
        keys_tx.append(key_tx)
        key_ty = hou.Keyframe(translate_y, hou.frameToTime(i))
        keys_ty.append(key_ty)
        key_tz = hou.Keyframe(translate_z, hou.frameToTime(i))
        keys_tz.append(key_tz)

        #camera rotation / not correctly exported from mandelbulber
        #thus cam xform matrix calculated from cam vectors
        '''
		#correct mandelbulber meta output
		rotate_x = 90 - float(meta["camera_rotation.y"])
		rotate_y = float(meta["camera_rotation.z"])
		rotate_z = float(meta["camera_rotation.x"])
		'''

        #calculate rotations from cam vectors

        #camera target
        target_x = float(meta["target.x"])
        target_y = float(meta["target.y"])
        target_z = float(meta["target.z"])
        target = hou.Vector3(target_x, target_y, target_z)

        #camera top (up)
        top_x = float(meta["top.x"])
        top_y = float(meta["top.y"])
        top_z = float(meta["top.z"])
        top = hou.Vector3(top_x, top_y, top_z)

        # calculate vectors
        forward = (translate - target).normalized()
        right = top.normalized().cross(forward)
        up = forward.cross(right)

        #build matrix
        right_c = hou.Vector4(right.x(), right.y(), right.z(), 0)
        up_c = hou.Vector4(up.x(), up.y(), up.z(), 0)
        forward_c = hou.Vector4(forward.x(), forward.y(), forward.z(), 0)
        translate_c = hou.Vector4(translate.x(), translate.y(), translate.z(),
                                  1)
        m = hou.Matrix4((right_c, up_c, forward_c, translate_c))

        #extract rotations
        pivot_v = hou.Vector3(0, 0, 0)
        pivot_rotate_v = hou.Vector3(0, 0, 0)
        rotate = m.extractRotates(transform_order='srt',
                                  rotate_order='xyz',
                                  pivot=pivot_v,
                                  pivot_rotate=pivot_rotate_v)
        rotate_x = rotate.x()
        rotate_y = rotate.y()
        rotate_z = rotate.z()

        key_rx = hou.Keyframe(rotate_x, hou.frameToTime(i))
        keys_rx.append(key_rx)
        key_ry = hou.Keyframe(rotate_y, hou.frameToTime(i))
        keys_ry.append(key_ry)
        key_rz = hou.Keyframe(rotate_z, hou.frameToTime(i))
        keys_rz.append(key_rz)

        fov = float(meta["fov"])
        #calulate focal length based on fov and "cam_aperture_base"
        focal = cam_aperture_base / (2 * math.tan(math.radians(fov) / 2))
        key_focal = hou.Keyframe(focal, hou.frameToTime(i))
        keys_focal.append(key_focal)

        stereo_eye_distance = 2 * float(meta["stereo_eye_distance"])
        key_stereo = hou.Keyframe(stereo_eye_distance, hou.frameToTime(i))
        keys_stereo.append(key_stereo)

        #print "\nFrame: {}".format(frame)
        #print "Translate: ({}, {}, {})".format(translate_x, translate_y, translate_z)
        #print "Rotate: ({}, {}, {})".format(rotate_x, rotate_y, rotate_z)
        #print "Stereo Distance: {}".format(stereo_eye_distance)

    #set keyframes
    parm_tx = cam.parm("tx")
    parm_tx.setKeyframes(keys_tx)
    parm_ty = cam.parm("ty")
    parm_ty.setKeyframes(keys_ty)
    parm_tz = cam.parm("tz")
    parm_tz.setKeyframes(keys_tz)

    parm_rx = cam.parm("rx")
    parm_rx.setKeyframes(keys_rx)
    parm_ry = cam.parm("ry")
    parm_ry.setKeyframes(keys_ry)
    parm_rz = cam.parm("rz")
    parm_rz.setKeyframes(keys_rz)

    parm_aperture = cam.parm("aperture")
    parm_aperture.set(cam_aperture_base)
    parm_focal = cam.parm("focal")

    if perspective_type == "persp_equirectangular":
        parm_focal.set(cam_vr_focal)
        parm_stereo = cam.parm("vreyeseparation")
        if stereo_enabled == "yes":
            parm_stereo.setKeyframes(keys_stereo)
        else:
            parm_stereo.set(0)
    else:
        parm_focal.setKeyframes(keys_focal)
        if stereo_enabled == "yes":
            parm_stereo = cam.parm("interaxial")
            parm_stereo.setKeyframes(keys_stereo)

    #delete img node
    img.destroy()

    #select camera
    cam.setSelected(1, 1)
    print "\nCamera successfully created from Mandelbulber EXR Image Sequence.\n\n"