def newGeo(hpath):
    templateNode = hou.node(hpath).createNode("geometryTemplate")
    alist = listContainers()
    resp = ui.inputWindow("Enter the New Operator Label", wtitle="OTL Label")
    filename = str()
    if resp != None and resp.strip() != "":
        name = formatName(resp)
        filename = name.replace(" ", "_")
        templateNode.setName(filename, unique_name=True)
    answer = ui.listWindow(alist, wmessage="Select Container Asset this belongs to:")
    if not answer:
        ui.infoWindow(
            "Geometry must be associated with a container asset! Geometry asset not created.",
            msev=messageSeverity.Error,
        )
        templateNode.destroy()
        return
    answer = answer[0]
    sdir = "$JOB/PRODUCTION/assets/"
    gfile = ui.fileChooser(
        start_dir=sdir + alist[answer] + "/geo",
        wtitle="Choose Geometry",
        mode=fileMode.Read,
        extensions="*.bjson, *.obj",
    )
    if len(gfile) > 4 and gfile[:4] != "$JOB":
        ui.infoWindow(
            "Path must start with '$JOB'. Default geometry used instead.",
            wtitle="Path Name",
            msev=messageSeverity.Error,
        )
        templateNode.destroy()
    elif gfile != "":
        hou.parm(templateNode.path() + "/read_file/file").set(gfile)
Пример #2
0
        def set_path(self):
            rownum = self.tableWidget.rowCount()

            for r in range(0, rownum):

                if self.tableWidget.item(r, 3).text() != self.tableWidget.item(
                        r, 4).text() and self.tableWidget.item(
                            r, 4).text() != '' and self.tableWidget.item(
                                r, 0).text().find('exist') == -1:
                    if self.tableWidget.item(
                            r, 1).text() == 'alembic' or self.tableWidget.item(
                                r, 1).text() == 'alembicarchive':
                        ll = hou.parm(
                            self.tableWidget.item(r, 2).text() + '/fileName')
                    else:
                        ll = hou.parm(
                            self.tableWidget.item(r, 2).text() + '/file')

                    try:
                        ll.set(self.tableWidget.item(r, 4).text())
                    except:
                        print 'Error:' + str(ll) + 'possible  locked '
                    print 'set  ' + str(ll) + ' =  ' + self.tableWidget.item(
                        r, 4).text()
                else:
                    pass
Пример #3
0
def newGeo(hpath):
    templateNode = hou.node(hpath).createNode("geometryTemplate")
    alist = listContainers()
    response = hou.ui.readInput("Enter the New Operator Label", title="OTL Label", buttons=('OK', 'Cancel'))
    filename = str()
    if response[0]==0:
        name = response[1]
    else:
        name = None
    if name != None and name.strip() != '':
        name = hou_asset_mgr.formatName(name)
        filename = name.replace(' ', '_')
        templateNode.setName(filename, unique_name=True)
    answer = hou.ui.selectFromList(alist, message='Select Container Asset this belongs to:', exclusive=True)
    if not answer:
        hou.ui.displayMessage("Geometry must be associated with a container asset! Geometry asset not created.", severity=hou.severityType.Error)
        templateNode.destroy()
        return
    answer = answer[0]
    sdir = '$JOB/production/assets/'
    gfile = hou.ui.selectFile(start_directory=os.path.join(sdir, alist[answer]+'/geo'), title='Choose Geometry', chooser_mode=hou.fileChooserMode.Read, pattern='*.abc')
    if len(gfile) > 4 and gfile[:4] != '$JOB':
        hou.ui.displayMessage("Path must start with '$JOB'. Default geometry used instead.", title='Path Name', severity=hou.severityType.Error)
        templateNode.destroy()
    elif gfile != '':
        hou.parm(templateNode.path() + '/read_file/fileName').set(gfile)
Пример #4
0
def newGeo(hpath):
    templateNode = hou.node(hpath).createNode("geometryTemplate")
    alist = listContainers()
    response = hou.ui.readInput("Enter the New Operator Label", title="OTL Label", buttons=('OK', 'Cancel'))
    filename = str()
    if response[0]==0:
        name = response[1]
    else:
        name = None
    if name != None and name.strip() != '':
        name = formatName(name)
        filename = name.replace(' ', '_')
        templateNode.setName(filename, unique_name=True)
    answer = hou.ui.selectFromList(alist, message='Select Container Asset this belongs to:', exclusive=True)
    if not answer:
        hou.ui.displayMessage("Geometry must be associated with a container asset! Geometry asset not created.", severity=hou.severityType.Error)
        templateNode.destroy()
        return
    answer = answer[0]
    sdir = '$JOB/production/assets/'
    gfile = hou.ui.selectFile(start_directory=os.path.join(sdir, alist[answer]+'/geo'), title='Choose Geometry', chooser_mode=hou.fileChooserMode.Read, pattern='*.bjson, *.obj')
    if len(gfile) > 4 and gfile[:4] != '$JOB':
        hou.ui.displayMessage("Path must start with '$JOB'. Default geometry used instead.", title='Path Name', severity=hou.severityType.Error)
        templateNode.destroy()
    elif gfile != '':
        hou.parm(templateNode.path() + '/read_file/file').set(gfile)
Пример #5
0
def import_btn():
    node = hou.pwd()
    parm = node.parm('wedge_select')
    parm_val = parm.eval()
    load_value = node.parm('wedge_list').eval().split('\n')

    value_list = []

    wedge_parms = node.parm('wedge_parm').multiParmInstances()

    for i in wedge_parms:
        if 'chs' in i.rawValue():
            value_list.append(i.rawValue()[6:-3])
        else:
            pass

    import_value_list = []

    for l in load_value:
        import_value_list.append(l.split(' - ')[-1])

    import_value = import_value_list[parm_val][1:-1]

    import_parm = node.parm('import_value')
    import_parm.lock(False)
    import_parm.set(import_value)
    import_parm.lock(True)

    set_value = import_value_list[parm_val][1:-1].split(', ')

    for v, s in zip(value_list, set_value):
        hou.parm(v).set(float(s))
def read_dataset_from_current_frame(working_dir, sop_name, prediction=False):
    frame_id = hou.intFrame()

    # Find the name of the current animation
    anim_type = hou.parm(sop_name + '/anim_types').evalAsString()
    clip_name = hou.parm(sop_name + '/' + anim_type).evalAsString()
    clip_name = clip_name.replace('.bclip', '')

    if prediction:
        clip_path = os.path.join(working_dir, 'prediction', clip_name + '.npz')
    else:
        clip_path = os.path.join(working_dir, 'dataset', clip_name + '.npz')

    if os.path.exists(clip_path):
        npzfile = np.load(clip_path)
        #bones = npzfile['bones']
        #base_skinnings = npzfile['bases']
        if prediction:
            smooth_skinnings = npzfile['predicted_smooths']
        else:
            smooth_skinnings = npzfile['smooths']
            #smooth_skinnings = npzfile['bases']

        #bone = bones[frame_id-1]
        #base_skinning = base_skinnings[frame_id-1]
        smooth_skinning = smooth_skinnings[frame_id - 1]

        node = hou.pwd()
        geo = node.geometry()

        for i, point in enumerate(geo.points()):
            point.setPosition(smooth_skinning[i])
    else:
        print('the file ', clip_path, ' doesnt exist')
Пример #7
0
def _checkRenderParameters(parms):
    """Check the values of the render-specific parameters.

    Return True if the values are valid and False otherwise.
    """

    if parms["max_hosts_per_job"] < parms["min_hosts_per_job"]:
        hqrop.displayError(
            "Max. Hosts Per Job must be greater than or equal to "
            "Min. Hosts Per Job.")
        return False

    # Check IFD file path.
    if parms["make_ifds"] or not parms["use_output_driver"]:
        if not parms["ifd_path"]:
            if parms["make_ifds"]:
                ifd_path_parm = hou.parm("hq_outputifd")
            elif not parms["use_output_driver"]:
                ifd_path_parm = hou.parm("hq_input_ifd")

            ifd_parm_label = ifd_path_parm.parmTemplate().label()
            hqrop.displayError(" ".join([
                "The value of the", ifd_parm_label, "parameter in\n",
                hou.pwd().path(), "\n"
                "must not be blank."
            ]))
            return False

    return True
	def testPrimitiveGroupModeWithMultipleObjects( self ) :
		hou.setFrame( 3 )
		cache = self.cacheSop( file="test/IECoreHoudini/data/torusWithVertexNormals.bgeo" )
		cache.parm( "groupingMode" ).set( 0 )
		hou.parm( "/obj/geo1/group1/entity" ).set( 0 )
		torus = cache.parent().createNode( "file" )
		torus.parm( "file" ).set( "test/IECoreHoudini/data/torusWithVertexNormals.bgeo" )
		group = torus.createOutputNode( "group" )
		group.parm( "crname" ).set( "torus2" )
		merge = cache.inputs()[0].createOutputNode( "merge" )
		merge.setInput( 1, group )
		cache.setInput( 0, merge )
		result = IECoreHoudini.FromHoudiniPolygonsConverter( cache ).convert()
		numTorusPoints = len(torus.geometry().points())
		for key in [ "P", "Cs" ] :
			self.assert_( key in result )
			self.assertEqual( result[key].data.size(), 2 * numTorusPoints )
		
		for i in range( 0, numTorusPoints ) :
			self.assertNotEqual( result['P'].data[i], result['P'].data[numTorusPoints+i] )
			self.assertEqual( result['Cs'].data[i], result['Cs'].data[numTorusPoints+i] )
		
		numTorusVerts = sum( [ len(x.vertices()) for x in torus.geometry().prims() ] )
		self.assert_( "N" in result )
		self.assertEqual( result["N"].data.size(), 2 * numTorusVerts )
		for i in range( 0, numTorusVerts ) :
			self.assertNotEqual( result['N'].data[i], result['N'].data[numTorusPoints+i] )
Пример #9
0
    def testPrimitiveGroupModeWithMultipleObjects(self):
        hou.setFrame(3)
        cache = self.cacheSop(
            file="test/IECoreHoudini/data/torusWithVertexNormals.bgeo")
        cache.parm("groupingMode").set(0)
        hou.parm("/obj/geo1/group1/entity").set(0)
        torus = cache.parent().createNode("file")
        torus.parm("file").set(
            "test/IECoreHoudini/data/torusWithVertexNormals.bgeo")
        group = torus.createOutputNode("group")
        group.parm("crname").set("torus2")
        merge = cache.inputs()[0].createOutputNode("merge")
        merge.setInput(1, group)
        cache.setInput(0, merge)
        result = IECoreHoudini.FromHoudiniPolygonsConverter(cache).convert()
        numTorusPoints = len(torus.geometry().points())
        for key in ["P", "Cs"]:
            self.assert_(key in result)
            self.assertEqual(result[key].data.size(), 2 * numTorusPoints)

        for i in range(0, numTorusPoints):
            self.assertNotEqual(result['P'].data[i],
                                result['P'].data[numTorusPoints + i])
            self.assertEqual(result['Cs'].data[i],
                             result['Cs'].data[numTorusPoints + i])

        numTorusVerts = sum(
            [len(x.vertices()) for x in torus.geometry().prims()])
        self.assert_("N" in result)
        self.assertEqual(result["N"].data.size(), 2 * numTorusVerts)
        for i in range(0, numTorusVerts):
            self.assertNotEqual(result['N'].data[i],
                                result['N'].data[numTorusPoints + i])
Пример #10
0
    def testPrimitiveGroupModeWithTransformAttribute(self):
        cache = self.cacheSop(
            file="test/IECoreHoudini/data/torusWithVertexNormals.bgeo")
        cache.parm("groupingMode").set(0)
        hou.parm("/obj/geo1/group1/entity").set(0)
        hou.setFrame(2)
        orig = IECoreHoudini.FromHoudiniPolygonsConverter(cache).convert()
        cache.parm("transformAttribute").set("transform")
        result = IECoreHoudini.FromHoudiniPolygonsConverter(cache).convert()
        self.assertNotEqual(orig, result)
        self.assertNotEqual(orig['P'], result['P'])
        self.assertNotEqual(orig['N'], result['N'])
        self.assertEqual(orig['P'].data.size(), result['P'].data.size())
        self.assertEqual(orig['N'].data.size(), result['N'].data.size())
        self.assertEqual(orig['Cs'], result['Cs'])
        self.assertEqual(orig['pointId'], result['pointId'])

        i = IECore.InterpolatedCache(
            cache.parm("cacheSequence").eval(),
            IECore.InterpolatedCache.Interpolation.Linear,
            IECore.OversamplesCalculator(24, 1))
        matrix = i.read(2, "torus", "transform").value.transform
        origP = orig["P"].data
        origN = orig["N"].data
        resultP = result["P"].data
        resultN = result["N"].data
        for i in range(0, origP.size()):
            self.assertNotEqual(resultP[i], origP[i])
            self.assertNotEqual(resultN[i], origN[i])
            self.assertEqual(resultP[i], matrix.multVecMatrix(origP[i]))
            self.failUnless(resultN[i].equalWithAbsError(
                matrix.multDirMatrix(origN[i]), 1e-6))
Пример #11
0
    def testErrorStates(self):

        # no prims
        merge = self.createCurves(4)
        add = merge.createOutputNode("add")
        add.parm("keep").set(True)  # deletes primitive and leaves points
        converter = IECoreHoudini.FromHoudiniCurvesConverter(add)
        self.assertRaises(RuntimeError, converter.convert)

        # non-curve prims
        merge = self.createCurves(4)
        merge.createInputNode(5, "box")
        converter = IECoreHoudini.FromHoudiniCurvesConverter(merge)
        self.assertRaises(RuntimeError, converter.convert)

        # many curves, different orders
        merge = self.createCurves(4)
        hou.parm("/obj/geo3/curve3/order").set(3)
        converter = IECoreHoudini.FromHoudiniCurvesConverter(merge)
        self.assertRaises(RuntimeError, converter.convert)

        # many curves, different periodicity
        merge = self.createCurves(4)
        hou.parm("/obj/geo4/curve3/close").set(True)
        converter = IECoreHoudini.FromHoudiniCurvesConverter(merge)
        self.assertRaises(RuntimeError, converter.convert)
Пример #12
0
	def testErrorStates( self ) :
		
		# no prims
		merge = self.createCurves( 4 )
		add = merge.createOutputNode( "add" )
		add.parm( "keep" ).set( True ) # deletes primitive and leaves points
		converter = IECoreHoudini.FromHoudiniCurvesConverter( add )
		self.assertRaises( RuntimeError, converter.convert )
		
		# non-curve prims
		merge = self.createCurves( 4 )
		merge.createInputNode( 5, "box" )
		converter = IECoreHoudini.FromHoudiniCurvesConverter( merge )
		self.assertRaises( RuntimeError, converter.convert )
		
		# many curves, different orders
		merge = self.createCurves( 4 )
		hou.parm( "/obj/geo3/curve3/order" ).set( 3 )
		converter = IECoreHoudini.FromHoudiniCurvesConverter( merge )
		self.assertRaises( RuntimeError, converter.convert )
		
		# many curves, different periodicity
		merge = self.createCurves( 4 )
		hou.parm( "/obj/geo4/curve3/close" ).set( True )
		converter = IECoreHoudini.FromHoudiniCurvesConverter( merge )
		self.assertRaises( RuntimeError, converter.convert )
def main():
    if (len(sys.argv) != 3):
        exit(1)

    global g_jobIFD, g_jobEXR

    print 'Loading File...',
    hou.hipFile.load(sys.argv[1], ignore_load_warnings=True)
    print 'DONE!'

    rop_list = []
    rop_out = hou.node("/out/OUT")
    rop_children = rop_out.inputAncestors()
    for child in rop_children:
        type = child.type().name()
        if type == 'ifd':
            rop_list.append(child)
    for rop in rop_list:
        print rop.path()
        parm_diskName = os.path.basename(
            hou.parm(rop.path() + '/soho_diskfile').eval()).split('.')[0]
        parm_outputDir_IFD = os.path.dirname(
            hou.parm(rop.path() + '/soho_diskfile').eval())
        parm_outputDir_EXR = os.path.dirname(
            hou.parm(rop.path() + '/vm_picture').eval())
        parm_frameStart = int(hou.evalParm(rop.path() + '/f1'))
        parm_frameEnd = int(hou.evalParm(rop.path() + '/f2'))

        g_jobIFD['name'] = "IFD-GEN : %s - %s - %s" % (
            os.environ["USERNAME"], os.environ["HIPNAME"], rop.name())
        g_jobIFD['rop'] = rop.path()
        g_jobIFD['frames'] = "%d - %d" % (parm_frameStart, parm_frameEnd)
        g_jobIFD['files'] = os.environ['HIPFILE']
        g_jobIFD['outdir'] = parm_outputDir_IFD
        g_jobIFD['paused'] = int(sys.argv[2])
        # IFD submission
        print g_jobIFD
        njid = buildCmdLineIFD(g_jobIFD)

        g_jobEXR['name'] = "IFD-REN : %s - %s - %s" % (
            os.environ["USERNAME"], os.environ["HIPNAME"], rop.name())
        files = ""
        # fixing windows inadequacies, create empty files so wildcards work!
        if not os.path.exists(parm_outputDir_IFD):
            os.makedirs(parm_outputDir_IFD)
        for i in range(parm_frameStart, parm_frameEnd + 1):
            filename = '%s/%s.%04d.ifd' % (parm_outputDir_IFD, parm_diskName,
                                           i)
            open(filename, 'a').close()
        files = '"@%s/%s.%s.ifd"' % (parm_outputDir_IFD, parm_diskName, '*')

        g_jobEXR['files'] = files
        g_jobEXR['outdir'] = parm_outputDir_EXR
        g_jobEXR['dep'] = njid
        g_jobEXR['paused'] = int(sys.argv[2])
        # EXR submission
        print g_jobEXR
        buildCmdLineEXR(g_jobEXR)

    hou.releaseLicense()
Пример #14
0
 def p_scale(self, state):
     if state == QtCore.Qt.Checked:
         x = hou.parm('/obj/geo1/attribwrangle_pscale/snippet')
         x.set('@pscale=rand(@ptnum)+.3;')
     else:
         x = hou.parm('/obj/geo1/attribwrangle_pscale/snippet')
         x.set('')
	def testPrimitiveGroupModeWithTransformAttribute( self ) :
		cache = self.cacheSop( file="test/IECoreHoudini/data/torusWithVertexNormals.bgeo" )
		cache.parm( "groupingMode" ).set( 0 )
		hou.parm( "/obj/geo1/group1/entity" ).set( 0 )
		hou.setFrame( 2 )
		orig = IECoreHoudini.FromHoudiniPolygonsConverter( cache ).convert()
		cache.parm( "transformAttribute" ).set( "transform" )
		result = IECoreHoudini.FromHoudiniPolygonsConverter( cache ).convert()
		self.assertNotEqual( orig, result )
		self.assertNotEqual( orig['P'], result['P'] )
		self.assertNotEqual( orig['N'], result['N'] )
		self.assertEqual( orig['P'].data.size(), result['P'].data.size() )
		self.assertEqual( orig['N'].data.size(), result['N'].data.size() )
		self.assertEqual( orig['Cs'], result['Cs'] )
		self.assertEqual( orig['pointId'], result['pointId'] )
		
		i = IECore.InterpolatedCache( cache.parm( "cacheSequence" ).eval(), IECore.InterpolatedCache.Interpolation.Linear, IECore.OversamplesCalculator( 24, 1 ) )
		matrix = i.read( 2, "torus", "transform" ).value.transform
		origP = orig["P"].data
		origN = orig["N"].data
		resultP = result["P"].data
		resultN = result["N"].data
		for i in range( 0, origP.size() ) :
			self.assertNotEqual( resultP[i], origP[i] )
			self.assertNotEqual( resultN[i], origN[i] )
			self.assertEqual( resultP[i], matrix.multVecMatrix( origP[i] ) )
			self.failUnless( resultN[i].equalWithAbsError( matrix.multDirMatrix( origN[i] ), 1e-6 ) )
Пример #16
0
def _checkRenderParameters(parms):
    """Check the values of the render-specific parameters.

    Return True if the values are valid and False otherwise.
    """

    if parms["max_hosts_per_job"] < parms["min_hosts_per_job"]:
        hqrop.displayError(
            "Max. Hosts Per Job must be greater than or equal to "
            "Min. Hosts Per Job.")
        return False
    
    # Check IFD file path.
    if parms["make_ifds"] or not parms["use_output_driver"]:
        if not parms["ifd_path"]:
            if parms["make_ifds"]:
                ifd_path_parm = hou.parm("hq_outputifd")
            elif not parms["use_output_driver"]:
                ifd_path_parm = hou.parm("hq_input_ifd")
            
            ifd_parm_label = ifd_path_parm.parmTemplate().label()
            hqrop.displayError(" ".join(["The value of the", ifd_parm_label,
                               "parameter in\n", hou.pwd().path(), "\n"
                               "must not be blank."]))
            return False

    return True
 def setLG(self,*args):
     aovG = self.main_widget.lineEdit.text()
     if aovG != '':
         global selNodes
         for each in selNodes:
             hou.parm('/obj/' + str(each) + '/ar_aov').set(aovG)
     else:
         self.consoleUpdate("Please Enter a Light Group name.")
Пример #18
0
    def o_rient(self, state):
        if state == QtCore.Qt.Checked:
            x = hou.parm('/obj/geo1/attribwrangle_rotation/snippet')
            x.set('@P.y-=.2;vector axis = {0,1,0};vector nvec = normalize(axis);float rand = fit01(random(@ptnum+311),0,360);vector4 quat = quaternion(radians(rand), nvec);@orient = qmultiply({0,0,0,1}, quat);'
                  )
        else:

            x = hou.parm('/obj/geo1/attribwrangle_rotation/snippet')
            x.set('')
Пример #19
0
def resetParms():
    
    job = hou.parm("job")
    cut = hou.parm("cut")
    
    jobexp = "strcat(strcat(chs(\"client\"),\"/\"),chs(\"project\"))"
    cutexp = "chs(\"shot\")"
        
    job.setExpression(jobexp)
    cut.setExpression(cutexp)   
Пример #20
0
def menuItems():
      
    client = hou.parm("client").eval()
    project = hou.parm("project").eval()
    cut = hou.parm("cut").eval()    
   
    client_path = root
    project_path = os.path.join(root,client)
    cut_path = os.path.join(project_path,project)
               
    return (client_path,project_path,cut_path)
 def getTarget(self,*args):
     self.main_widget.lighttar_list.clear()
     try:
         targNode = hou.selectedNodes()[0]
         self.main_widget.lighttar_list.addItem(str(targNode))
         addNode = '/obj/' + str(targNode) + '/' 
         print(targNode)
         global selNodes
         for each in selNodes:
             hou.parm('/obj/' + str(each) + '/lookatpath').set(addNode)
     except:
         self.consoleUpdate("Please Select a Node to Target.")
 def setExpVal(self,*args):
     
     
     minVal = self.main_widget.MindoubleSpinBox.value()
     maxVal = self.main_widget.MaxdoubleSpinBox.value()
     
     self.consoleUpdate('Setting Exposure Values')
     for each in selNodes:
         if minVal != 0:
             hou.parm('/obj/'+ str(each) +'/ar_intensity').set(minVal)
         if maxVal != 0:    
             hou.parm('/obj/'+ str(each) +'/ar_exposure').set(maxVal)
Пример #23
0
 def reset_all(self):
     switch_input_parm = hou.parm('/obj/geo1//switch2/input')
     switch_input_parm.set(1)
     paint_node = hou.node('/obj/geo1//paint1')
     x = hou.parmTuple('/obj/geo1//paint1/fg')
     x[0].set(0)
     x[1].set(0)
     x[2].set(0)
     hou.parm('/obj/geo1//paint1/flood').pressButton()
     y = hou.parmTuple('/obj/geo1//paint1/bg')
     y[0].set(0)
     y[1].set(0)
     y[2].set(0)
     hou.parm('/obj/geo1//paint1/flood').pressButton()
Пример #24
0
    def dropEvent(self, event):
        text = event.mimeData().text()
        #print event.mimeData().formats()
        parm = hou.parm(text)
        if parm != None:
            if hou.parm(self.pathLabel.text()) !=None:
                self.removeCallBack(hou.parm(self.pathLabel.text()).node())
            if isinstance(parm.eval(),str):
                mime = QtCore.QMimeData()
                mime.setText("")
                newEvent = QtGui.QDropEvent(event.pos(), event.dropAction(), mime, event.mouseButtons(), event.keyboardModifiers())
                super(snippet, self).dropEvent(newEvent)

                self.pathLabel.setText(text)
                self.setText(parm.eval())
                self.pathLabel.setStyleSheet(stylesheet.styles["valid"])

                self.setUpCallback(parm.node())
            else:
                mime = QtCore.QMimeData()
                mime.setText("")
                newEvent = QtGui.QDropEvent(event.pos(), event.dropAction(), mime, event.mouseButtons(), event.keyboardModifiers())
                super(snippet, self).dropEvent(newEvent)
                self.pathLabel.setText("Invalid. Only String Parameter is acceptable:")
                self.pathLabel.setStyleSheet(stylesheet.styles["invalid"])
        else:
            ###
            ### droped info is not path to parm
            ###
            if hou.parm(self.pathLabel.text()) != None:
                ###
                ### parm is already set
                ###
                if hou.node(text) == None:
                    ###
                    ### dropping a template
                    ###
                    self.dropTemplate(event)
                    if hou.parm(self.pathLabel.text()).name() == "snippet":
                        self.parmCreate(hou.parm(self.pathLabel.text()).node())
                else:
                    ###
                    ### dropping node or something
                    ###
                    if hou.parm(self.pathLabel.text()) !=None:
                        self.removeCallBack(hou.parm(self.pathLabel.text()).node())
                    mime = QtCore.QMimeData()
                    mime.setText("")
                    newEvent = QtGui.QDropEvent(event.pos(), event.dropAction(), mime, event.mouseButtons(), event.keyboardModifiers())
                    super(snippet, self).dropEvent(newEvent)
                    self.pathLabel.setText("Invalid. Drop a parameter:")
                    self.pathLabel.setStyleSheet(stylesheet.styles["invalid"])
            else:
                ###
                ### parm is not set
                ###
                self.dropTemplate(event)
                self.pathLabel.setText("Invalid. Drop a parameter first:")
                self.pathLabel.setStyleSheet(stylesheet.styles["invalid"])
    def autoConnect(self, node):
        parm = node.parm("snippet")
        if parm != None:
            if hou.parm(self.pathLabel.text()) != None:
                self.removeCallBack(hou.parm(self.pathLabel.text()).node())
            if isinstance(parm.eval(), str):
                self.pathLabel.setText(parm.path())
                self.setText(parm.eval())
                self.pathLabel.setStyleSheet(stylesheet.styles["valid"])

                self.setUpCallback(parm.node())
            else:
                print("not valid")
        else:
            print("not valid2")
	def __enter__( self ) :
		
		handlers = {
			"Int" : self.__simpleParmHandler,
			"Float" : self.__simpleParmHandler,
			"String" : self.__simpleParmHandler,
		}

		self.__restoreCommands = []
		for parmName, value in self.__parametersAndValues.items() :
			
			# check we can handle this type
			parm = hou.parm( parmName ) or hou.parmTuple( parmName )
			if not parm :
				raise TypeError( "Parameter \"%s\" does not exist." % parmName )
			
			parmType = parm.parmTemplate().dataType().name()
			handler = handlers.get( parmType, None )
			if not handler :
				raise TypeError( "Parameter \"%s\" has unsupported type \"%s\"." % ( parmName, parmType ) )

			# store a command to restore the parameter value later
			self.__restoreCommands.append( parm.asCode() )

			# and change the parameter value
			handler( parm, value )
Пример #27
0
 def tree_length_change(self):
     slider_value = int(self.sender().value())
     treelen = slider_value / 100.00
     tree_length_parm = hou.parm('/obj/deciduoustree1/treesys1_lsystem1_generations'
                                 )
     tree_length_parm.set(treelen)
     self.tree_length_val.setValue(treelen)
Пример #28
0
def cb_btn_change():
    '''Callback function called by "Change" button, and "start" function for initialization.'''
    
    parmPath = gDIALOG.value('strField_tarParm.val')
    parm = hou.parm(parmPath)
    if parm:
        script = gDIALOG.value('strField_newScript.val')
        houLang = INDEX_TO_HOULANG[gDIALOG.value('menu_lang.val')]
        
        if script:
            # Edit parameter template.
            templ = parm.parmTemplate()
            templ.setScriptCallback(script)
            templ.setScriptCallbackLanguage(houLang)

            # Replace parameter by edited template.
            result = parm.node().replaceSpareParmTuple(parm.name(), templ)
            if result:
                print ''
                print '[chpc - cb_btn_change] Callback information has been updated!'
                print '[chpc log] %s %s callback script: %s | %s' % (strftime('%H:%M:%S', localtime()), parmPath, houLang.name(), script)
            else:
                print '[chpc - cb_btn_change] Warning! Can not change callback information!'
        else:
            hou.ui.displayMessage('Empty script, skip writing!', title=UI_TITLE)
    else:
        hou.ui.displayMessage('Invalid parameter path!', title=UI_TITLE)
Пример #29
0
def dropdown_menu(kwargs, roptype):
    try:
        node = kwargs['node']
        ropque = kwargs['parm'].name()

        button = []
        que = str(re.findall('\d+', ropque)[0])
        roppath = node.evalParm(roptype + que)
        ropnode = hou.node(roppath)
        ropparm = hou.parm(roppath)

        if ropnode != None:
            buttonList = [
                p for p in ropnode.parms()
                if p.parmTemplate().type() == hou.parmTemplateType.Button
            ]
            #toggles = [p for p in node.parms() if isinstance(p.parmTemplate(), hou.ButtonParmTemplate)]
            for parm in buttonList:
                if str(parm.name()) != 'renderdialog':
                    button.extend([str(parm.name()), str(parm.description())])
        elif ropparm != None:
            button = [str(ropparm.name()), str(ropparm.description())]
        else:
            if roptype == 'rop':
                button = [
                    'execute', 'Render', 'reload', 'Reload', 'renderpreview',
                    'Render To Mplay', 'executebackground',
                    'Render in Background'
                ]
            else:
                button = ['execute', 'Please assign rop']

        return button
    except:
        return ['execute', 'Please assign rop']
Пример #30
0
    def copy(self, name="", set_current=False):
        '''
            Return a copy of that take and add it to the list of take.
        '''
        if self.name not in _listTakeNames():
            raise TakeError("Can not find take: " + self.name)
        
        if not name:
            name = self.name + "_copy"
            
        out_take = Take(name)
        for k in self.take_members:
            
            p = hou.parm(k)
            if p is None:
                p = hou.parmTuple(k)

            if p is None:
                continue

            out_take.includeParms(k, self.take_members[k])
        
        if set_current:
            setTake(name)
        else:
            returnToMainTake()
        
        return out_take
Пример #31
0
 def __init__(self, chPath, minFrame, maxFrame):
     self.path = chPath
     self.data = []
     prm = hou.parm(chPath)
     for fno in xrange(minFrame, maxFrame + 1):
         val = prm.evalAtFrame(fno)
         self.data.append(val)
Пример #32
0
    def blend(self, blend):
        animEdit = None
        for pane in hou.ui.currentPaneTabs():
            if pane.type() == hou.paneTabType.ChannelEditor:
                animEdit = pane

        if animEdit:
            graph = animEdit.graph()
            keyframes = graph.selectedKeyframes()
            # if there are keyframes selected
            # tween those
            if keyframes:
                for parm in keyframes.keys():
                    for key in keyframes[parm]:
                        tween(parm, key.frame(), blend)
                return

        # otherwise, just use the scoped / visible channels at the current time
        scope = hou.hscript("chscope")[0]
        for x in scope.split():
            chan = hou.parm(x)
            # only operate on channels that are visible in the graph editor
            if chan.isSelected():
                with hou.undos.group('tweenmachine'):
                    tween(chan, hou.frame(), blend)
Пример #33
0
    def copy(self, name="", set_current=False):
        '''
            Return a copy of that take and add it to the list of take.
        '''
        if self.name not in _listTakeNames():
            raise TakeError("Can not find take: " + self.name)

        if not name:
            name = self.name + "_copy"

        out_take = Take(name)
        for k in self.take_members:

            p = hou.parm(k)
            if p is None:
                p = hou.parmTuple(k)

            if p is None:
                continue

            out_take.includeParms(k, self.take_members[k])

        if set_current:
            setTake(name)
        else:
            returnToMainTake()

        return out_take
Пример #34
0
def setTexture():
    # set new texture
    texturePath = "$HIP/tex/" + newName + ".tif"
    # assign new texture
    print texturePath
    shader1 = hou.parm("/shop/Packshot/Texture/tex0")
    shader1.set(texturePath)
    return
Пример #35
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)
Пример #36
0
def watchlist_write():
    def set_string_attrib(attrib_name, attrib_val):
        if not geo.findGlobalAttrib(attrib_name):
            geo.addAttrib(hou.attribType.Global,
                          attrib_name,
                          '',
                          create_local_variable=False)
        geo.setGlobalAttribValue(attrib_name, attrib_val)

    node = hou.pwd()
    parent = node.parent()
    geo = node.geometry()

    set_string_attrib('hipfile_path', parent.evalParm('hipfile_path'))
    set_string_attrib('hipfile_date', parent.evalParm('hipfile_date'))
    set_string_attrib('hipfile_project', parent.evalParm('hipfile_project'))
    set_string_attrib('hipfile_source', parent.evalParm('hipfile_source'))
    set_string_attrib('hipfile_error', parent.evalParm('hipfile_error'))

    watch_metadata = {}
    num_watch_nodes = parent.evalParm('watchlist_parms')
    for n in range(num_watch_nodes):
        watch_node = parent.parm('watch_node_{0}'.format(n + 1)).evalAsNode()

        if not watch_node:
            continue
        watch_node_path = watch_node.path()

        watch_metadata[watch_node_path] = {}

        num_watch_parms = parent.evalParm('watch_parms_{0}'.format(n + 1))
        for p in range(num_watch_parms):
            key = parent.evalParm('watch_parm_{0}_{1}'.format(n + 1, p + 1))

            watch_parm = hou.parm('{0}/{1}'.format(watch_node_path, key))
            if not watch_parm:
                continue

            has_keyframe = len(watch_parm.keyframes()) > 0

            try:
                watch_parm.expression()
                is_expr = True
            except hou.OperationFailed:
                is_expr = False

            if has_keyframe and not is_expr:
                val = ('<< Animated Parameter >>', '<< Animated Parameter >>')
            else:
                val = (watch_parm.eval(), watch_parm.evalAsString())

            watch_metadata[watch_node_path][key] = val

    _watch_metadata = json.dumps(watch_metadata)
    set_string_attrib('watchlist', _watch_metadata)

    return
Пример #37
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)
Пример #38
0
def getCallbackInfo(parmPath):
    '''Function used to get callback information, such as script and language.'''

    parm = hou.parm(parmPath)
    parmTemp = parm.parmTemplate()
    
    script = parmTemp.scriptCallback()
    language = parmTemp.scriptCallbackLanguage().name()
    
    return (script, language)
Пример #39
0
	def testBrokenSop( self ) :
		
		scene = self.buildScene()
		boxNode = hou.node( "/obj/box1" )
		box1 = scene.scene( [ "sub1", "box1" ] )
		self.assertEqual( box1.hasObject(), True )
		mesh = box1.readObject( 0 )
		self.failUnless( isinstance( mesh, IECore.MeshPrimitive ) )
		self.assertEqual( mesh["P"].data.size(), 8 )
		self.assertEqual( box1.childNames(), [ "gap" ] )
		self.assertTrue( isinstance( box1.child( "gap" ), IECoreHoudini.LiveScene ) )
		
		# forcing a cook error
		hou.parm('/obj/box1/actualBox/sizex').setExpression( "fake" )
		self.assertEqual( box1.hasObject(), False )
		self.assertEqual( box1.readObject( 0 ), None )
		self.assertEqual( box1.childNames(), [] )
		self.assertRaises( RuntimeError, box1.child, "gap" )
		self.assertEqual( box1.child( "gap", IECore.SceneInterface.MissingBehaviour.NullIfMissing ), None )
		self.assertRaises( hou.OperationFailed, box1.node().renderNode().cook )
Пример #40
0
	def testBrokenSop( self ) :
		
		scene = self.buildScene()
		boxNode = hou.node( "/obj/box1" )
		box1 = scene.scene( [ "sub1", "box1" ] )
		self.assertEqual( box1.hasObject(), True )
		mesh = box1.readObject( 0 )
		self.failUnless( isinstance( mesh, IECore.MeshPrimitive ) )
		self.assertEqual( mesh["P"].data.size(), 8 )
		self.assertEqual( box1.childNames(), [ "gap" ] )
		self.assertTrue( isinstance( box1.child( "gap" ), IECoreHoudini.LiveScene ) )
		
		# forcing a cook error
		hou.parm('/obj/box1/actualBox/sizex').setExpression( "fake" )
		self.assertEqual( box1.hasObject(), False )
		self.assertEqual( box1.readObject( 0 ), None )
		self.assertEqual( box1.childNames(), [] )
		self.assertRaises( RuntimeError, box1.child, "gap" )
		self.assertEqual( box1.child( "gap", IECore.SceneInterface.MissingBehaviour.NullIfMissing ), None )
		self.assertRaises( hou.OperationFailed, box1.node().renderNode().cook )
 def cdSet(self,chan):
     global cdR, cdG, cdB 
     #Get Value from Channel
     if chan == 'r':
         cdV = float(self.main_widget.Cd_Slider_R.value())/100
         self.main_widget.r_out.setText("R: " + str(cdV))
         cdR = cdV
     elif chan == 'g':
         cdV = float(self.main_widget.Cd_Slider_G.value())/100
         self.main_widget.g_out.setText("G: " + str(cdV))
         cdG = cdV
     elif chan == 'b':
         cdV = float(self.main_widget.Cd_Slider_B.value())/100
         self.main_widget.b_out.setText("B: " + str(cdV))
         cdB = cdV
     #Update Cd
     self.cdMapper()
     #Update Node Tree
     for each in selNodes:
         hou.parm('/obj/'+ str(each) +'/ar_color' + chan).set(cdV)
Пример #42
0
def newGeo(hpath):
    templateNode = hou.node(hpath).createNode("geometryTemplate")
    alist = listContainers()
    ok, resp = hou.ui.readInput("Enter the New Operator Label", buttons=('OK', 'Cancel'), title="OTL Label")
    filename = str()
    if ok == 0 and resp.strip() != '':
        name = formatName(resp)
        filename = name.replace(' ', '_')
        templateNode.setName(filename, unique_name=True)
    answer = hou.ui.selectFromList(alist, exclusive=True, message='Select Container Asset this belongs to:')
    if not answer:
        hou.ui.displayMessage("Geometry must be associated with a container asset! Geometry asset not created.", severity=hou.severityType.Error)
        templateNode.destroy()
        return
    answer = answer[0]
    sdir = '$JOB/PRODUCTION/assets/'
    gfile = hou.ui.selectFile(start_directory=sdir + alist[answer]+'/geo', title='Choose Geometry', chooser_mode=hou.fileChooserMode.Read)
    if len(gfile) > 4 and gfile[:4] != '$JOB':
        hou.ui.displayMessage("Path must start with '$JOB'. Default geometry used instead.", title='Path Name', severity=hou.severityType.Error)
        templateNode.destroy()
    elif gfile != '':
        hou.parm(templateNode.path() + '/read_file/file').set(gfile)
Пример #43
0
def newGeo(hpath):
    templateNode = hou.node(hpath).createNode("geometryTemplate")
    alist = listContainers()
    response = hou.ui.readInput("Enter the New Operator Label", title="OTL Label", buttons=("OK", "Cancel"))
    filename = str()
    if response[0] == 0:
        name = response[1]
    else:
        name = None
    if name != None and name.strip() != "":
        name = formatName(name)
        filename = name.replace(" ", "_")
        templateNode.setName(filename, unique_name=True)
    answer = hou.ui.selectFromList(alist, message="Select Container Asset this belongs to:", exclusive=True)
    if not answer:
        hou.ui.displayMessage(
            "Geometry must be associated with a container asset! Geometry asset not created.",
            severity=hou.severityType.Error,
        )
        templateNode.destroy()
        return
    answer = answer[0]
    sdir = os.environ["ASSETS_DIR"]
    gfile = hou.ui.selectFile(
        start_directory=os.path.join(sdir, alist[answer] + "/geo"),
        title="Choose Geometry",
        chooser_mode=hou.fileChooserMode.Read,
        pattern="*.bjson, *.obj",
    )
    if len(gfile) > 4 and gfile[:4] != "$JOB":
        hou.ui.displayMessage(
            "Path must start with '$JOB'. Default geometry used instead.",
            title="Path Name",
            severity=hou.severityType.Error,
        )
        templateNode.destroy()
    elif gfile != "":
        hou.parm(templateNode.path() + "/read_file/file").set(gfile)
Пример #44
0
def set_parms_in_take(parmsDict, node = None):
    """
    Set values of parms in a take.
    parmsDict contains pairs of parms and values.
    ex.{'tx': '0', 'ty':'1', 'tz':2}
    If no node provided, the keys of parmDict have to be
    parm absolute paths.
    """
    for parm_name in parmsDict:
        if not node:
            node = hou.parm(parm_name).node()
        hou.hscript('takeinclude {0} {1}'.format(node.path(), parm_name))
        try:
            node.parm(parm_name).set(parmsDict[parm_name])
        except AttributeError:
            print 'Unable to set parameter: {0}/{1}'.format(node.path(), parm_name)
Пример #45
0
    def getUnexpandedStringPath(self, path, node_type, node_cat):
        for item in Define.CACHE_NODES:

            if not node_cat == item.get("cat"):
                continue

            if node_type == item.get("name"):
                parmName = item.get("parmName")
                break

        try:
            parmPath = path + '/' + parmName
            unExpPath = hou.parm(parmPath).unexpandedString()
            return unExpPath

        except:
            return "Error: definition error"
Пример #46
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)
 def dropEvent(self, event):
     event.acceptProposedAction()
     event.accept()
     if  event.mimeData().hasText():
         mim = event.mimeData()
         text = mim.text()
         p = hou.parm(text)
         if p:
             if type(p) == hou.Parm:
                 if p.parmTemplate().type() == hou.parmTemplateType.String:
                     exists = self.tab.check_exists_tab(parm=p)
                     if not exists is None:
                         self.show_status_message('Parameter allready opened')
                         self.tab.setCurrentIndex(exists)
                     else:
                         t = self.tab.add_tab()
                         self.tab.assign_tab_reference(t, parm=p)
     QMainWindow.dropEvent(self,event)
Пример #48
0
	def parms(self):
		
		'''returns a tuple of hou.parms'''
		hscript_cmd = 'takels  -i -l ' + self._name
		hscript_cmd_results = hou.hscript(hscript_cmd)
		
		if _takeErr(hscript_cmd_results[1]):
			result = None
		else: 
			parm_names_paths = hscript_cmd_results[0].split('\n')
			parm_names_paths = [x for x in parm_names_paths if x!='']
			parm_names_paths.remove(self._name)

			# make parm objects
			parms = []
			for parm_names_path in parm_names_paths:
				
				node_path = parm_names_path.split(' ',1)[0]
				parm_names = parm_names_path.split(' ',1)[1].split()
				
				for parm_name in parm_names:
					if '-flag' in parm_name:
						continue
					
					parm = hou.parm(node_path + '/' + parm_name)
					
					if parm == None:
						parm = hou.parmTuple(node_path + '/' + parm_name)
						if parm == None:
							msg = "unable to resolve parm object for: "+node_path + '/' + parm_name
							print >> sys.stderr, msg
							continue
						
						else: [parms.append(i) for i in parm]

					else: parms.append(parm)

			if len(parms) == 0:
				result = None
			else: result = tuple(parms)

		return result
Пример #49
0
def blackAssign():
############ create black shader ####
    if blackShader.name() == "constant_black":
        blackShader.destroy()
        constant = hou.galleries.galleryEntries('constant')[0]
        constant.createChildNode(hou.node("/shop")).setName('constant_black')
        hou.parmTuple('/shop/constant_black/difclr').set((0,0,0))
    else:
        constant = hou.galleries.galleryEntries('constant')[0]
        constant.createChildNode(hou.node("/shop")).setName('constant_black')
        hou.parmTuple('/shop/constant_black/difclr').set((0,0,0))    

############# select objects assign black shader ##################    
    candidateObjects = hou.parm('vobject')
    canEval = candidateObjects.eval()
    allNodes = hou.node("/obj").recursiveGlob(canEval, filter=hou.nodeTypeFilter.ObjGeometry)
    #print allNodes   
    for i in allNodes:
        objNode = hou.node("/obj/" + str(i))
        print i
        objNode.setParms({"/obj/" + str(i) + "/shop_materialpath": '/shop/constant_black'})
Пример #50
0
def bAssign():
    
    #### create red shader ####
    if blueShader.name() == "constant_blue":
        blueShader.destroy()
        constant = hou.galleries.galleryEntries('constant')[0]
        constant.createChildNode(hou.node("/shop")).setName('constant_blue')
        hou.parmTuple('/shop/constant_blue/difclr').set((0,0,1))
    else:
        constant = hou.galleries.galleryEntries('constant')[0]
        constant.createChildNode(hou.node("/shop")).setName('constant_blue')
        hou.parmTuple('/shop/constant_blue/difclr').set((0,0,1))
        
    ##### assign red shader #####
    blueParm = hou.parm('blue_matte')
    blueList = blueParm.eval()
    allNodes = hou.node("/obj").recursiveGlob(blueList, filter=hou.nodeTypeFilter.ObjGeometry)
    #print allNodes   
    for i in allNodes:
        objNode = hou.node("/obj/" + str(i))
        print i
        objNode.setParms({"/obj/" + str(i) + "/shop_materialpath": '/shop/constant_blue'})
Пример #51
0
def gAssign():
    
    #### create red shader ####
    if greenShader.name() == "constant_green":
        greenShader.destroy()
        constant = hou.galleries.galleryEntries('constant')[0]
        constant.createChildNode(hou.node("/shop")).setName('constant_green')
        hou.parmTuple('/shop/constant_green/difclr').set((0,1,0))
    else:
        constant = hou.galleries.galleryEntries('constant')[0]
        constant.createChildNode(hou.node("/shop")).setName('constant_green')
        hou.parmTuple('/shop/constant_green/difclr').set((0,1,0))
        
    ##### assign red shader #####
    greenParm = hou.parm('green_matte')
    greenList = greenParm.eval()
    allNodes = hou.node("/obj").recursiveGlob(greenList, filter=hou.nodeTypeFilter.ObjGeometry)
    #print allNodes   
    for i in allNodes:
        objNode = hou.node("/obj/" + str(i))
        print i
        objNode.setParms({"/obj/" + str(i) + "/shop_materialpath": '/shop/constant_green'})
Пример #52
0
    def test_varChange(self):
        parm = hou.parm("/obj/test_varChange/file1/file")

        string = "something_$VARCHANGE.bgeo"

        parm.set(string)

        path = parm.eval()

        self.assertEqual(path, string.replace("$VARCHANGE", ""))

        hou.setVariable("VARCHANGE", 22)

        hou.varChange()

        newPath = parm.eval()

        # Test the paths aren't the same.
        self.assertNotEqual(path, newPath)

        # Test the update was successful.
        self.assertEqual(newPath, string.replace("$VARCHANGE", "22"))
Пример #53
0
def rAssign():
    
    #### create red shader ####
    if redShader.name() == "constant_red":
        redShader.destroy()
        constant = hou.galleries.galleryEntries('constant')[0]
        constant.createChildNode(hou.node("/shop")).setName('constant_red')
        hou.parmTuple('/shop/constant_red/difclr').set((1,0,0))
    else:
        constant = hou.galleries.galleryEntries('constant')[0]
        constant.createChildNode(hou.node("/shop")).setName('constant_red')
        hou.parmTuple('/shop/constant_red/difclr').set((1,0,0))
        
    ##### assign red shader #####
    redParm = hou.parm('red_matte')
    redList = redParm.eval()
    allNodes = hou.node("/obj").recursiveGlob(redList, filter=hou.nodeTypeFilter.ObjGeometry)
    #print allNodes   
    for i in allNodes:
        objNode = hou.node("/obj/" + str(i))
        print i
        objNode.setParms({"/obj/" + str(i) + "/shop_materialpath": '/shop/constant_red'})
Пример #54
0
def cb_btn_getParmCallback():
    '''Callback function called by "Get Parameter Callback info" button.'''
    
    # Check if the parameter path is valid or not.
    path = getParmPath()
    if path:
        # Check if target parameter is a valid spare parameter of its node.
        parm = hou.parm(path)
        if parm in parm.node().spareParms():
            # Target parameter string field.
            gDIALOG.enableValue('strField_tarParm.val', True)
            gDIALOG.setValue('strField_tarParm.val', path)
            #gDIALOG.enableValue('strField_tarParm.val', False)

            # Old script string field, and language menu item.
            script, lang = getCallbackInfo(path)
            gDIALOG.setValue('strField_oldScript.val', script)
            gDIALOG.setValue('menu_lang.val', LANG_TO_INDEX[lang])
        else:
            hou.ui.displayMessage('This parameter is not allow to edit!', title=UI_TITLE)
    else:
        hou.ui.displayMessage('No parameter copied!', title=UI_TITLE)

    gDIALOG.enableValue('strField_tarParm.val', False)
Пример #55
0
def bakeTransforms(pathToSource, pathToDest, startSampleFrame, endSampleFrame, stepFrame):
        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)+')'
                hexprRX = 'chf(\"'+pathToSource+'\"/rx,'+str(frame)+')'
                hexprRY = 'chf(\"'+pathToSource+'\"/ry,'+str(frame)+')'
                hexprRZ = 'chf(\"'+pathToSource+'\"/rz,'+str(frame)+')'						
                retvalTX = hou.hscriptExpression(hexprTX)
                retvalTY = hou.hscriptExpression(hexprTY)
                retvalTZ = hou.hscriptExpression(hexprTZ)
                retvalRX = hou.hscriptExpression(hexprTX)
                retvalRY = hou.hscriptExpression(hexprTY)
                retvalRZ = hou.hscriptExpression(hexprTZ)				
		
                TX = float(retvalTX)
                TY = float(retvalTY)
                TZ = float(retvalTZ)
                RX = float(retvalRX)
                RY = float(retvalRY)
                RZ = float(retvalRZ)
						
                frameValList.append((frame, (TX, TY, TZ, RX, RY, RZ)))
		
        #make keys:
	pathToDestTX = pathToDest+"/tx"
	pathToDestTY = pathToDest+"/ty"
	pathToDestTZ = pathToDest+"/tz"
	pathToDestRX = pathToDest+"/rx"
	pathToDestRY = pathToDest+"/ry"
	pathToDestRZ = pathToDest+"/rz"
	
        parmTX = hou.parm(pathToDestTX)
        parmTX.deleteAllKeyframes()

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

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

        parmRX = hou.parm(pathToDestRX)
        parmRX.deleteAllKeyframes()

        parmRY = hou.parm(pathToDestRY)
        parmRY.deleteAllKeyframes()

        parmRZ = hou.parm(pathToDestRZ)
        parmRZ.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)

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

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

                key = hou.Keyframe()
                key.setFrame(frameVal[0])
                key.setValue(frameVal[1][5])
                parmRZ.setKeyframe(key)
Пример #56
0
def bakeChopTransforms(pathToChop="/obj/cam_master/hdfchopNet/exportCamChop/cam_main_orig_mm", pathToNode="/obj/fx_cam_meters", startFrame=1003, endFrame=1564, stepFrame=1):
        #sample chop:
        frameValList = []
	pathToChopTX = pathToChop + "/tx"
	pathToChopTY = pathToChop + "/ty"
	pathToChopTZ = pathToChop + "/tz"
	pathToChopRX = pathToChop + "/rx"
	pathToChopRY = pathToChop + "/ry"
	pathToChopRZ = pathToChop + "/rz"		
        for frame in range(startSampleFrame, endSampleFrame, stepFrame):		
                hexpr = 'chopf(\"'+pathToChopTX+'\",'+str(frame)+')'
                retval = hou.hscriptExpression(hexpr)
                valTX = float(retval)		
                hexpr = 'chopf(\"'+pathToChopTY+'\",'+str(frame)+')'
                retval = hou.hscriptExpression(hexpr)
                valTY = float(retval)
                hexpr = 'chopf(\"'+pathToChopTZ+'\",'+str(frame)+')'
                retval = hou.hscriptExpression(hexpr)
                valTZ = float(retval)
                hexpr = 'chopf(\"'+pathToChopRX+'\",'+str(frame)+')'
                retval = hou.hscriptExpression(hexpr)
                valRX = float(retval)
                hexpr = 'chopf(\"'+pathToChopRY+'\",'+str(frame)+')'
                retval = hou.hscriptExpression(hexpr)
                valRY = float(retval)
                hexpr = 'chopf(\"'+pathToChopRZ+'\",'+str(frame)+')'
                retval = hou.hscriptExpression(hexpr)
                valRZ = float(retval)			
                frameValList.append((frame, (valTX, valTY, valTZ, valRX, valRY, valRZ)))
		
        #make keys:
        parmTX = hou.parm(pathToNode+"/tx")
        parmTX.deleteAllKeyframes()
        parmTY = hou.parm(pathToNode+"/ty")
        parmTY.deleteAllKeyframes()
        parmTZ = hou.parm(pathToNode+"/tz")
        parmTZ.deleteAllKeyframes()
        parmRX = hou.parm(pathToNode+"/rx")
        parmRX.deleteAllKeyframes()
        parmRY = hou.parm(pathToNode+"/ry")
        parmRY.deleteAllKeyframes()
        parmRZ = hou.parm(pathToNode+"/rz")
        parmRZ.deleteAllKeyframes()


        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)
                key = hou.Keyframe()
                key.setFrame(frameVal[0])
                key.setValue(frameVal[1][3])
                parmRX.setKeyframe(key)
                key = hou.Keyframe()
                key.setFrame(frameVal[0])
                key.setValue(frameVal[1][4])
                parmRY.setKeyframe(key)
                key = hou.Keyframe()
                key.setFrame(frameVal[0])
                key.setValue(frameVal[1][5])
                parmRZ.setKeyframe(key)
Пример #57
0
def render():
    """Evaluate and package the HDA parameters and submit a job to HQueue.""" 
    # Build a dictionary of base parameters and add the HQueue Render-specific
    # ones.
    parms = hqrop.getBaseParameters()
    
    use_cloud = (hou.ch("hq_use_cloud1")
        if hou.parm("hq_use_cloud1") is not None else 0)
    num_cloud_machines = (hou.ch("hq_num_cloud_machines")
        if hou.parm("hq_num_cloud_machines") is not None else 0)
    machine_type = (hou.ch("hq_cloud_machine_type")
        if hou.parm("hq_cloud_machine_type") is not None else "")
    use_output_driver = bool(use_cloud) or parms["hip_action"] != "use_ifd"

    # validate the machine type
    if machine_type not in ['c1.medium', 'c1.xlarge',
                            'm1.small', 'm1.large', 'm1.xlarge']:
        machine_type = 'c1.xlarge'

    
    parms.update({
        "assign_ifdgen_to" : hou.parm("hq_assign_ifdgen_to").evalAsString(),
        "ifdgen_clients": hou.ch("hq_ifdgen_clients").strip(),
        "ifdgen_client_groups" : hou.ch("hq_ifdgen_client_groups").strip(),
        "batch_all_frames": hou.ch("hq_batch_all_frames"),
        "frames_per_job": hou.ch("hq_framesperjob"),
        "render_frame_order": hou.parm("hq_render_frame_order").evalAsString(),
        "make_ifds": hou.ch("hq_makeifds"),
        "max_hosts_per_job": hou.ch("hq_max_hosts"),
        "min_hosts_per_job": hou.ch("hq_min_hosts"),
        "is_CPU_number_set": bool(hou.ch("hq_is_CPU_number_set")),
        "CPUs_to_use": hou.ch("hq_CPUs_to_use"),
        "output_ifd": hou.parm("hq_outputifd").unexpandedString().strip(),
        "use_output_driver" : use_output_driver,
        "use_cloud": use_cloud,
        "num_cloud_machines": num_cloud_machines,
        "cloud_machine_type" : machine_type,
        "use_render_tracker" : hou.ch("hq_use_render_tracker"),
        "delete_ifds": hou.ch("hq_delete_ifds"),
        "render_single_tile": bool(hou.ch("hq_render_single_tile")),
    })

    if use_output_driver:
        # Convert output_driver path to an absolute path.
        parms["output_driver"] = hou.ch("hq_driver").strip()
        rop_node = hou.pwd().node(parms["output_driver"])
        if rop_node:
            parms["output_driver"] = rop_node.path()

        parms["ifd_path"] = hou.parm("hq_outputifd").unexpandedString().strip()
        output_driver = hqrop.getOutputDriver(hou.pwd())

        # Turn "off" Mantra-specific parameters if there is an output driver
        # and it is not a Mantra ROP.
        if output_driver and output_driver.type().name() != "ifd":
            parms["make_ifds"] = False
            parms["min_hosts_per_job"] = 1
            parms["max_hosts_per_job"] = 1
    else:
        parms.update({
            "ifd_path" : hou.parm("hq_input_ifd").unexpandedString().strip(),
            "start_frame" : hou.ch("hq_frame_range_1"),
            "end_frame" : hou.ch("hq_frame_range_2"),
            "frame_skip" : hou.ch("hq_frame_range_3"),
            # If we are not using an output driver we are using IFDs and so
            # we won't be making them
            "make_ifds" : False,
        })

        if parms["frame_skip"] <= 0:
            parms["frame_skip"] = 1
 
    # We stop if we cannot establish a connection with the server
    if (not parms["use_cloud"]
        and not hqrop.doesHQServerExists(parms["hq_server"])):
        return None

    if "ifd_path" in parms and not parms["use_cloud"]:
        expand_frame_variables = False
        parms["ifd_path"] = hqrop.substituteWithHQROOT(
            parms["hq_server"], parms["ifd_path"], expand_frame_variables)

    # Validate parameter values.
    if (not hqrop.checkBaseParameters(parms) or
            not _checkRenderParameters(parms)):
        return
    if use_output_driver and parms["hip_action"] == "use_current_hip":
        if not hqrop.checkOutputDriver(parms["output_driver"]):
            return
        if hqrop.checkForRecursiveChain(hou.pwd()):
            hqrop.displayError(("Cannot submit HQueue job because"
                                " %s is in the input chain of %s.") 
                                % (hou.pwd().path(), parms["output_driver"]))
            return

    # If we're not supposed to run this job on the cloud, submit the job.
    # Otherwise, we'll display the file dependency dialog.
    if parms["use_cloud"]:
        # We don't want to keep the interrupt dialog open, so we exit this soho
        # script so the dialog closes and schedule an event to run the code to
        # display the dialog.
        import soho
        rop_node = hou.node(soho.getOutputDriver().getName())
        cloud.selectProjectParmsForCloudRender(
            rop_node, parms["num_cloud_machines"], parms["cloud_machine_type"])
        return

    # Automatically save changes to the .hip file,
    # or at least warn the user about unsaved changes.
    should_continue = hqrop.warnOrAutoSaveHipFile(parms)
    if not should_continue:
        return

    hqrop.submitJob(parms, _byu_troubleshoot_hq)
Пример #58
0
    def restore_tabs_from_hip(self):
        node = hou.node('obj/'+tabsNodeName)
        if not node:
            self.messageSignal.emit('Saved tabs not found')
            return
        ptg = node.parmTemplateGroup()
        tabs = []
        for i in range(len(ptg.entries())):
            type = node.parm('type%s' % i)
            path = node.parm('path%s' % i)
            text = node.parm('text%s' % i)
            if all([type, path, text]):
                tabs.append(dict(
                    type=type.eval(),
                    path=path.eval(),
                    text=text.eval()
                ))
        if tabs:
            errors = []
            for tab in tabs:
                if tab['type'] == 'parm':
                    parm = hou.parm(tab['path'])
                    if parm:
                        t = self.add_tab()
                        self.assign_tab_reference(t, parm=parm)
                        t.edit.setText(tab['text'])
                    else:
                        t = self.add_tab()
                        t.edit.setText(('!!! ERROR\n!!! PARAMETER NOT FOUND: %s\n\n' % tab['path']) + tab['text'])
                        errors.append(tab)

                elif tab['type'] == 'section':
                    name, sect = tab['path'].split('/')
                    definition = self.get_definition(name)
                    if definition:
                        if sect in definition.sections().keys():
                            section = definition.sections()[sect]
                            t = self.add_tab()
                            self.assign_tab_reference(t, section=section)
                            t.edit.setText(tab['text'])
                            continue
                    t = self.add_tab()
                    t.edit.setText(('!!! ERROR\n!!! SECTION OR DEFINITION NOT FOUND: %s\n\n' % tab['path']) + tab['text'])
                    errors.append(tab)

                elif tab['type'] == 'file':
                    if os.path.exists(tab['path']):
                        t = self.add_tab()
                        self.assign_tab_reference(t, filepath=tab['path'])
                        t.edit.setText(tab['text'])
                    else:
                        t = self.add_tab()
                        t.edit.setText(('!!! ERROR\n!!! FILE NOT FOUND: %s\n\n' % tab['path']) + tab['text'])
                        errors.append(tab)
                elif tab['type'] == 'empty':
                    t = self.add_tab()
                    t.edit.setText(tab['text'])
        ind_parm = node.parm('tabs_active_index')
        if ind_parm:
            i = ind_parm.eval()
            if i < self.count():
                self.setCurrentIndex(i)

        QTimer.singleShot(100,self.update_info)
Пример #59
0
def importDataFromXmlToAbc():
# select Alembic archive #    
    abc = lastSelectedNode()
    if abc is None:
	hou.ui.setStatusMessage("Select one root Alembic Archive node.")
	hou.ui.displayMessage("No root Alembic Archive node has been selected. Select one.", title="Attention, monsieur!")
	return None
    if abc.type() == hou.nodeType(hou.objNodeTypeCategory(), 'alembicarchive'):
	print "Alembic Archive found"
    else:
	print "No Alembic Archive selected"

# XML stuff #
    #file_name = "/home/max/exported_data.xml"
    hou.ui.setStatusMessage("Choose XML file to import textures from.")
    file_name = hou.ui.selectFile(start_directory="/mnt/karramba/", title="Choose XML", pattern="*.xml")
    if file_name == "":
	return None
    file_name = os.path.expandvars(file_name)
    xml = parse(file_name)
    xmlobjects = xml.getElementsByTagName("object")
    
# parse and assign textures #	
    stat_assigned = 0
    stat_noshader = 0
    stat_newshader = 0
    i = 0
    for obj in xmlobjects:
        object_name = obj.getElementsByTagName("object_name")[0]
        object_path = object_name.childNodes[0].data
        #print object_path
        object_path = object_path.replace('|', '/')
        print object_path
        object_fullpath = abc.path() + object_path
        print object_fullpath

#get texture data from XML        
        object_texture_color = obj.getElementsByTagName("texture_color")[0]
        texture_path_color = object_texture_color.childNodes[0].data
        
        object_texture_spec = obj.getElementsByTagName("texture_spec")[0]
        texture_path_spec = object_texture_spec.childNodes[0].data
        
        object_texture_bump = obj.getElementsByTagName("texture_bump")[0]
        texture_path_bump = object_texture_bump.childNodes[0].data

#create shader if needed        
        if hou.parm(str(object_fullpath) + "/shop_materialpath") is None:
            shader_template = hou.galleries.galleryEntries("mantrasurface")[0]
            shader[i] = shader_template.createChildNode(hou.node("shop"))
            shader[i].setName(object_name)
            stat_newshader = stat_newshader + 1

        if hou.parm(str(object_fullpath) + "/shop_materialpath") is not None:
            object_shader = hou.parm(str(object_fullpath) + "/shop_materialpath").evalAsString()
            #object_shader = hou.node(str(object_fullpath)).evalParm("shop_materialpath")
            if hou.node(object_shader) is not None:
                if hou.node(object_shader).parm("baseColorMap") is not None:
                    hou.node(object_shader).parm("baseColorMap").set(str(texture_path_color))
                if hou.node(object_shader).parm("baseSpecMap") is not None:
                    hou.node(object_shader).parm("baseSpecMap").set(str(texture_path_spec))
                if hou.node(object_shader).parm("baseDispMap") is not None:
                    hou.node(object_shader).parm("baseDispMap").set(str(texture_path_bump))
                stat_assigned = stat_assigned + 1
            else:
                print object_fullpath + ": Shader assigned, but doesn't exist."
                stat_noshader = stat_noshader + 1
        i+=1

    print str(stat_assigned) + " textures assigned successfully."
    print str(stat_newshader) + " shaders created."
    print str(stat_noshader) + " shaders assigned, but not found."