def export_renderer_output(node):
    """
    """
    module_logger.debug("RendererOutputExport - export_renderer_output()")

    export_logger = logging.getLogger(
        "katana_addons.Plugins.RendererOutputExport.Export")
    export_logger.setLevel(int(
        node.getParameter("Debug.logLevel").getValue(0)))

    from PyUtilModule import NodeDebugOutput

    export_geometry_producer = Nodes3DAPI.GetGeometryProducer(node)
    renderer = (export_geometry_producer.getAttribute(
        "renderSettings.renderer").getValue()
                or RenderingAPI.RenderPlugins.GetDefaultRendererPluginName())

    NodeDebugOutput.WriteRenderDebug(
        node=node,
        renderer=renderer,
        filename=node.getParameter("filename").getValue(0),
        expandProcedural=node.getParameter(
            "Export.expandProcedurals").getValue(0),
        openInEditor=False,
        customEditor=None,
        log=export_logger)
예제 #2
0
    def nameChangedCallback(self, *args, **kwds):
        nameParameter = self.__node.getParameter('name')
        nm_node = SA.GetRefNode(self.__node, 'networkMaterial')
        nm_node.getParameter('name').setValue(nameParameter.getValue(0), 0)

        Producer = Nodes3DAPI.GetRenderProducer(self.__node, 0, False, 0)
        callback = []
        location = "/root/materials/materialx"
        proc = Producer.getProducerByPath(location)
        SA.WalkProducer(proc, callback, ["material"])
        new_location = ""
        for path in callback:
            if new_location:
                new_location = new_location + "|" + path
            else:
                # The first path
                new_location = path
        attr_node = SA.GetRefNode(self.__node, 'arnoldGlobalSettings')
        attr_node.getParameter('args.arnoldGlobalStatements.operators.enable').setValue(True, 0)
        param = attr_node.getParameter('args.arnoldGlobalStatements.operators.value')
        operators = param.getValue(0)
        for operator_path in operators.split("|"):
            # if operator_path under '/root/materials/materialx', skip!
            if operator_path.find(location) >= 0:
                continue
            if operator_path in callback:
                continue
            # if operator_path is "", skip!
            if operator_path == "":
                continue
            new_location = new_location + "|" + operator_path
        param.setValue(new_location, 0)
        return 1
예제 #3
0
def buildPxrUsdInOpArgsFromDownstreamNode(self,
                                          downstreamNode,
                                          graphState,
                                          portIndex=0):
    if not hasattr(self, '_argsCookTmp'):
        self._argsCookTmp = {}

    key = (FnAttribute.GroupBuilder().set('graphState',
                                          graphState.getOpSystemArgs()).set(
                                              'node',
                                              hash(downstreamNode)).set(
                                                  'portIndex',
                                                  portIndex).build().getHash())

    # Set a dynamic entry that's not prefixed with "var:" so it won't show up
    # in op system args (or other graph state comparisons other than hash
    # uniqueness)
    useGraphState = graphState.edit().setDynamicEntry(
        kArgsCookTmpKeyToken, FnAttribute.StringAttribute(key)).build()

    # trigger a cook with this unique graph state
    Nodes3DAPI.CreateClient(downstreamNode,
                            graphState=useGraphState,
                            portIndex=portIndex)

    if key in self._argsCookTmp:
        result = self._argsCookTmp[key]
        return result
    else:
        # TODO, exception?
        pass
예제 #4
0
    def __viewNodeChangedEvent(self, node):

        viewedTime = NodegraphAPI.GetCurrentTime()
        viewedNode = NodegraphAPI.GetViewNode()

        print "viewNode ---> ", viewedNode

        if not viewedNode:
            self.__runtime = None
            self.__client = None
            return

        self.__runtime = FnGeolib.GetRegisteredRuntimeInstance()
        txn = self.__runtime.createTransaction()

        op = Nodes3DAPI.GetOp(txn, viewedNode, viewedTime)

        if not op:
            self.__runtime = None
            return

        self.__client = txn.createClient()
        txn.setClientOp(self.__client, op)

        self.__runtime.commit(txn)

        self.__setLocations()
예제 #5
0
def doesExist(node, location):
    producer = Nodes3DAPI.GetRenderProducer(node, 0, False, 0)
    geometryProc = producer.getProducerByPath(location)
    if geometryProc is not None:
        return True
    else:
        return False
예제 #6
0
def get_attribute_values(node, locations, attribute_name):
    """
    Get unique attribute values from locations.

    Given a list of locations, and an attribute name, it cooking the locations at
    the given node, and gets a list of unique values for the attribute_name.
    
    Args:
        node (str): node
        locations (list): locations to cook
        attribute_name (str): Attribute name to fetch
    
    Returns:
        list. List of unique attributes

    """
    runtime = FnGeolib.GetRegisteredRuntimeInstance()
    txn = runtime.createTransaction()
    client = txn.createClient()
    op = Nodes3DAPI.GetOp(txn, NodegraphAPI.GetNode(node.getName()))
    txn.setClientOp(client, op)
    runtime.commit(txn)

    attribute_values = []

    for location in locations:
        cooked_location = client.cookLocation(location)
        attrs = cooked_location.getAttrs()
        attribute = attrs.getChildByName(attribute_name)
        attribute_value = attribute.getChildByName("value").getValue()
        if attribute_value not in attribute_values:
            attribute_values.append(attribute_value)
    return attribute_values
def registerShapeID():
    """
    Registers a new ShapeID node type using the NodeTypeBuilder utility class.
    """

    from Katana import Nodes3DAPI
    from Katana import FnAttribute

    def buildShapeIDOpChain(node, interface):
        """
        Defines the callback function used to define the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.ShapeID}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(1)

        argsGb = FnAttribute.GroupBuilder()

        # Parse the CEL parameter
        celParam = node.getParameter('CEL')
        if celParam:
            argsGb.set('CEL', celParam.getValue(frameTime))

        # Parse the displacement parameter
        pathParam = node.getParameter('regedit')
        if pathParam:
            argsGb.set('regedit', pathParam.getValue(frameTime))

        # Add the ShapeID Op to the Ops chain
        interface.appendOp('ShapeID', argsGb.build())

    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('ShapeID')

    # Add an input port
    nodeTypeBuilder.setInputPortNames(('in', ))

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('CEL', FnAttribute.StringAttribute(''))
    gb.set('regedit', FnAttribute.StringAttribute('*.json'))

    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())
    # Set parameter hints
    nodeTypeBuilder.setHintsForParameter('CEL', {'widget': 'cel'})
    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildShapeIDOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #8
0
    def __populate(self):
        """
        Populates the UI.
        """
        showLights = self.__displayMode & DISPLAY_LIGHTS
        showCameras = self.__displayMode & DISPLAY_CAMERAS

        if self.__displayMode == (DISPLAY_LIGHTS | DISPLAY_CAMERAS):
            showLights = self.__lightsCheckbox.isChecked()
            showCameras = self.__camerasCheckbox.isChecked()


        self.__pathToDisplayInfo = {}
        self.clear()

        items = []

        # Add builtin cameras
        if showCameras:
            for builtin_camera in LightPickerButton.__builtins:
                items.append((builtin_camera, None, (builtin_camera + 'Shape', 'camera')))
                self.__pathToDisplayInfo[builtin_camera+'Shape'] = (builtin_camera, '')

        prod = Nodes3DAPI.GetGeometryProducer(self.__node)
        world = prod.getChildByName('world')

        if showCameras:
            # Build camera list
            globalsGroup = world.getAttribute("globals")
            camList = globalsGroup.childByName("cameraList")
            if camList:
                camera_locations = camList.getNearestSample(0)
                camera_locations.sort()

            abbreviatedCameraLocationNames = GeoAPI.ScenegraphUtils.AbbreviateScenegraphLocations(
                camera_locations)
            for fullLoc,shortLoc in zip(camera_locations,abbreviatedCameraLocationNames):
                items.append((shortLoc, self.__pixmaps['camera'], (fullLoc, 'camera')))
                self.__pathToDisplayInfo[fullLoc] = (shortLoc, 'camera')
        if showLights:
            # Build light list
            light_locations = []
            lightList = world.getAttribute("lightList")
            if lightList:
                for lightKey, lightAttr in lightList.childDict().items():
                    path = lightAttr.childByName("path")
                    lightPath = path.getNearestSample(0)[0]
                    light_locations.append(lightPath)

            light_locations.sort()
            abbreviatedLightLocationNames = GeoAPI.ScenegraphUtils.AbbreviateScenegraphLocations(
                light_locations)
            for fullLoc,shortLoc in zip(light_locations,abbreviatedLightLocationNames):
                items.append((shortLoc, self.__pixmaps['light'], (fullLoc, 'light')))
                self.__pathToDisplayInfo[fullLoc] = (shortLoc, 'light')


        for (shortLoc, pixmap, meta) in items:
            self.addItem(shortLoc, pixmap=pixmap, meta=meta)
예제 #9
0
 def displayModel(self,node=NodegraphAPI.GetRootNode(), nameInNode='_hiShape'):
     allPath =[]
     nameInNode = self.namelineEdit.text()
     node = NodegraphAPI.GetNode( 'root' )
     sg = ScenegraphManager.getActiveScenegraph()
     time = NodegraphAPI.GetCurrentTime()
     producer = Nodes3DAPI.GetGeometryProducer(node, time)
     splitText = str(self.pathLineEdit.text()).split(' ')
     if len(splitText) > 0 and splitText[0] != '' :
         for prodpath in splitText:
             producer =producer.getProducerByPath(prodpath)
             a = self.recursiveFindPath(producer, allPath, nameInNode=nameInNode)
             producer = Nodes3DAPI.GetGeometryProducer(node, time)
     else:
         allPath = self.recursiveFindPath(producer, listPath=[], nameInNode=nameInNode)
     for item in allPath:
         sg.addPinnedLocation(item)
예제 #10
0
def createMeshLights(gafferNode,
                     celExpression,
                     lightName="",
                     rigName="",
                     mode="Append",
                     lightType="mesh"):
    client = utils.getClient(node=gafferNode)
    geoProducer = Nodes3DAPI.GetGeometryProducer(gafferNode)
    collectedLocations = GeoAPI.Util.CelUtil.CollectPathsFromCELStatement(
        client, celExpression)

    rootPackage = gafferNode.getRootPackage()
    if mode == "Override":
        for package in rootPackage.getChildPackages():
            package.delete()

    rigName = rigName or "{}LightsRig".format(lightType)
    rigPackage = rootPackage.createChildPackage("RigPackage", rigName)
    mmPackage = rootPackage.createChildPackage(
        "MasterMaterialPackage", "{}MasterMaterial".format(rigName))
    mmPackage.setShader("arnoldLight", "{}_light".format(lightType))

    for idx, location in enumerate(collectedLocations):
        cookedLocation = client.cookLocation(location)
        if cookedLocation.getAttrs().getChildByName("type").getValue() not in (
                "subdmesh", "polymesh"):
            continue
        name = lightName or "{}Light".format(os.path.basename(location))
        lightPackage = rigPackage.createChildPackage("LightPackage",
                                                     "{}_{}".format(name, idx))
        lightPackage.setMasterMaterial(mmPackage)
        materialNode = lightPackage.getMaterialNode()
        materialNode.checkDynamicParameters()
        if lightType == "mesh":
            materialNode.getParameter(
                'shaders.arnoldLightParams.mesh.enable').setValue(True, 0.0)
            materialNode.getParameter(
                'shaders.arnoldLightParams.mesh.value').setValue(
                    location, 0.0)
        elif lightType == "point":
            bounds = GeoAPI.Transform.ProducerWorldBounds(
                geoProducer.getProducerByPath(location))
            centerX = (bounds[0] + bounds[1]) / 2
            centerY = (bounds[2] + bounds[3]) / 2
            centerZ = (bounds[4] + bounds[5]) / 2
            materialNode.getParameter(
                'shaders.arnoldLightParams.position.enable').setValue(
                    True, 0.0)
            materialNode.getParameter(
                'shaders.arnoldLightParams.position.value.i0').setValue(
                    centerX, 0.0)
            materialNode.getParameter(
                'shaders.arnoldLightParams.position.value.i1').setValue(
                    centerY, 0.0)
            materialNode.getParameter(
                'shaders.arnoldLightParams.position.value.i2').setValue(
                    centerZ, 0.0)
예제 #11
0
def getClient(node=None):
    runtime = FnGeolib.GetRegisteredRuntimeInstance()
    transaction = runtime.createTransaction()
    client = transaction.createClient()
    if node:
        terminalOp = Nodes3DAPI.GetOp(transaction, node)
        transaction.setClientOp(client, terminalOp)
        runtime.commit(transaction)
    return client
예제 #12
0
def getRigScale(node, location):
    scale = [1.0, 1.0, 1.0]
    producer = Nodes3DAPI.GetRenderProducer(node, 0, False, 0)
    geometryproducer = producer.getProducerByPath(location)
    ad = geometryproducer.getAttribute('bound')
    if ad :
        data = ad.getData()
        scale = math.sqrt( math.pow((data[5]-data[4])/2, 2) + math.pow((data[1]-data[0])/2, 2) )
    return scale
예제 #13
0
def getRigTranslate(node, location):
    translate = [0.0, 0.0, 0.0]
    producer = Nodes3DAPI.GetRenderProducer(node, 0, False, 0)
    geometryproducer = producer.getProducerByPath(location)
    ad=geometryproducer.getDelimitedLocalAttribute('bound')
    if ad :
        data = ad.getData()
        translate = [(data[0]+data[1])/2, (data[2]+data[3])/2, (data[4]+data[5])/2]
    return translate
예제 #14
0
def registerAutoLookfileAssign():
    """
    Registers a new AutoLookfileAssign node type using the NodeTypeBuilder utility
    class.
    """

    from Katana import Nodes3DAPI
    from Katana import FnAttribute

    def buildAutoLookfileAssignOpChain(node, interface):
        """
        Defines the callback function used to create the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.AutoLookfileAssign}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(1)

        argsGb = FnAttribute.GroupBuilder()

        # Add the AutoLookfileAssign Op to the Ops chain
        interface.appendOp('AutoLookfileAssign', argsGb.build())


    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('alaAutoLookfile')

    # Add input port
    nodeTypeBuilder.setInputPortNames(("in",))

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()

    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())

    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildAutoLookfileAssignOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #15
0
def get_producer(knode, location=None):
    '''
    :description get the scenegraph location producer
    :prama knode <Nodegraph Node Object>
    :param location <str>
    :example
        from core import scenegraph
        knode = NodegraphAPI.GetAllSelectedNodes()[0]
        scenegraph.get_producer(knode, location=None)    
    '''
    NodegraphAPI.SetNodeViewed(knode, True, exclusive=True)
    producer = Nodes3DAPI.GetGeometryProducer(node=knode)
    if location:
        producer = producer.getProducerByPath(location)
    return producer
예제 #16
0
def getAll():
    node = NodegraphAPI.GetViewNode()
    runtime = FnGeolib.GetRegisteredRuntimeInstance()
    txn = runtime.createTransaction()
    client = txn.createClient()
    op = Nodes3DAPI.GetOp(txn, node)
    txn.setClientOp(client, op)
    runtime.commit(txn)

    locationPathsAndData = []
    traversal = FnGeolib.Util.Traversal(client, "/root")
    while traversal.valid():
        locationPathsAndData.append(
            (traversal.getLocationPath(), traversal.getLocationData()))
        traversal.next()
    for i in locationPathsAndData:
        print i
예제 #17
0
def importRigsSet(node):
    gaffer_three_node = getGafferThreeNode(node)
    root_locations = node.getParameter('rootLocations').getChildren()
    producer = Nodes3DAPI.GetRenderProducer(node, 0, False, 0)
    if not gaffer_three_node:
        message = "GafferThree node have not be connected to GafferThreeRigs!"
        setMessage(message)
        log.warning(message)
        return

    if not root_locations:
        message = "GafferThreeRigs node has no rootLocation!"
        setMessage(message)
        log.warning(message)
        return
    else:
        if root_locations and root_locations[0].getValue(0) is "":
            message = "GafferThreeRigs has no rootLocation"
            log.warning(message)
            return


    if not producer.getProducerByPath(getGafferThreeLocation(node) + "/" + cRigLayers[0]):
        chr_layer_rig_node = createRig(gaffer_three_node, cRigLayers[0])        
        setCharacterRig(gaffer_three_node, node, chr_layer_rig_node)
    else:
        chr_layer_rig_node = getRootRig(gaffer_three_node, cRigLayers[0])
        setCharacterRig(gaffer_three_node, node, chr_layer_rig_node)


    if not producer.getProducerByPath(getGafferThreeLocation(node) + "/" + cRigLayers[1]):
        env_layer_rig_node = createRig(gaffer_three_node, cRigLayers[1])
        setEnvrionmentRig(gaffer_three_node, node, env_layer_rig_node)
    else:
        message = "Light rig env_layer already created!"
        log.warning(message)

    if not producer.getProducerByPath(getGafferThreeLocation(node) + "/" + cRigLayers[2]):
        vol_layer_rig_node = createRig(gaffer_three_node, cRigLayers[2])
    else:
        message = "Light rig vol_layer already created!"
        log.warning(message)

    message = "Light rigs have been created into {%s} node!"%gaffer_three_node.getName()
    setMessage(message)
    CacheManager.flush(True)
예제 #18
0
def getCommonRigTranslate(node, locationNodes):
    rig_position_list = []
    for location in locationNodes:
        translate = [0.0, 0.0, 0.0]
        location_value = location.getValue(0)
        producer = Nodes3DAPI.GetRenderProducer(node, 0, False, 0)
        geometryproducer = producer.getProducerByPath(location_value)
        ad = geometryproducer.getDelimitedLocalAttribute('bound')
        if ad :
            data = ad.getData()
            translate = [(data[0]+data[1])/2, (data[2]+data[3])/2, (data[4]+data[5])/2]
        rig_position_list.append(translate)
    center_x = center_y = center_z = 0
    for position in rig_position_list:
        center_x += position[0]
        center_y += position[1]
        center_z += position[2]
    length = len(rig_position_list)
    return (center_x/length, center_y/length, center_z/length)
예제 #19
0
def _GetLocationType(node, location):
    """
    Get the 'type' attribute value for the given location, using the Op tree
    for the given node.

    @type node: C{Node}
    @type location: C{str}
    @rtype: C{str} or C{None}
    @param node: The node to calculate the scenegraph for
    @param location: The scenegraph location to query the type of
    @return: The location type as a string, or C{None} if the location wasn't
        found or the type attribute wasn't found
    """
    producer = Nodes3DAPI.GetGeometryProducer(node)
    if not producer:
        return None

    locationProducer = producer.getProducerByPath(location)
    if not locationProducer:
        return None

    attr = locationProducer.getAttribute("type")
    if attr:
        return attr.getData()[0]
예제 #20
0
    def rootLocationsParameterChangedCallback(self, *args, **kwds):
        root_locations = self.__node.getParameter('rootLocations')
        groupStackNode = SA.GetRefNode(self.__node, 'groupStack')
        opScriptNode = SA.GetRefNode(self.__node, 'opScript')
        location_list = []
        for location in root_locations.getChildren():
            location_value = location.getValue(0)           
            if location_value is not "":
                location_list.append(location_value)

        for child in groupStackNode.getChildNodes():
            groupStackNode.deleteChildNode(child)

        cel_string = ""
        Producer = Nodes3DAPI.GetRenderProducer(self.__node, 0, False, 0)
        for location in location_list:
            cel_string = cel_string + " " + location
            gnode = groupStackNode.buildChildNode(adoptNode=None)
            gnode.getParameter("paths.i0").setValue(location, 0)
            gnode.getParameter("attributeName").setValue("LightChaserAnimation.lightRig.assetName",0)
            gnode.getParameter("attributeType").setValue("string",0)
            gnode.getParameter('stringValue.i0').setValue(location,0)

        opScriptNode.getParameter('CEL').setValue(cel_string, 0)
예제 #21
0
    def rootLocationsParameterChangedCallback(self, *args, **kwds):
        root_locations = self.__node.getParameter('rootLocations')
        groupStackNode = SA.GetRefNode(self.__node, 'groupStack')
        opScriptNode = SA.GetRefNode(self.__node, 'opScript')
        location_list = []
        for location in root_locations.getChildren():
            location_value = location.getValue(0)
            if location_value is not "":
                location_list.append(location_value)

        for child in groupStackNode.getChildNodes():
            groupStackNode.deleteChildNode(child)

        cel_string = ""
        Producer = Nodes3DAPI.GetRenderProducer(self.__node, 0, False, 0)
        for location in location_list:
            cel_string = cel_string + " " + location
            proc = Producer.getProducerByPath(location)
            ad = proc.getDelimitedLocalAttribute('bound')
            if ad is not None:
                continue
            callback = []
            SA.WalkProducer(proc, callback, ["subdmesh", "polymesh"])
            bodygeo_string = "/root/world/geo"
            for path in callback:
                if path[-13:] == "body_geoShape":
                    bodygeo_string = path
            gnode = groupStackNode.buildChildNode(adoptNode=None)
            gnode.getParameter("paths.i0").setValue(location, 0)
            gnode.getParameter("attributeName").setValue(
                "LightChaserAnimation.assembly.bodyGeometry", 0)
            gnode.getParameter("attributeType").setValue("string", 0)
            gnode.getParameter('stringValue.i0').setValue(bodygeo_string, 0)

        opScriptNode.getParameter('CEL').setValue(cel_string, 0)
        return 1
예제 #22
0
requiredAttrs.set("material.parameters", FnAttribute.NullAttribute())
requiredAttrs.set("material.reference", FnAttribute.NullAttribute())

# Get the names of all known renderer plug-ins for light shaders
rendererPluginNames = RenderingAPI.RenderPlugins.GetRendererPluginNames()
for rendererPluginName in rendererPluginNames:
    requiredAttrs.set("material.%sLightShader" % rendererPluginName,
                      FnAttribute.NullAttribute())

#-------------------------------------------------------------------------------
# Match by value - Specify attributes whose value must also match those provided
#-------------------------------------------------------------------------------
requiredAttrs.set("material.style", FnAttribute.StringAttribute("network"))
requiredAttrs.set("viewer.default.resolveMaterialInViewer",
                  FnAttribute.StringAttribute("always"))

#-------------------------------------------------------------------------------
# Generate Op args
#-------------------------------------------------------------------------------
opArgsBuilder = FnAttribute.GroupBuilder()
opArgsBuilder.set("locationPaths", FnAttribute.StringAttribute('/root/world'))
opArgsBuilder.set('setAttrs.i0.name',
                  FnAttribute.StringAttribute("viewer.materialResolveAttrs"))
opArgsBuilder.set('setAttrs.i0.attr', requiredAttrs.build())
opArgsBuilder.set('setAttrs.i0.inherit', FnAttribute.IntAttribute(0))

# Register this op with the viewer implicit resolvers
Nodes3DAPI.RegisterImplicitResolver(
    Nodes3DAPI.ImplicitResolverStage.BeforeViewerResolvers,
    'AttributeSetIfNotPresent', opArgsBuilder.build(), True)
예제 #23
0
def registerBgeoIn():
    """
    Registers a new BgeoIn node type using the NodeTypeBuilder utility
    class.
    """

    from Katana import Nodes3DAPI
    from Katana import AssetAPI
    from Katana import FnAttribute
    from Katana import FnGeolibServices

    def buildBgeoInOpChain(node, interface):
        """
        Defines the callback function used to create the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.BgeoIn}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(0)

        argsGb = FnAttribute.GroupBuilder()

        # Parse node parameters
        locationParam = node.getParameter('location')
        fileNameParam = node.getParameter('fileName')
        makeFacesetsParam = node.getParameter('makeFacesets')
        reportEmptyParam = node.getParameter('reportEmpty')
        computeBoundParam = node.getParameter('computePointCloudBound')
        createSubdParam = node.getParameter('createSubd')
        checkVersionParam = node.getParameter('checkVersion')

        # resolve file path so that it can include frame number replacement
        # i.e. %04d
        filePath = fileNameParam.getValue(frameTime)
        fileSequencePlugin = AssetAPI.GetDefaultFileSequencePlugin()
        if fileSequencePlugin and fileSequencePlugin.isFileSequence(filePath):
            fileSequence = fileSequencePlugin.getFileSequence(filePath)
            resolvedPath = fileSequence.getResolvedPath(int(frameTime))
        else:
            resolvedPath = filePath

        argsGb.set('fileName', FnAttribute.StringAttribute(resolvedPath))
        argsGb.set(
            'makeFacesets',
            FnAttribute.IntAttribute(makeFacesetsParam.getValue(frameTime)))
        argsGb.set(
            'reportEmpty',
            FnAttribute.IntAttribute(reportEmptyParam.getValue(frameTime)))
        argsGb.set(
            'computePointCloudBound',
            FnAttribute.IntAttribute(computeBoundParam.getValue(frameTime)))
        argsGb.set(
            'createSubd',
            FnAttribute.IntAttribute(createSubdParam.getValue(frameTime)))
        argsGb.set(
            'checkVersion',
            FnAttribute.IntAttribute(checkVersionParam.getValue(frameTime)))

        # We want to use the StaticSceneCreate Op to build the parent
        # hierarchy, so that our op only has to worry about generating its
        # children. Its args are somewhat complex, but fortunately, there
        # is a helper class that makes it all much easier.

        rootLocation = locationParam.getValue(frameTime)

        sscb = FnGeolibServices.OpArgsBuilders.StaticSceneCreate()
        sscb.addSubOpAtLocation(rootLocation, 'BgeoIn', argsGb.build())

        interface.appendOp('StaticSceneCreate', sscb.build())

    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('BgeoIn')

    nodeTypeBuilder.setHintsForNode({'help': buildHelp("BgeoInHelp.txt")})

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('location', FnAttribute.StringAttribute('/root/world/geo/BgeoIn'))
    gb.set('fileName', FnAttribute.StringAttribute(''))
    gb.set('makeFacesets', FnAttribute.IntAttribute(0))
    gb.set('reportEmpty', FnAttribute.IntAttribute(1))
    gb.set('computePointCloudBound', FnAttribute.IntAttribute(0))
    gb.set('createSubd', FnAttribute.IntAttribute(1))
    gb.set('checkVersion', FnAttribute.IntAttribute(1))

    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())

    # Set parameter hints
    nodeTypeBuilder.setHintsForParameter('location', {
        'label': 'Location',
        'widget': 'scenegraphLocation'
    })
    nodeTypeBuilder.setHintsForParameter('fileName', {
        'label': 'File Name',
        'widget': 'fileInput'
    })
    nodeTypeBuilder.setHintsForParameter(
        'makeFacesets', {
            'label': 'Make Facesets',
            'widget': 'checkBox',
            'help': 'Create facesets from primitive groups.'
        })
    nodeTypeBuilder.setHintsForParameter(
        'reportEmpty', {
            'label': 'Report Empty Geometry',
            'widget': 'checkBox',
            'help': 'Report empty BGEO files (i.e. no geometry) as an error.'
        })
    nodeTypeBuilder.setHintsForParameter(
        'computePointCloudBound', {
            'label':
            'Compute Point Cloud Bound',
            'widget':
            'checkBox',
            'help':
            'Compute the bound based on point P and width attributes, ' +
            'instead of using the embedded header bound. This will prevent ' +
            'points at the edges of the bound from be clipped. Enabling this '
            + 'option prevents deferred loading of the BGEO file.'
        })
    nodeTypeBuilder.setHintsForParameter(
        'createSubd', {
            'label': 'Create Subdivision Surfaces',
            'widget': 'checkBox',
            'help': 'Create subdivision surfaces for polymesh primitives.'
        })
    nodeTypeBuilder.setHintsForParameter(
        'checkVersion', {
            'label':
            'Check Version',
            'widget':
            'checkBox',
            'help':
            'Verify the version in the bgeo file is compatible. ' +
            'Turn this off if you know the file is compatible regardless of ' +
            'the version it was written out from, i.e. from use of ' +
            'HOUDINIX_Y_GEO_COMPATIBILITY environment variables.'
        })

    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildBgeoInOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #24
0
def registerSphereMaker():
    """
    Registers a new SphereMaker node type using the NodeTypeBuilder utility
    class.
    """

    from Katana import Nodes3DAPI
    from Katana import FnAttribute

    def buildSphereMakerOpChain(node, interface):
        """
        Defines the callback function used to create the Ops chain for the
        node type being registered.

        @type node: C{Nodes3DAPI.NodeTypeBuilder.SphereMaker}
        @type interface: C{Nodes3DAPI.NodeTypeBuilder.BuildChainInterface}
        @param node: The node for which to define the Ops chain
        @param interface: The interface providing the functions needed to set
            up the Ops chain for the given node.
        """
        # Get the current frame time
        frameTime = interface.getGraphState().getTime()

        # Set the minimum number of input ports
        interface.setMinRequiredInputs(0)

        argsGb = FnAttribute.GroupBuilder()

        # Parse node parameters
        locationParam = node.getParameter('location')
        numberOfSpheresParam = node.getParameter('numberOfSpheres')
        if locationParam:
            location = locationParam.getValue(frameTime)

            # The base location is encoded using nested group attributes
            # defining a hierarchy where the elements in the location paths
            # are interleaved with group attributes named 'c' (for child).
            # The last element will contain a group attribute, named 'a',
            # which in turn will hold an attribute defining the number of
            # spheres to be generated.
            # See the Op source code for more details
            locationPaths = location[1:].split('/')[1:]
            attrsHierarchy = 'c.' + '.c.'.join(locationPaths)
            argsGb.set(
                attrsHierarchy + '.a.numberOfSpheres',
                FnAttribute.IntAttribute(
                    numberOfSpheresParam.getValue(frameTime)))

        # Add the SphereMaker Op to the Ops chain
        interface.appendOp('SphereMaker', argsGb.build())

    # Create a NodeTypeBuilder to register the new type
    nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('SphereMaker')

    # Build the node's parameters
    gb = FnAttribute.GroupBuilder()
    gb.set('location',
           FnAttribute.StringAttribute('/root/world/geo/SphereMaker'))
    gb.set('numberOfSpheres', FnAttribute.IntAttribute(20))

    # Set the parameters template
    nodeTypeBuilder.setParametersTemplateAttr(gb.build())

    # Set parameter hints
    nodeTypeBuilder.setHintsForParameter('location',
                                         {'widget': 'scenegraphLocation'})
    nodeTypeBuilder.setHintsForParameter('numberOfSpheres', {'int': True})

    # Set the callback responsible to build the Ops chain
    nodeTypeBuilder.setBuildOpChainFnc(buildSphereMakerOpChain)

    # Build the new node type
    nodeTypeBuilder.build()
예제 #25
0
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from Katana import (
    Nodes3DAPI,
    FnAttribute,
    FnGeolibServices,
)


def getScenegraphLocation(self, frameTime):
    return self.getParameter('location').getValue(frameTime)


# node type builder for a our new node type
nb = Nodes3DAPI.NodeTypeBuilder('PxrUsdIn')

# group builder for the node parameters
gb = FnAttribute.GroupBuilder()

gb.set('fileName', '')
nb.setHintsForParameter('fileName', {
    'help': 'The USD file to read.',
})

gb.set('location', '/root/world/geo')
nb.setHintsForParameter(
    'location', {
        'widget': 'scenegraphLocation',
        'help': 'The Katana scenegraph location to load the USD contents.',
    })
예제 #26
0
파일: PxrUsdIn.py 프로젝트: xinguo2015/USD
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from Katana import (
    Nodes3DAPI,
    FnAttribute,
    FnGeolibServices,
)


def getScenegraphLocation(self, frameTime):
    return self.getParameter('location').getValue(frameTime)


# node type builder for a our new node type
nb = Nodes3DAPI.NodeTypeBuilder('PxrUsdIn')

# group builder for the node parameters
gb = FnAttribute.GroupBuilder()

gb.set('fileName', '')
nb.setHintsForParameter('fileName', {
    'help': 'The USD file to read.',
})

gb.set('location', '/root/world/geo')
nb.setHintsForParameter(
    'location', {
        'widget': 'scenegraphLocation',
        'help': 'The Katana scenegraph location to load the USD contents.',
    })
			argsGb.set(attrsHierarchy + '.a.filePath', FnAttribute.StringAttribute(filePathParam.getValue(0)))
		else:
			argsGb.set(attrsHierarchy + '.a.numPoints', FnAttribute.IntAttribute(numPointsParam.getValue(0)))
			argsGb.set(attrsHierarchy + '.a.splitPointcloudLocations', FnAttribute.IntAttribute(splitPointcloudLocationsParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.pointWidthType', FnAttribute.IntAttribute(pointWidthTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.constantPointWidth', FnAttribute.FloatAttribute(constantPointWidthParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.randomPointWidthMin', FnAttribute.FloatAttribute(randomPointWidthMinParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.randomPointWidthMax', FnAttribute.FloatAttribute(randomPointWidthMaxParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.areaSpread', FnAttribute.FloatAttribute([areaSpreadParamX.getValue(0), areaSpreadParamY.getValue(0), areaSpreadParamZ.getValue(0)], 3))
		argsGb.set(attrsHierarchy + '.a.extraFloatPrimvarType', FnAttribute.IntAttribute(extraFloatPrimvarTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.extraVectorPrimvarType', FnAttribute.IntAttribute(extraVectorPrimvarTypeParam.getValue(0)))
		argsGb.set(attrsHierarchy + '.a.extraColorPrimvarType', FnAttribute.IntAttribute(extraColorPrimvarTypeParam.getValue(0)))

	interface.appendOp('PointCloudCreate', argsGb.build())

nodeTypeBuilder = Nodes3DAPI.NodeTypeBuilder('PointCloudCreate')

gb = FnAttribute.GroupBuilder()
gb.set('location', FnAttribute.StringAttribute('/root/world/geo/pointcloud1'))
gb.set('generateType', FnAttribute.IntAttribute(0))
gb.set('fileType', FnAttribute.IntAttribute(0))
gb.set('filePath', FnAttribute.StringAttribute(""))
gb.set('numPoints', FnAttribute.IntAttribute(10000))
gb.set('splitPointcloudLocations', FnAttribute.IntAttribute(0))
gb.set('pointWidthType', FnAttribute.IntAttribute(0))
gb.set('constantPointWidth', FnAttribute.FloatAttribute(0.1))
gb.set('randomPointWidthMin', FnAttribute.FloatAttribute(0.1))
gb.set('randomPointWidthMax', FnAttribute.FloatAttribute(0.2))
gb.set('areaSpread', FnAttribute.FloatAttribute([20.0, 20.0, 20.0], 3))
gb.set('extraFloatPrimvarType', FnAttribute.IntAttribute(0))
gb.set('extraVectorPrimvarType', FnAttribute.IntAttribute(0))
예제 #28
0
    def bake(self):
        import KTMaterialXTools.ScriptMaterialX as MateX
        reload(MateX)
        switch_node = SA.GetRefNode(self, 'switch')
        merge_node = SA.GetRefNode(self, 'merge')
        def walkProducer(producer, callback, location_types=[]):
           child = producer.getFirstChild()
           while child:
               walkProducer(child, callback, location_types)
               child = child.getNextSibling()
           if producer.getType() in location_types:
               fullLocation = producer.getFullName()
               callback.append(fullLocation)
        def makeCollctions(producer, callback, collations):
            for path in callback:
                proc = producer.getProducerByPath(path)
                attr=proc.getAttribute("geometry.arbitrary.materialAssigned.value")
                temp_map = {}
                temp_map["material"] = attr.getValue()
                temp_map["collction"] = path
                collations.append(temp_map)


        # Get attribute rootLocations.
        rootLocationsParameters = self.getParameter('rootLocations').getChildren()
        rootLocations = []
        for rootLocationsParameter in rootLocationsParameters:
            rootLocations.append(rootLocationsParameter.getValue(0))
        rootLocations = sorted(rootLocations , key = len)


        # Get attribute saveTo.
        saveToParameter = self.getParameter('saveTo')
        saveTo = saveToParameter.getValue(0)

        # If saveTo is None, stop at first time here
        if not saveTo:
            log.warning("Parameter saveTo is empty, please enter the specify path!")
            return 


        children = self.getParameter('passes').getChildren()
        look_set = {}
        for child in children:
            look_name = child.getValue(0)

            index = switch_node.getInputPort(child.getName()).getIndex()
            switch_node.getParameter('in').setValue(index, 0)
            producer = Nodes3DAPI.GetRenderProducer(merge_node, 0, False, 0)

            callback = []
            collations = []
            location_types = ["subdmesh", "polymesh", "renderer procedural"]
            walkProducer(producer, callback, location_types)
            makeCollctions(producer, callback, collations)
            assignment_set = []
            for MC in collations:
                material_name = MC["material"]
                collation_path = MC["collction"]
                collation_name = collation_path
                for prefix in rootLocations:
                    if collation_path.startswith(prefix):
                        collation_name = collation_path[len(prefix):]
                assignment_set.append( (collation_name, material_name) )

            if assignment_set:
                look_set[look_name] = assignment_set

        MateX.export(look_set,saveTo)
        log.info("MaterialX file save to %s"%saveTo)
        # Set Switch back
        switch_node.getParameter('in').setValue(0, 0)
예제 #29
0
from Katana import FnAttribute, Nodes3DAPI

nb = Nodes3DAPI.NodeTypeBuilder('TestOp')
nb.setInputPortNames(('in', ))

nb.setParametersTemplateAttr(FnAttribute.GroupBuilder().set(
    'argParent', FnAttribute.StringAttribute("father")).set(
        'argChild', FnAttribute.StringAttribute("son")).build())

nb.setHintsForNode({'help': 'Node hints here!!!'})
nb.setHintsForParameter('attrName', {'help': 'Arg hints here!!!'})


def myBuildOps(node, interface):
    op = interface.buildOp('testParentOp')

    if op.areParametersDirty():
        frameTime = interface.getFrameTime()

        op.setOpType('TestParentOp')
        op.setOpArg('argParent',
                    node.getParameter('argParent').getValue(frameTime))
        op.setOpArg('argChild',
                    node.getParameter('argChild').getValue(frameTime))

    if op.areInputsDirty():
        op.setOpInputs(interface.getAllInputOps())

    return op

예제 #30
0
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from Katana import (
    Nodes3DAPI,
    FnAttribute,
    FnGeolibServices,
)


def getScenegraphLocation(self, frameTime):
    return self.getParameter('location').getValue(frameTime)


# node type builder for a our new node type
nb = Nodes3DAPI.NodeTypeBuilder('PxrUsdIn')

# group builder for the node parameters
gb = FnAttribute.GroupBuilder()

gb.set('fileName', '')
nb.setHintsForParameter('fileName', {
    'help': 'The USD file to read.',
})

gb.set('location', '/root/world/geo')
nb.setHintsForParameter(
    'location', {
        'widget': 'scenegraphLocation',
        'help': 'The Katana scenegraph location to load the USD contents.',
    })