def _popupMenu( menuDefinition, plugValueWidget ) : compoundNumericPlugValueWidget = None if isinstance( plugValueWidget, GafferUI.CompoundNumericPlugValueWidget ) : compoundNumericPlugValueWidget = plugValueWidget else : plugWidget = plugValueWidget.ancestor( GafferUI.PlugWidget ) if plugWidget is not None and isinstance( plugWidget.plugValueWidget(), GafferUI.CompoundNumericPlugValueWidget ) : compoundNumericPlugValueWidget = plugWidget.plugValueWidget() if compoundNumericPlugValueWidget is None : return if compoundNumericPlugValueWidget.getPlug().isGanged() : menuDefinition.append( "/GangDivider", { "divider" : True } ) menuDefinition.append( "/Ungang", { "command" : Gaffer.WeakMethod( compoundNumericPlugValueWidget.__ungang ), "shortCut" : "Ctrl+G", "active" : not plugValueWidget.getReadOnly() and not Gaffer.readOnly( compoundNumericPlugValueWidget.getPlug() ), } ) elif compoundNumericPlugValueWidget.getPlug().canGang() : menuDefinition.append( "/GangDivider", { "divider" : True } ) menuDefinition.append( "/Gang", { "command" : Gaffer.WeakMethod( compoundNumericPlugValueWidget.__gang ), "shortCut" : "Ctrl+G", "active" : not plugValueWidget.getReadOnly() and not Gaffer.readOnly( compoundNumericPlugValueWidget.getPlug() ), } )
def testCopyPaste( self ) : s = Gaffer.ScriptNode() s["b"] = Gaffer.Box() s["b"]["a1"] = GafferTest.AddNode() s["b"]["a2"] = GafferTest.AddNode() s["b"]["a2"]["op1"].setInput( s["b"]["a1"]["sum"] ) s["b"].promotePlug( s["b"]["a1"]["op1"] ) s["b"].exportForReference( self.temporaryDirectory() + "/test.grf" ) s["r"] = Gaffer.Reference() s["r"].load( self.temporaryDirectory() + "/test.grf" ) self.assertTrue( Gaffer.readOnly( s["r"]["a1"] ) ) self.assertTrue( Gaffer.readOnly( s["r"]["a2"] ) ) s.execute( s.serialise( parent = s["r"], filter = Gaffer.StandardSet( [ s["r"]["a1"], s["r"]["a2"] ] ) ) ) self.assertTrue( "a1" in s ) self.assertTrue( "a2" in s ) self.assertTrue( s["a2"]["op1"].getInput().isSame( s["a1"]["sum"] ) ) self.assertFalse( Gaffer.readOnly( s["a1"] ) ) self.assertFalse( Gaffer.readOnly( s["a2"] ) )
def __init__( self, node, **kw ) : column = GafferUI.ListContainer( spacing = 4 ) GafferUI.Widget.__init__( self, column, **kw ) self.__node = node with column : with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing = 4 ) : GafferUI.Label( "Language" ) self.__languageMenu = GafferUI.MenuButton( "", menu = GafferUI.Menu( Gaffer.WeakMethod( self.__languageMenuDefinition ) ) ) self.__languageMenu.setEnabled( not Gaffer.readOnly( node ) ) self.__textWidget = GafferUI.MultiLineTextWidget( role = GafferUI.MultiLineTextWidget.Role.Code ) self.__textWidget.setEditable( not Gaffer.readOnly( node ) ) self.__activatedConnection = self.__textWidget.activatedSignal().connect( Gaffer.WeakMethod( self.__activated ) ) self.__editingFinishedConnection = self.__textWidget.editingFinishedSignal().connect( Gaffer.WeakMethod( self.__editingFinished ) ) self.__dropTextConnection = self.__textWidget.dropTextSignal().connect( Gaffer.WeakMethod( self.__dropText ) ) self.__messageWidget = GafferUI.MessageWidget() self.__expressionChangedConnection = self.__node.expressionChangedSignal().connect( Gaffer.WeakMethod( self.__expressionChanged ) ) self.__errorConnection = self.__node.errorSignal().connect( Gaffer.WeakMethod( self.__error ) ) self.__update()
def __plugMetadataChanged( self, nodeTypeId, plugPath, key, plug ) : if self.__plug is None : return if ( Gaffer.affectedByChange( self.__plug, nodeTypeId, plugPath, plug ) or ( key == "readOnly" and Gaffer.ancestorAffectedByChange( self.__plug, nodeTypeId, plugPath, plug ) ) ) : self._updateFromPlug()
def __applyReadOnly( self, readOnly ) : def clearFlags( plug ) : plug.setFlags( Gaffer.Plug.Flags.ReadOnly, False ) for child in plug.children() : clearFlags( child ) with Gaffer.UndoContext( self.getPlug().ancestor( Gaffer.ScriptNode.staticTypeId() ) ) : # We used to use a plug flag, but we use metadata now # instead. Clear the old flags so that metadata is in # control. clearFlags( self.getPlug() ) Gaffer.setReadOnly( self.getPlug(), readOnly )
def __clicked( self, button ) : if Gaffer.readOnly( self.__node["context"] ) : return with Gaffer.UndoScope( self.__node.ancestor( Gaffer.ScriptNode ) ) : self.__node["context"].addChild( Gaffer.NameValuePlug( "", "", True, "member1", flags = Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.Dynamic ) )
def __clicked( self, button ) : if Gaffer.readOnly( self.__node["context"] ) : return with Gaffer.UndoScope( self.__node.ancestor( Gaffer.ScriptNode ) ) : self.__node["context"].addOptionalMember( "", "", enabled = True )
def _qtImport( name, lazy=False ) : # decide which qt bindings to use, and apply any fix-ups we need # to shield us from PyQt/PySide differences. global __qtModuleName if __qtModuleName is None : import os if "GAFFERUI_QT_BINDINGS" in os.environ : __qtModuleName = os.environ["GAFFERUI_QT_BINDINGS"] else : # no preference stated via environment - see what we shipped with if os.path.exists( os.environ["GAFFER_ROOT"] + "/python/PySide" ) : __qtModuleName = "PySide" else : __qtModuleName = "PyQt4" # PyQt unfortunately uses an implementation-specific # naming scheme for its new-style signal and slot classes. # We use this to make it compatible with PySide, according to : # # http://qt-project.org/wiki/Differences_Between_PySide_and_PyQt if "PyQt" in __qtModuleName : QtCore = __import__( __qtModuleName + ".QtCore" ).QtCore QtCore.Signal = QtCore.pyqtSignal # import the submodule from those bindings and return it if lazy : import Gaffer return Gaffer.lazyImport( __qtModuleName + "." + name ) else : qtModule = __import__( __qtModuleName + "." + name ) return getattr( qtModule, name )
def __nodeGraphPlugContextMenu( nodeGraph, plug, menuDefinition ) : if not isinstance( plug.node(), GafferScene.Shader ) : return if not ( plug.node()["parameters"].isAncestorOf( plug ) or plug.node()["out"].isAncestorOf( plug ) ) : return if len( menuDefinition.items() ) : menuDefinition.append( "/HideDivider", { "divider" : True } ) if plug.direction() == plug.Direction.In : numConnections = 1 if plug.getInput() else 0 else : numConnections = len( plug.outputs() ) menuDefinition.append( "/Hide", { "command" : functools.partial( __setPlugMetadata, plug, "noduleLayout:visible", False ), "active" : numConnections == 0 and not Gaffer.readOnly( plug ), } )
def applyDefaults( graphComponent ) : if isinstance( graphComponent, Gaffer.Plug ) : plug = graphComponent if plug.direction() == plug.Direction.Out : return elif plug.isSame( plug.node()["user"] ) : # Not much sense reverting user plugs, since we # don't expect the user to have gone to the trouble # of giving them defaults. return elif plug.getName().startswith( "__" ) : # Private plugs are none of our business. return elif Gaffer.readOnly( plug ) : return if isinstance( plug, Gaffer.ValuePlug ) : if plug.settable() : plug.setToDefault() return for c in graphComponent.children( Gaffer.Plug ) : applyDefaults( c )
def __popupMenu( menuDefinition, plugValueWidget ) : plug = plugValueWidget.getPlug() if not isinstance( plug, Gaffer.ValuePlug ) : return node = plug.node() if node is None or node.parent() is None : return input = plug.getInput() if input is not None or not plugValueWidget._editable() or Gaffer.readOnly( plug ) : return languages = [ l for l in Gaffer.Expression.languages() if Gaffer.Expression.defaultExpression( plug, l ) ] if not languages : return menuDefinition.prepend( "/ExpressionDivider", { "divider" : True } ) for language in languages : menuDefinition.prepend( "/Create " + IECore.CamelCase.toSpaced( language ) + " Expression...", { "command" : functools.partial( __createExpression, plug, language ) } )
def __namesPopupMenu( menuDefinition, plugValueWidget ) : plug = plugValueWidget.getPlug() node = plug.node() if not isinstance( node, GafferScene.DeleteGlobals ) : return if plug != node["names"] : return with plugValueWidget.getContext() : globals = node["in"]["globals"].getValue() currentNames = set( node["names"].getValue().split() ) prefix = node._namePrefix() names = [ n for n in globals.keys() if n.startswith( prefix ) ] if not names : return menuDefinition.prepend( "/NamesDivider", { "divider" : True } ) menuPrefix = "/" + node.typeName().rsplit( ":" )[-1].replace( "Delete", "" ) + "/" for name in reversed( sorted( list( names ) ) ) : nameWithoutPrefix = name[len(prefix):] menuDefinition.prepend( menuPrefix + nameWithoutPrefix, { "command" : IECore.curry( __toggleName, plug, nameWithoutPrefix ), "active" : plug.settable() and not plugValueWidget.getReadOnly() and not Gaffer.readOnly( plug ), "checkBox" : nameWithoutPrefix in currentNames, } )
def __menuDefinition( self ) : result = IECore.MenuDefinition() url = Gaffer.Metadata.value( self.nodeUI().node(), "documentation:url" ) result.append( "/Documentation...", { "active" : bool( url ), "command" : functools.partial( GafferUI.showURL, url ), } ) result.append( "/DocumentationDivider", { "divider" : True } ) result.append( "/Revert to Defaults", { "command" : Gaffer.WeakMethod( self.__revertToDefaults ), "active" : not Gaffer.readOnly( self.nodeUI().node() ), } ) self.toolMenuSignal()( self, self.nodeUI().node(), result ) return result
def _updateFromPlug( self ) : with self.getContext() : shaderName = self.getPlug().getValue() self.__label.setText( "<h3>Shader : " + shaderName + "</h3>" ) ## \todo Disable the type check once we've got OpenGLShader implementing reloading properly. self.__button.setEnabled( not Gaffer.readOnly( self.getPlug() ) and not isinstance( self.getPlug().node(), GafferScene.OpenGLShader ) )
def __plugMetadataChanged( self, nodeTypeId, plugPath, key, plug ) : if self.getPlug() is None : return if key=="label" and Gaffer.affectedByChange( self.getPlug(), nodeTypeId, plugPath, plug ) : self.__updateFormatter()
def __printPerformance(self, script, args): print "Performance :\n" self.__printItems(self.__timers.items()) if self.__performanceMonitor is not None: print "\n" + Gaffer.formatStatistics( self.__performanceMonitor, maxLinesPerMetric=args["maxLinesPerMetric"].value )
def __plugMetadataChanged( self, nodeTypeId, plugPath, key ) : if self.__key != key : return if not self.__target.node().isInstanceOf( nodeTypeId ) : return if not Gaffer.match( self.__target.relativeName( self.__target.node() ), plugPath ) : return self.__update()
def test(self): for s, p, r in [ ("", "", True), ("a", "a", True), ("a", "*", True), ("ab", "a*", True), ("cat", "dog", False), ("dogfish", "*fish", True), ("dogcollar", "*fish", False), ("dog collar", "dog collar", True), ("dog collar", "dog co*", True), ("dog collar", "dog *", True), ("dog collar", "dog*", True), ]: self.assertEqual(Gaffer.match(s, p), r) if " " not in s: self.assertEqual(Gaffer.matchMultiple(s, p), r)
def __setsPopupMenu( menuDefinition, plugValueWidget ) : plug = plugValueWidget.getPlug() if plug is None : return acceptsSetName = Gaffer.Metadata.value( plug, "ui:scene:acceptsSetName" ) acceptsSetNames = Gaffer.Metadata.value( plug, "ui:scene:acceptsSetNames" ) if not acceptsSetName and not acceptsSetNames : return node = plug.node() if isinstance( node, GafferScene.Filter ) : nodes = [ o.node() for o in node["out"].outputs() ] else : nodes = [ node ] setNames = set() with plugValueWidget.getContext() : for node in nodes : for scenePlug in node.children( GafferScene.ScenePlug ) : if scenePlug.direction() != scenePlug.Direction.In : continue setNames.update( [ str( n ) for n in scenePlug["setNames"].getValue() ] ) if not setNames : return menuDefinition.prepend( "/SetsDivider", { "divider" : True } ) with plugValueWidget.getContext() : if acceptsSetNames : currentNames = set( plug.getValue().split() ) else : currentNames = set( [ plug.getValue() ] ) for setName in reversed( sorted( list( setNames ) ) ) : newNames = set( currentNames ) if acceptsSetNames else set() if setName not in currentNames : newNames.add( setName ) else : newNames.discard( setName ) menuDefinition.prepend( "/Sets/%s" % setName, { "command" : functools.partial( __setValue, plug, " ".join( sorted( newNames ) ) ), "checkBox" : setName in currentNames, "active" : plug.settable() and not plugValueWidget.getReadOnly() and not Gaffer.readOnly( plug ), } )
def _updateFromSet( self ) : GafferUI.NodeSetEditor._updateFromSet( self ) del self.__column[:] self.__nodeUI = None self.__nameWidget = None node = self._lastAddedNode() if not node : return with self.__column : with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, borderWidth=8, spacing=4 ) : GafferUI.Label( "<h4>Node Name</h4>" ) self.__nameWidget = GafferUI.NameWidget( node ) ## \todo Make NameWidget support the readOnly metadata internally itself. # We can't do that easily right now, because it would need to be managing # the exact same `setEditable()` call that we're using here to propagate # our Widget readonlyness. Really our Widget readonlyness mechanism is a # bit lacking, and it should really be inherited automatically so we don't # have to propagate it like this. self.__nameWidget.setEditable( not self.getReadOnly() and not Gaffer.readOnly( node ) ) with GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, spacing=4 ) as infoSection : GafferUI.Label( "<h4>" + node.typeName().rpartition( ":" )[-1] + "</h4>" ) button = GafferUI.Button( image = "info.png", hasFrame = False ) url = Gaffer.Metadata.value( node, "documentation:url" ) if url : button.clickedSignal().connect( lambda button : GafferUI.showURL( url ), scoped = False ) toolTip = "<h3>" + node.typeName().rpartition( ":" )[2] + "</h3>" description = Gaffer.Metadata.nodeDescription( node ) if description : toolTip += "\n\n" + description infoSection.setToolTip( toolTip ) GafferUI.MenuButton( image = "gear.png", hasFrame = False, menu = GafferUI.Menu( Gaffer.WeakMethod( self.__menuDefinition ) ) ) frame = GafferUI.Frame( borderStyle=GafferUI.Frame.BorderStyle.None, borderWidth=0 ) self.__column.append( frame, expand=True ) self.__nodeUI = GafferUI.NodeUI.create( node ) self.__nodeUI.setReadOnly( self.getReadOnly() ) frame.setChild( self.__nodeUI )
def test( self ) : # lazy loading something already loaded should just return the module # directly. ut = Gaffer.lazyImport( "unittest" ) self.failUnless( ut is unittest ) self.failUnless( type( ut ) is types.ModuleType ) # lazy loading something not yet loaded should give us a nice # lazy module. hopefully nobody is loading the dummy_threading # module for any other purpose. self.failIf( "dummy_threading" in sys.modules ) lazyDT = Gaffer.lazyImport( "dummy_threading" ) self.failUnless( "dummy_threading" in sys.modules ) self.failUnless( isinstance( lazyDT, Gaffer.LazyModule ) ) # check we can still get stuff out t = lazyDT.Thread() s = lazyDT.Semaphore()
def __plugMetadataChanged( self, nodeTypeId, plugPath, key, plug ) : parentAffected = isinstance( self.__parent, Gaffer.Plug ) and Gaffer.affectedByChange( self.__parent, nodeTypeId, plugPath, plug ) childAffected = Gaffer.childAffectedByChange( self.__parent, nodeTypeId, plugPath, plug ) if not parentAffected and not childAffected : return if key in ( "divider", self.__layoutName + ":divider", self.__layoutName + ":index", self.__layoutName + ":section", self.__layoutName + ":accessory", "plugValueWidget:type" ) : # we often see sequences of several metadata changes - so # we schedule a lazy update to batch them into one ui update. self.__layoutDirty = True self.__updateLazily() elif re.match( self.__layoutName + ":section:.*:summary", key ) : self.__summariesDirty = True self.__updateLazily()
def appendNodeContextMenuDefinitions( nodeGraph, node, menuDefinition ) : if len( menuDefinition.items() ) : menuDefinition.append( "/GraphBookmarksDivider", { "divider" : True } ) menuDefinition.append( "/Bookmarked", { "checkBox" : __getBookmarked( node ), "command" : functools.partial( __setBookmarked, node ), "active" : not Gaffer.readOnly( node ), } )
def testHasWildcards( self ) : for p, r in [ ( "", False ), ( "a", False ), ( "*", True ), ( "a*", True ), ( "a**", True ), ( "a*b", True ), ( "*a", True ), ] : self.assertEqual( Gaffer.hasWildcards( p ), r )
def appendEnabledPlugMenuDefinitions( cls, nodeGraph, node, menuDefinition ) : enabledPlug = node.enabledPlug() if isinstance( node, Gaffer.DependencyNode ) else None if enabledPlug is not None : menuDefinition.append( "/EnabledDivider", { "divider" : True } ) menuDefinition.append( "/Enabled", { "command" : functools.partial( cls.__setEnabled, node ), "checkBox" : enabledPlug.getValue(), "active" : enabledPlug.settable() and not Gaffer.readOnly( enabledPlug ) } )
def __nodeGraphPlugContextMenu( nodeGraph, plug, menuDefinition ) : readOnly = Gaffer.readOnly( plug ) if isinstance( plug.node(), Gaffer.Box ) : menuDefinition.append( "/Rename...", { "command" : functools.partial( __renamePlug, plug = plug ), "active" : not readOnly, } ) menuDefinition.append( "/MoveDivider", { "divider" : True } ) currentEdge = Gaffer.Metadata.value( plug, "nodeGadget:nodulePosition" ) if not currentEdge : currentEdge = "top" if plug.direction() == plug.Direction.In else "bottom" for edge in ( "top", "bottom", "left", "right" ) : menuDefinition.append( "/Move To/" + edge.capitalize(), { "command" : functools.partial( __setPlugMetadata, plug, "nodeGadget:nodulePosition", edge ), "active" : edge != currentEdge and not readOnly, } ) edgePlugs = __edgePlugs( nodeGraph, plug ) edgeIndex = edgePlugs.index( plug ) menuDefinition.append( "/Move " + ( "Up" if currentEdge in ( "left", "right" ) else "Left" ), { "command" : functools.partial( __reorderPlugs, edgePlugs, plug, edgeIndex - 1 ), "active" : edgeIndex > 0 and not readOnly, } ) menuDefinition.append( "/Move " + ( "Down" if currentEdge in ( "left", "right" ) else "Right" ), { "command" : functools.partial( __reorderPlugs, edgePlugs, plug, edgeIndex + 1 ), "active" : edgeIndex < len( edgePlugs ) - 1 and not readOnly, } ) __appendPlugDeletionMenuItems( menuDefinition, plug, readOnly ) __appendPlugPromotionMenuItems( menuDefinition, plug, readOnly )
def _plugMetadataChanged(cls, nodeTypeId, plugPath, key): for i in cls.__instances: instance = i() if instance is None or instance.getTarget() is None: continue if instance.__key != key: continue if not isinstance(instance.getTarget(), Gaffer.Plug): continue if not instance.getTarget().node().isInstanceOf(nodeTypeId): continue if not Gaffer.match(instance.getTarget().relativeName(instance.getTarget().node()), plugPath): continue instance.__updateWidgetValue()
def _editable( self, canEditAnimation = False ) : plug = self.getPlug() if plug is None : return False if self.__readOnly : return False if hasattr( plug, "settable" ) and not plug.settable() : if not canEditAnimation or not Gaffer.Animation.isAnimated( plug ) : return False if Gaffer.readOnly( plug ) : return False return True
def testScaling( self ) : # See DispatcherTest.testScaling for details. s = Gaffer.ScriptNode() lastTask = None for i in range( 0, 5 ) : perFrame = GafferDispatch.PythonCommand() perFrame["command"].setValue( "context.getFrame()" ) s["perFrame%d" % i] = perFrame if lastTask is not None : perFrame["preTasks"][0].setInput( lastTask["task"] ) perSequence = GafferDispatch.PythonCommand() perSequence["command"].setValue( "pass" ) perSequence["sequence"].setValue( True ) perSequence["preTasks"][0].setInput( perFrame["task"] ) s["perSequence%d" % i] = perSequence lastTask = perSequence d = self.__createLocalDispatcher() d["framesMode"].setValue( d.FramesMode.CustomRange ) d["frameRange"].setValue( "1-1000" ) t = time.clock() d.dispatch( [ lastTask ] ) timeLimit = 6 if Gaffer.isDebug(): timeLimit *= 2 self.assertLess( time.clock() - t, timeLimit ) d["executeInBackground"].setValue( True ) d.dispatch( [ lastTask ] ) t = time.clock() d.jobPool().jobs()[0].kill() self.assertLess( time.clock() - t, 1 ) d.jobPool().waitForAll()
def testMultiple(self): for s, p, r in [ ("", "", True), ("a", "b a", True), ("a", "c *", True), ("ab", "c a*", True), ("cat", "dog fish", False), ("cat", "cad cat", True), ("cat", "cad ", False), ("cat", "cat ", True), ("cat", "cadcat", False), ("dogfish", "cat *fish", True), ("dogcollar", "dog *fish", False), ("dogcollar", "dog collar", False), ("a1", "*1 b2", True), ]: self.assertEqual(Gaffer.matchMultiple(s, p), r)
def testDerivingInPython( self ) : class TestGraphComponent( Gaffer.GraphComponent ) : def __init__( self, name = "TestGraphComponent" ) : Gaffer.GraphComponent.__init__( self, name ) self.acceptsChildCalled = False self.acceptsParentCalled = False def acceptsChild( self, potentialChild ) : self.acceptsChildCalled = True return isinstance( potentialChild, TestGraphComponent ) def acceptsParent( self, potentialParent ) : self.acceptsParentCalled = True return isinstance( potentialParent, TestGraphComponent ) IECore.registerRunTimeTyped( TestGraphComponent ) # check names in constructors g1 = TestGraphComponent() self.assertEqual( g1.getName(), "TestGraphComponent" ) g2 = TestGraphComponent( "g" ) self.assertEqual( g2.getName(), "g" ) # check calling virtual overrides directly self.assertEqual( g1.acceptsChildCalled, False ) self.assertEqual( g1.acceptsParentCalled, False ) self.assertEqual( g2.acceptsChildCalled, False ) self.assertEqual( g2.acceptsParentCalled, False ) self.failUnless( g1.acceptsChild( g2 ) ) self.failUnless( g1.acceptsParent( g2 ) ) self.failIf( g1.acceptsChild( Gaffer.Node() ) ) self.failIf( g1.acceptsParent( Gaffer.Node() ) ) self.assertEqual( g1.acceptsChildCalled, True ) self.assertEqual( g1.acceptsParentCalled, True ) self.assertEqual( g2.acceptsChildCalled, False ) self.assertEqual( g2.acceptsParentCalled, False ) # check calling virtual overrides indirectly through C++ g1 = TestGraphComponent() g2 = TestGraphComponent( "g" ) self.assertEqual( g1.acceptsChildCalled, False ) self.assertEqual( g1.acceptsParentCalled, False ) self.assertRaises( RuntimeError, g1.addChild, Gaffer.Node() ) self.assertEqual( g1.acceptsChildCalled, True ) self.assertEqual( g1.acceptsParentCalled, False ) self.assertRaises( RuntimeError, Gaffer.GraphComponent().addChild, g1 ) self.assertEqual( g1.acceptsChildCalled, True ) self.assertEqual( g1.acceptsParentCalled, True )
def testRectLightVisibilityAttributes(self): s = Gaffer.ScriptNode() s["diffuse_edf"] = GafferAppleseed.AppleseedLight("diffuse_edf") s["diffuse_edf"].loadShader("diffuse_edf") s["AppleseedAttributes"] = GafferAppleseed.AppleseedAttributes( "AppleseedAttributes") s["AppleseedAttributes"]["in"].setInput(s["diffuse_edf"]["out"]) s["AppleseedAttributes"]["attributes"]["cameraVisibility"][ "value"].setValue(False) s["AppleseedAttributes"]["attributes"]["cameraVisibility"][ "enabled"].setValue(True) s["AppleseedAttributes"]["attributes"]["cameraVisibility"][ "value"].setValue(False) s["AppleseedAttributes"]["attributes"]["cameraVisibility"][ "enabled"].setValue(True) s["AppleseedAttributes"]["attributes"]["lightVisibility"][ "value"].setValue(False) s["AppleseedAttributes"]["attributes"]["lightVisibility"][ "enabled"].setValue(True) s["AppleseedAttributes"]["attributes"]["shadowVisibility"][ "value"].setValue(False) s["AppleseedAttributes"]["attributes"]["shadowVisibility"][ "enabled"].setValue(True) s["AppleseedAttributes"]["attributes"]["diffuseVisibility"][ "value"].setValue(False) s["AppleseedAttributes"]["attributes"]["diffuseVisibility"][ "enabled"].setValue(True) s["AppleseedAttributes"]["attributes"]["specularVisibility"][ "value"].setValue(False) s["AppleseedAttributes"]["attributes"]["specularVisibility"][ "enabled"].setValue(True) s["AppleseedAttributes"]["attributes"]["glossyVisibility"][ "value"].setValue(False) s["AppleseedAttributes"]["attributes"]["glossyVisibility"][ "enabled"].setValue(True) s["render"] = GafferAppleseed.AppleseedRender("AppleseedRender") s["render"]["in"].setInput(s["AppleseedAttributes"]["out"]) s["render"]["mode"].setValue(s["render"].Mode.SceneDescriptionMode) projectFilename = self.temporaryDirectory() + "/test.appleseed" s["render"]["fileName"].setValue(projectFilename) s["render"]["task"].execute() reader = asr.ProjectFileReader() options = asr.ProjectFileReaderOptions.OmitReadingMeshFiles project = reader.read(projectFilename, appleseedProjectSchemaPath(), options) scene = project.get_scene() mainAssembly = scene.assemblies().get_by_name("assembly") objInstance = mainAssembly.object_instances()[0] params = objInstance.get_parameters() visFlags = params['visibility'] self.assertFalse(visFlags['camera']) self.assertFalse(visFlags['diffuse']) self.assertFalse(visFlags['glossy']) self.assertFalse(visFlags['light']) self.assertFalse(visFlags['shadow']) self.assertFalse(visFlags['specular'])
def testMany( self ) : l = [] for i in range( 0, 100000 ) : l.append( Gaffer.GraphComponent() )
def __acquirePlayback( self ) : if self.__playback is None or not self.__playback.context().isSame( self.getContext() ) : self.__playback = GafferUI.Playback.acquire( self.getContext() ) self.__playbackStateChangedConnection = self.__playback.stateChangedSignal().connect( Gaffer.WeakMethod( self.__playbackStateChanged ) )
"description", """ May be incremented to force a reload if the file has changed on disk - otherwise old contents may still be loaded via Gaffer's cache. """, ], }) GafferUI.PlugValueWidget.registerCreator( GafferImage.ImageReader, "fileName", lambda plug: GafferUI.PathPlugValueWidget( plug, path=Gaffer.FileSystemPath( "/", filter=Gaffer.FileSystemPath.createStandardFilter( extensions=GafferImage.ImageReader.supportedExtensions(), extensionsLabel="Show only image files", )), pathChooserDialogueKeywords={ "bookmarks": GafferUI.Bookmarks.acquire(plug, category="image"), "leaf": True, }, )) GafferUI.PlugValueWidget.registerCreator(GafferImage.ImageReader, "refreshCount", GafferUI.IncrementingPlugValueWidget, label="Refresh", undoable=False)
def testUndoMerging(self): s = Gaffer.ScriptNode() s["n"] = Gaffer.Node() s["n"]["p"] = Gaffer.IntPlug() self.assertEqual(s["n"]["p"].getValue(), 0) self.assertFalse(s.undoAvailable()) cs = GafferTest.CapturingSlot(s["n"].plugSetSignal()) with Gaffer.UndoContext(s, mergeGroup="test"): s["n"]["p"].setValue(1) self.assertEqual(len(cs), 1) self.assertEqual(s["n"]["p"].getValue(), 1) self.assertTrue(s.undoAvailable()) with Gaffer.UndoContext(s, mergeGroup="test"): s["n"]["p"].setValue(2) self.assertEqual(len(cs), 2) self.assertEqual(s["n"]["p"].getValue(), 2) self.assertTrue(s.undoAvailable()) with Gaffer.UndoContext(s, mergeGroup="test2"): s["n"]["p"].setValue(3) self.assertEqual(len(cs), 3) self.assertEqual(s["n"]["p"].getValue(), 3) self.assertTrue(s.undoAvailable()) s.undo() self.assertEqual(len(cs), 4) self.assertEqual(s["n"]["p"].getValue(), 2) self.assertTrue(s.undoAvailable()) s.undo() self.assertEqual(len(cs), 5) self.assertEqual(s["n"]["p"].getValue(), 0) self.assertFalse(s.undoAvailable()) s.redo() self.assertEqual(len(cs), 6) self.assertEqual(s["n"]["p"].getValue(), 2) self.assertTrue(s.undoAvailable()) s.undo() self.assertEqual(len(cs), 7) self.assertEqual(s["n"]["p"].getValue(), 0) self.assertFalse(s.undoAvailable()) s.redo() s.redo() self.assertEqual(len(cs), 9) self.assertEqual(s["n"]["p"].getValue(), 3) self.assertTrue(s.undoAvailable()) s.undo() s.undo() self.assertEqual(len(cs), 11) self.assertEqual(s["n"]["p"].getValue(), 0) self.assertFalse(s.undoAvailable())
def __setBookmarked(node, bookmarked): with Gaffer.UndoScope(node.scriptNode()): Gaffer.MetadataAlgo.setBookmarked(node, bookmarked)
def testAcceptsNoneInput(self): p = Gaffer.IntPlug("hello") self.failUnless(p.acceptsInput(None))
def testReadOnlySetValueRaises(self): p = Gaffer.IntPlug(flags=Gaffer.Plug.Flags.Default | Gaffer.Plug.Flags.ReadOnly) self.assertRaises(RuntimeError, p.setValue, 10)
def _run( self, args ) : nodes = [] if not len( args["nodes"] ) : IECore.msg( IECore.Msg.Level.Error, "gaffer dispatch", "No nodes were specified" ) return 1 script = Gaffer.ScriptNode() if args["script"].value : script["fileName"].setValue( os.path.abspath( args["script"].value ) ) try : script.load( continueOnError = args["ignoreScriptLoadErrors"].value ) except Exception as exception : IECore.msg( IECore.Msg.Level.Error, "gaffer dispatch : loading \"%s\"" % script["fileName"].getValue(), str( exception ) ) return 1 self.root()["scripts"].addChild( script ) for nodeName in args["nodes"] : if args["script"].value : node = script.descendant( nodeName ) if node is None : IECore.msg( IECore.Msg.Level.Error, "gaffer dispatch", "\"%s\" does not exist." % nodeName ) return 1 else : node = self.__create( nodeName ) if node is None : return 1 if args["applyUserDefaults"].value : Gaffer.NodeAlgo.applyUserDefaults( node ) script.addChild( node ) nodes.append( node ) dispatcherType = args["dispatcher"].value or GafferDispatch.Dispatcher.getDefaultDispatcherType() dispatchers = [ GafferDispatch.Dispatcher.create( dispatcherType ) ] if not dispatchers[0] : IECore.msg( IECore.Msg.Level.Error, "gaffer dispatch", "{} is not a registered dispatcher.".format( dispatcherType ) ) return 1 if args["gui"].value and len(args["alternateDispatchers"]) : dispatchers.extend( GafferDispatch.Dispatcher.createMatching( " ".join( args["alternateDispatchers"] ) ) ) dispatcherNames = {} for dispatcher in dispatchers : Gaffer.NodeAlgo.applyUserDefaults( dispatcher ) dispatcherNames[dispatcher.getName()] = dispatcher if len(args["settings"]) % 2 : IECore.msg( IECore.Msg.Level.Error, "gaffer dispatch", "\"settings\" parameter must have matching entry/value pairs" ) return 1 for i in range( 0, len(args["settings"]), 2 ) : key = args["settings"][i].lstrip( "-" ) parent = key.split( "." )[0] value = args["settings"][i+1] if key.startswith( "context." ) : entry = key.partition( "context." )[-1] status = self.__setValue( entry, value, script, context=True ) elif key.startswith( "dispatcher." ) : identifier = key.partition( "dispatcher." )[-1] for dispatcher in dispatchers : status = self.__setValue( identifier, value, dispatcher ) elif parent in dispatcherNames : status = self.__setValue( key.partition( parent + "." )[-1], value, dispatcherNames[parent] ) else : status = self.__setValue( key, value, script ) if status : return status if args["gui"].value : import GafferUI import GafferDispatchUI self.__dialogue = GafferDispatchUI.DispatchDialogue( nodes, dispatchers ) self.__dialogueClosedConnection = self.__dialogue.closedSignal().connect( Gaffer.WeakMethod( self.__dialogueClosed ) ) self.__dialogue.setVisible( True ) GafferUI.EventLoop.mainEventLoop().start() else : return self.__dispatch( dispatchers[0], nodes ) return 0
GafferUI.PlugValueWidget.registerCreator(GafferScene.FileSource, "refreshCount", GafferUI.IncrementingPlugValueWidget, label="Refresh", undoable=False) ## \todo Once it's possible to register Widgets to go on the right of a PlugWidget, place the refresh button there. # AlembicSource GafferUI.PlugValueWidget.registerCreator( GafferScene.AlembicSource, "fileName", lambda plug: GafferUI.PathPlugValueWidget( plug, path=Gaffer.FileSystemPath("/", filter=Gaffer.FileSystemPath. createStandardFilter(extensions=["abc"])), pathChooserDialogueKeywords={ "bookmarks": GafferUI.Bookmarks.acquire(plug, category="sceneCache"), "leaf": True, }, )) # AttributeCache GafferUI.PlugValueWidget.registerCreator( GafferScene.AttributeCache, "fileName", lambda plug: GafferUI.PathPlugValueWidget( plug, path=Gaffer.SequencePath("/",
def _run(self, args): if args["cacheMemoryLimit"].value: Gaffer.ValuePlug.setCacheMemoryLimit( 1024 * 1024 * args["cacheMemoryLimit"].value) if args["hashCacheSizeLimit"].value: Gaffer.ValuePlug.setHashCacheSizeLimit( args["hashCacheSizeLimit"].value) self.__timers = collections.OrderedDict() self.__memory = collections.OrderedDict() self.__memory["Application"] = _Memory.maxRSS() script = Gaffer.ScriptNode() script["fileName"].setValue(os.path.abspath(args["script"].value)) with _Timer() as loadingTimer: script.load(continueOnError=True) self.__timers["Loading"] = loadingTimer self.root()["scripts"].addChild(script) self.__memory["Script"] = _Memory.maxRSS( ) - self.__memory["Application"] if args["performanceMonitor"].value: self.__performanceMonitor = Gaffer.PerformanceMonitor() else: self.__performanceMonitor = None if args["contextMonitor"].value: contextMonitorRoot = None if args["contextMonitorRoot"].value: contextMonitorRoot = script.descendant( args["contextMonitorRoot"].value) if contextMonitorRoot is None: IECore.msg( IECore.Msg.Level.Error, "stats", "Context monitor root \"%s\" does not exist" % args["contextMonitorRoot"].value) return 1 self.__contextMonitor = Gaffer.ContextMonitor(contextMonitorRoot) else: self.__contextMonitor = None if args["vtune"].value: try: self.__vtuneMonitor = Gaffer.VTuneMonitor() self.__vtuneMonitor.setActive(True) except AttributeError: IECore.msg(IECore.Msg.Level.Error, "gui", "unable to create requested VTune monitor") self.__output = file(args["outputFile"].value, "w") if args["outputFile"].value else sys.stdout self.__writeVersion(script) self.__output.write("\n") self.__writeArgs(args) self.__output.write("\n") self.__writeSettings(script) self.__output.write("\n") self.__writeVariables(script) self.__output.write("\n") if args["nodeSummary"].value: self.__writeNodes(script) if args["scene"].value: self.__writeScene(script, args) if args["image"].value: self.__writeImage(script, args) if args["task"].value: self.__writeTask(script, args) self.__output.write("\n") self.__writeMemory() self.__output.write("\n") self.__writePerformance(script, args) self.__output.write("\n") self.__writeContext(script, args) self.__output.write("\n") self.__output.close() if args["annotatedScript"].value: if self.__performanceMonitor is not None: Gaffer.MonitorAlgo.annotate( script, self.__performanceMonitor, Gaffer.MonitorAlgo.PerformanceMetric.TotalDuration) Gaffer.MonitorAlgo.annotate( script, self.__performanceMonitor, Gaffer.MonitorAlgo.PerformanceMetric.HashCount) if self.__contextMonitor is not None: Gaffer.MonitorAlgo.annotate(script, self.__contextMonitor) script.serialiseToFile(args["annotatedScript"].value) return 0
def __deletePlug(plug): with Gaffer.UndoScope(plug.ancestor(Gaffer.ScriptNode)): plug.parent().removeChild(plug)
def testEmptyName( self ) : g = Gaffer.GraphComponent() self.assertRaises( RuntimeError, g.setName, "" )
def followBookmark(number, weakEditor, _): editor = weakEditor() if editor is not None: b = Gaffer.NumericBookmarkSet(editor.scriptNode(), number) editor.setNodeSet(b)
def testGetChildWithEmptyName( self ) : g = Gaffer.GraphComponent() self.assertEqual( g.getChild( "" ), None ) self.assertRaises( KeyError, g.__getitem__, "" )
def __connect(inPlug, outPlug): with Gaffer.UndoScope(inPlug.ancestor(Gaffer.ScriptNode)): inPlug.setInput(outPlug)
def testWedge( self ) : s = Gaffer.ScriptNode() s["sphere"] = GafferScene.Sphere() s["sphere"]["sets"].setValue( "${wedge:value}" ) s["filter"] = GafferScene.SetFilter() s["filter"]["setExpression"].setValue( "hidden" ) s["attributes"] = GafferScene.StandardAttributes() s["attributes"]["attributes"]["visibility"]["enabled"].setValue( True ) s["attributes"]["attributes"]["visibility"]["value"].setValue( False ) s["attributes"]["filter"].setInput( s["filter"]["out"] ) s["attributes"]["in"].setInput( s["sphere"]["out"] ) s["outputs"] = GafferScene.Outputs() s["outputs"].addOutput( "beauty", IECoreScene.Output( self.temporaryDirectory() + "/${wedge:value}.tif", "tiff", "rgba", { } ) ) s["outputs"]["in"].setInput( s["attributes"]["out"] ) s["render"] = GafferArnold.ArnoldRender() s["render"]["fileName"].setValue( self.temporaryDirectory() + "/test.####.ass" ) s["render"]["in"].setInput( s["outputs"]["out"] ) s["wedge"] = Gaffer.Wedge() s["wedge"]["mode"].setValue( int( s["wedge"].Mode.StringList ) ) s["wedge"]["strings"].setValue( IECore.StringVectorData( [ "visible", "hidden" ] ) ) s["wedge"]["preTasks"][0].setInput( s["render"]["task"] ) s["fileName"].setValue( self.temporaryDirectory() + "/test.gfr" ) s.save() dispatcher = GafferDispatch.LocalDispatcher() dispatcher["jobsDirectory"].setValue( self.temporaryDirectory() + "/testJobDirectory" ) dispatcher["framesMode"].setValue( GafferDispatch.Dispatcher.FramesMode.CurrentFrame ) dispatcher["executeInBackground"].setValue( False ) dispatcher.dispatch( [ s["wedge"] ] ) hidden = GafferImage.ImageReader() hidden["fileName"].setValue( self.temporaryDirectory() + "/hidden.tif" ) visible = GafferImage.ImageReader() visible["fileName"].setValue( self.temporaryDirectory() + "/visible.tif" ) hiddenStats = GafferImage.ImageStats() hiddenStats["in"].setInput( hidden["out"] ) hiddenStats["area"].setValue( hiddenStats["in"]["dataWindow"].getValue() ) visibleStats = GafferImage.ImageStats() visibleStats["in"].setInput( visible["out"] ) visibleStats["area"].setValue( visibleStats["in"]["dataWindow"].getValue() ) self.assertLess( hiddenStats["average"].getValue()[0], 0.05 ) self.assertGreater( visibleStats["average"].getValue()[0], .27 )
def __contextMenu( self, widget ) : GafferUI.Pointer.setCurrent( None ) self.__menu = GafferUI.Menu( IECore.curry( Gaffer.WeakMethod( self.__menuDefinition ), widget ) ) self.__menu.popup()
def testTransformMotion( self ) : s = Gaffer.ScriptNode() s["plane"] = GafferScene.Plane() s["sphere"] = GafferScene.Sphere() s["group"] = GafferScene.Group() s["group"]["in"][0].setInput( s["plane"]["out"] ) s["group"]["in"][1].setInput( s["sphere"]["out"] ) s["expression"] = Gaffer.Expression() s["expression"].setExpression( inspect.cleandoc( """ parent["plane"]["transform"]["translate"]["x"] = context.getFrame() parent["sphere"]["transform"]["translate"]["y"] = context.getFrame() * 2 parent["group"]["transform"]["translate"]["z"] = context.getFrame() - 1 """ ) ) s["planeFilter"] = GafferScene.PathFilter() s["planeFilter"]["paths"].setValue( IECore.StringVectorData( [ "/group/plane" ] ) ) s["attributes"] = GafferScene.StandardAttributes() s["attributes"]["in"].setInput( s["group"]["out"] ) s["attributes"]["filter"].setInput( s["planeFilter"]["out"] ) s["attributes"]["attributes"]["transformBlur"]["enabled"].setValue( True ) s["attributes"]["attributes"]["transformBlur"]["value"].setValue( False ) s["options"] = GafferScene.StandardOptions() s["options"]["in"].setInput( s["attributes"]["out"] ) s["options"]["options"]["shutter"]["enabled"].setValue( True ) s["options"]["options"]["transformBlur"]["enabled"].setValue( True ) s["render"] = GafferArnold.ArnoldRender() s["render"]["in"].setInput( s["options"]["out"] ) s["render"]["mode"].setValue( s["render"].Mode.SceneDescriptionMode ) s["render"]["fileName"].setValue( self.temporaryDirectory() + "/test.ass" ) # No motion blur s["options"]["options"]["transformBlur"]["value"].setValue( False ) s["render"]["task"].execute() with IECoreArnold.UniverseBlock( writable = True ) : arnold.AiASSLoad( self.temporaryDirectory() + "/test.ass" ) camera = arnold.AiNodeLookUpByName( "gaffer:defaultCamera" ) sphere = arnold.AiNodeLookUpByName( "/group/sphere" ) sphereMotionStart = arnold.AiNodeGetFlt( sphere, "motion_start" ) sphereMotionEnd = arnold.AiNodeGetFlt( sphere, "motion_end" ) sphereMatrix = arnold.AiNodeGetMatrix( sphere, "matrix" ) plane = arnold.AiNodeLookUpByName( "/group/plane" ) planeMotionStart = arnold.AiNodeGetFlt( plane, "motion_start" ) planeMotionEnd = arnold.AiNodeGetFlt( plane, "motion_end" ) planeMatrix = arnold.AiNodeGetMatrix( plane, "matrix" ) # Motion parameters should be left at default self.assertEqual( sphereMotionStart, 0 ) self.assertEqual( sphereMotionEnd, 1 ) self.assertEqual( planeMotionStart, 0 ) self.assertEqual( planeMotionEnd, 1 ) expectedSphereMatrix = arnold.AiM4Translation( arnold.AtVector( 0, 2, 0 ) ) expectedPlaneMatrix = arnold.AiM4Translation( arnold.AtVector( 1, 0, 0 ) ) self.assertEqual( self.__m44f( sphereMatrix ), self.__m44f( expectedSphereMatrix ) ) self.assertEqual( self.__m44f( planeMatrix ), self.__m44f( expectedPlaneMatrix ) ) self.assertEqual( arnold.AiNodeGetFlt( camera, "shutter_start" ), 1 ) self.assertEqual( arnold.AiNodeGetFlt( camera, "shutter_end" ), 1 ) # Motion blur s["options"]["options"]["transformBlur"]["value"].setValue( True ) s["render"]["task"].execute() with IECoreArnold.UniverseBlock( writable = True ) : arnold.AiASSLoad( self.temporaryDirectory() + "/test.ass" ) camera = arnold.AiNodeLookUpByName( "gaffer:defaultCamera" ) sphere = arnold.AiNodeLookUpByName( "/group/sphere" ) sphereMotionStart = arnold.AiNodeGetFlt( sphere, "motion_start" ) sphereMotionEnd = arnold.AiNodeGetFlt( sphere, "motion_end" ) sphereMatrices = arnold.AiNodeGetArray( sphere, "matrix" ) plane = arnold.AiNodeLookUpByName( "/group/plane" ) planeMotionStart = arnold.AiNodeGetFlt( plane, "motion_start" ) planeMotionEnd = arnold.AiNodeGetFlt( plane, "motion_end" ) planeMatrices = arnold.AiNodeGetArray( plane, "matrix" ) self.assertEqual( sphereMotionStart, 0.75 ) self.assertEqual( sphereMotionEnd, 1.25 ) self.assertEqual( arnold.AiArrayGetNumElements( sphereMatrices.contents ), 1 ) self.assertEqual( arnold.AiArrayGetNumKeys( sphereMatrices.contents ), 2 ) self.assertEqual( planeMotionStart, 0.75 ) self.assertEqual( planeMotionEnd, 1.25 ) self.assertEqual( arnold.AiArrayGetNumElements( planeMatrices.contents ), 1 ) self.assertEqual( arnold.AiArrayGetNumKeys( planeMatrices.contents ), 2 ) for i in range( 0, 2 ) : frame = 0.75 + 0.5 * i sphereMatrix = arnold.AiArrayGetMtx( sphereMatrices, i ) expectedSphereMatrix = arnold.AiM4Translation( arnold.AtVector( 0, frame * 2, frame - 1 ) ) planeMatrix = arnold.AiArrayGetMtx( planeMatrices, i ) expectedPlaneMatrix = arnold.AiM4Translation( arnold.AtVector( 1, 0, frame - 1 ) ) self.assertEqual( self.__m44f( sphereMatrix ), self.__m44f( expectedSphereMatrix ) ) self.assertEqual( self.__m44f( planeMatrix ), self.__m44f( expectedPlaneMatrix ) ) self.assertEqual( arnold.AiNodeGetFlt( camera, "shutter_start" ), 0.75 ) self.assertEqual( arnold.AiNodeGetFlt( camera, "shutter_end" ), 1.25 ) # Motion blur on, but sampleMotion off s["options"]["options"]["sampleMotion"]["enabled"].setValue( True ) s["options"]["options"]["sampleMotion"]["value"].setValue( False ) s["render"]["task"].execute() with IECoreArnold.UniverseBlock( writable = True ) : arnold.AiASSLoad( self.temporaryDirectory() + "/test.ass" ) camera = arnold.AiNodeLookUpByName( "gaffer:defaultCamera" ) sphere = arnold.AiNodeLookUpByName( "/group/sphere" ) sphereMotionStart = arnold.AiNodeGetFlt( sphere, "motion_start" ) sphereMotionEnd = arnold.AiNodeGetFlt( sphere, "motion_end" ) sphereMatrices = arnold.AiNodeGetArray( sphere, "matrix" ) plane = arnold.AiNodeLookUpByName( "/group/plane" ) planeMotionStart = arnold.AiNodeGetFlt( plane, "motion_start" ) planeMotionEnd = arnold.AiNodeGetFlt( plane, "motion_end" ) planeMatrices = arnold.AiNodeGetArray( plane, "matrix" ) self.assertEqual( sphereMotionStart, 0.75 ) self.assertEqual( sphereMotionEnd, 1.25 ) self.assertEqual( arnold.AiArrayGetNumElements( sphereMatrices.contents ), 1 ) self.assertEqual( arnold.AiArrayGetNumKeys( sphereMatrices.contents ), 2 ) self.assertEqual( planeMotionStart, 0.75 ) self.assertEqual( planeMotionEnd, 1.25 ) self.assertEqual( arnold.AiArrayGetNumElements( planeMatrices.contents ), 1 ) self.assertEqual( arnold.AiArrayGetNumKeys( planeMatrices.contents ), 2 ) for i in range( 0, 2 ) : frame = 0.75 + 0.5 * i sphereMatrix = arnold.AiArrayGetMtx( sphereMatrices, i ) expectedSphereMatrix = arnold.AiM4Translation( arnold.AtVector( 0, frame * 2, frame - 1 ) ) planeMatrix = arnold.AiArrayGetMtx( planeMatrices, i ) expectedPlaneMatrix = arnold.AiM4Translation( arnold.AtVector( 1, 0, frame - 1 ) ) self.assertEqual( self.__m44f( sphereMatrix ), self.__m44f( expectedSphereMatrix ) ) self.assertEqual( self.__m44f( planeMatrix ), self.__m44f( expectedPlaneMatrix ) ) self.assertEqual( arnold.AiNodeGetFlt( camera, "shutter_start" ), 0.75 ) self.assertEqual( arnold.AiNodeGetFlt( camera, "shutter_end" ), 0.75 )
def __setValue( plug, value, *unused ) : with Gaffer.UndoScope( plug.ancestor( Gaffer.ScriptNode ) ) : plug.setValue( value )
def testRenderRegion( self ) : s = Gaffer.ScriptNode() s["camera"] = GafferScene.Camera() s["options"] = GafferScene.StandardOptions() s["options"]["in"].setInput( s["camera"]["out"] ) s["options"]["options"]["renderCamera"]["enabled"].setValue( True ) s["options"]["options"]["renderCamera"]["value"].setValue( "/camera" ) s["render"] = GafferArnold.ArnoldRender() s["render"]["in"].setInput( s["options"]["out"] ) s["render"]["mode"].setValue( s["render"].Mode.SceneDescriptionMode ) s["render"]["fileName"].setValue( self.temporaryDirectory() + "/test.ass" ) # Default region s["render"]["task"].execute() with IECoreArnold.UniverseBlock( writable = True ) : arnold.AiASSLoad( self.temporaryDirectory() + "/test.ass" ) options = arnold.AiUniverseGetOptions() self.assertEqual( arnold.AiNodeGetInt( options, "xres" ), 640 ) self.assertEqual( arnold.AiNodeGetInt( options, "yres" ), 480 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_min_x" ), 0 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_max_x" ), 639 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_min_y" ), 0 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_max_y" ), 479 ) # Apply Crop Window s["options"]["options"]["renderCropWindow"]["enabled"].setValue( True ) s["options"]["options"]["renderCropWindow"]["value"].setValue( imath.Box2f( imath.V2f( 0.25, 0.5 ), imath.V2f( 0.75, 1.0 ) ) ) s["render"]["task"].execute() with IECoreArnold.UniverseBlock( writable = True ) : arnold.AiASSLoad( self.temporaryDirectory() + "/test.ass" ) options = arnold.AiUniverseGetOptions() self.assertEqual( arnold.AiNodeGetInt( options, "xres" ), 640 ) self.assertEqual( arnold.AiNodeGetInt( options, "yres" ), 480 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_min_x" ), 160 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_max_x" ), 479 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_min_y" ), 240 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_max_y" ), 479 ) # Test Empty Crop Window s["options"]["options"]["renderCropWindow"]["value"].setValue( imath.Box2f() ) s["render"]["task"].execute() with IECoreArnold.UniverseBlock( writable = True ) : arnold.AiASSLoad( self.temporaryDirectory() + "/test.ass" ) options = arnold.AiUniverseGetOptions() self.assertEqual( arnold.AiNodeGetInt( options, "xres" ), 640 ) self.assertEqual( arnold.AiNodeGetInt( options, "yres" ), 480 ) # Since Arnold doesn't support empty regions, we default to one pixel in the corner self.assertEqual( arnold.AiNodeGetInt( options, "region_min_x" ), 0 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_max_x" ), 0 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_min_y" ), 479 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_max_y" ), 479 ) # Apply Overscan s["options"]["options"]["renderCropWindow"]["enabled"].setValue( False ) s["options"]["options"]["overscan"]["enabled"].setValue( True ) s["options"]["options"]["overscan"]["value"].setValue( True ) s["options"]["options"]["overscanTop"]["enabled"].setValue( True ) s["options"]["options"]["overscanTop"]["value"].setValue( 0.1 ) s["options"]["options"]["overscanBottom"]["enabled"].setValue( True ) s["options"]["options"]["overscanBottom"]["value"].setValue( 0.2 ) s["options"]["options"]["overscanLeft"]["enabled"].setValue( True ) s["options"]["options"]["overscanLeft"]["value"].setValue( 0.3 ) s["options"]["options"]["overscanRight"]["enabled"].setValue( True ) s["options"]["options"]["overscanRight"]["value"].setValue( 0.4 ) s["render"]["task"].execute() with IECoreArnold.UniverseBlock( writable = True ) : arnold.AiASSLoad( self.temporaryDirectory() + "/test.ass" ) options = arnold.AiUniverseGetOptions() self.assertEqual( arnold.AiNodeGetInt( options, "xres" ), 640 ) self.assertEqual( arnold.AiNodeGetInt( options, "yres" ), 480 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_min_x" ), -192 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_max_x" ), 640 + 255 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_min_y" ), -48 ) self.assertEqual( arnold.AiNodeGetInt( options, "region_max_y" ), 480 + 95 )
def testDependencyNodeAcceptsNoneInputs( self ) : n = Gaffer.SwitchDependencyNode() self.assertTrue( n["enabled"].acceptsInput( None ) ) self.assertTrue( n["index"].acceptsInput( None ) )
def __init__(self, scriptNode, **kw): self.__row = GafferUI.ListContainer( GafferUI.ListContainer.Orientation.Horizontal, borderWidth=4, spacing=2) GafferUI.EditorWidget.__init__(self, self.__row, scriptNode, **kw) with self.__row: self.__visibilityButton = GafferUI.Button(image="timeline3.png", hasFrame=False) self.__visibilityButtonClickedConnection = self.__visibilityButton.clickedSignal( ).connect(Gaffer.WeakMethod(self.__visibilityButtonClicked)) self.__scriptRangeStart = GafferUI.NumericPlugValueWidget( scriptNode["frameRange"]["start"]) self.__scriptRangeStart.numericWidget().setFixedCharacterWidth(4) self.__scriptRangeStart.setToolTip( self.__scriptRangeStart.getPlug().fullName()) self.__sliderRangeStart = GafferUI.NumericWidget( scriptNode["frameRange"]["start"].getValue()) self.__sliderRangeStart.setFixedCharacterWidth(4) self.__sliderRangeStart.setToolTip("Slider minimum") self.__sliderRangeStartChangedConnection = self.__sliderRangeStart.editingFinishedSignal( ).connect(Gaffer.WeakMethod(self.__sliderRangeChanged)) self.__slider = GafferUI.NumericSlider( value=self.getContext().getFrame(), min=float(scriptNode["frameRange"]["start"].getValue()), max=float(scriptNode["frameRange"]["end"].getValue()), parenting={"expand": True}, ) self.__slider.setPositionIncrement( 0 ) # disable so the slider doesn't mask our global frame increment shortcut self.__sliderValueChangedConnection = self.__slider.valueChangedSignal( ).connect(Gaffer.WeakMethod(self.__valueChanged)) self.__startButton = GafferUI.Button(image="timelineStart.png", hasFrame=False) self.__startButtonClickedConnection = self.__startButton.clickedSignal( ).connect(Gaffer.WeakMethod(self.__startOrEndButtonClicked)) self.__playPause = GafferUI.Button(image="timelinePlay.png", hasFrame=False) self.__playPauseClickedConnection = self.__playPause.clickedSignal( ).connect(Gaffer.WeakMethod(self.__playPauseClicked)) self.__endButton = GafferUI.Button(image="timelineEnd.png", hasFrame=False) self.__endButtonClickedConnection = self.__endButton.clickedSignal( ).connect(Gaffer.WeakMethod(self.__startOrEndButtonClicked)) self.__frame = GafferUI.NumericWidget(self.getContext().getFrame()) self.__frame.setFixedCharacterWidth(5) self.__frame.setToolTip("Current frame") self.__frameChangedConnection = self.__frame.valueChangedSignal( ).connect(Gaffer.WeakMethod(self.__valueChanged)) self.__sliderRangeEnd = GafferUI.NumericWidget( scriptNode["frameRange"]["end"].getValue()) self.__sliderRangeEnd.setFixedCharacterWidth(4) self.__sliderRangeEnd.setToolTip("Slider maximum") self.__sliderRangeEndChangedConnection = self.__sliderRangeEnd.editingFinishedSignal( ).connect(Gaffer.WeakMethod(self.__sliderRangeChanged)) self.__scriptRangeEnd = GafferUI.NumericPlugValueWidget( scriptNode["frameRange"]["end"]) self.__scriptRangeEnd.numericWidget().setFixedCharacterWidth(4) self.__scriptRangeEnd.setToolTip( self.__scriptRangeEnd.getPlug().fullName()) self.__scriptNodePlugSetConnection = scriptNode.plugSetSignal( ).connect(Gaffer.WeakMethod(self.__scriptNodePlugSet)) frameIncrementShortcut = QtGui.QShortcut(QtGui.QKeySequence("Right"), self._qtWidget()) frameIncrementShortcut.activated.connect( Gaffer.WeakMethod(self.__incrementFrame)) frameDecrementShortcut = QtGui.QShortcut(QtGui.QKeySequence("Left"), self._qtWidget()) frameDecrementShortcut.activated.connect( IECore.curry(Gaffer.WeakMethod(self.__incrementFrame), -1)) self.__playback = None self._updateFromContext(set())
def testContains( self ) : n = Gaffer.GraphComponent() self.failIf( "c" in n ) n["c"] = Gaffer.GraphComponent() self.failUnless( "c" in n )
def testRoot( self ) : script = Gaffer.ScriptNode() script["sphere"] = GafferScene.Sphere() script["sphere"]["sets"].setValue( "sphereSet" ) script["group"] = GafferScene.Group() script["group"]["in"][0].setInput( script["sphere"]["out"] ) script["cube"] = GafferScene.Cube() script["cube"]["sets"].setValue( "cubeSet" ) script["switch"] = Gaffer.Switch() script["switch"].setup( GafferScene.ScenePlug() ) script["switch"]["in"][0].setInput( script["group"]["out"] ) script["switch"]["in"][1].setInput( script["cube"]["out"] ) script["collect"] = GafferScene.CollectScenes() script["collect"]["in"].setInput( script["switch"]["out"] ) script["collect"]["rootNames"].setValue( IECore.StringVectorData( [ "0", "1", "2", "3" ] ) ) script["expression"] = Gaffer.Expression() script["expression"].setExpression( inspect.cleandoc( """ root = context.get( "collect:rootName", "0" ) parent["switch"]["index"] = int( root ) > 1 parent["collect"]["sourceRoot"] = { "0" : "", "1" : "/group", "2" : "/", "3" : "/cube" }[root] """ ) ) self.assertEqual( script["collect"]["out"].childNames( "/" ), IECore.InternedStringVectorData( [ "0", "1", "2", "3" ] ) ) self.assertEqual( script["collect"]["out"].childNames( "/0" ), IECore.InternedStringVectorData( [ "group" ] ) ) self.assertEqual( script["collect"]["out"].childNames( "/1" ), IECore.InternedStringVectorData( [ "sphere" ] ) ) self.assertEqual( script["collect"]["out"].childNames( "/2" ), IECore.InternedStringVectorData( [ "cube" ] ) ) self.assertEqual( script["collect"]["out"].childNames( "/3" ), IECore.InternedStringVectorData() ) self.assertEqual( script["collect"]["out"].object( "/0" ), IECore.NullObject() ) self.assertEqual( script["collect"]["out"].object( "/1" ), IECore.NullObject() ) self.assertEqual( script["collect"]["out"].object( "/2" ), IECore.NullObject() ) self.assertEqual( script["collect"]["out"].object( "/3" ), script["cube"]["out"].object( "/cube" ) ) self.assertEqual( script["collect"]["out"].childNames( "/0/group" ), IECore.InternedStringVectorData( [ "sphere" ] ) ) self.assertEqual( script["collect"]["out"].childNames( "/1/sphere" ), IECore.InternedStringVectorData() ) self.assertEqual( script["collect"]["out"].childNames( "/2/cube" ), IECore.InternedStringVectorData() ) self.assertEqual( script["collect"]["out"].object( "/0/group" ), IECore.NullObject() ) self.assertEqual( script["collect"]["out"].object( "/1/sphere" ), script["sphere"]["out"].object( "/sphere" ) ) self.assertEqual( script["collect"]["out"].object( "/2/cube" ), script["cube"]["out"].object( "/cube" ) ) self.assertEqual( script["collect"]["out"].childNames( "/0/group/sphere" ), IECore.InternedStringVectorData() ) self.assertEqual( script["collect"]["out"].object( "/0/group/sphere" ), script["sphere"]["out"].object( "/sphere" ) ) self.assertEqual( script["collect"]["out"]["setNames"].getValue(), IECore.InternedStringVectorData( [ "sphereSet", "cubeSet" ] ) ) self.assertEqual( set( script["collect"]["out"].set( "sphereSet" ).value.paths() ), { "/0/group/sphere", "/1/sphere", } ) self.assertEqual( set( script["collect"]["out"].set( "cubeSet" ).value.paths() ), { "/2/cube", "/3", } )
def __init__(self, name="ColoriseSHO"): GafferImage.ImageProcessor.__init__(self, name) self["show"] = Gaffer.IntPlug(defaultValue=0, minValue=0, maxValue=3) # Channel colorising merge = GafferImage.Merge() self["__Merge"] = merge merge["operation"].setValue(0) outputSwitch = Gaffer.Switch() self["__Switch_output"] = outputSwitch outputSwitch.setup(self["out"]) outputSwitch["index"].setInput(self["show"]) outputSwitch["in"][0].setInput(merge["out"]) for channel in GafferAstro.NarrowbandChannels: self["source%s" % channel] = Gaffer.StringPlug( defaultValue='%s.input' % channel) self["range%s" % channel] = Gaffer.V2fPlug(defaultValue=imath.V2f(0, 1)) self["map%s" % channel] = Gaffer.SplinefColor4fPlug( defaultValue=self.__mapDefaults[channel]) self["saturation%s" % channel] = Gaffer.FloatPlug(defaultValue=1.0, minValue=0.0) self["multiply%s" % channel] = Gaffer.FloatPlug(defaultValue=1.0) self["gamma%s" % channel] = Gaffer.FloatPlug(defaultValue=1.0) colorise = GafferAstro.Colorise() self["__Colorise_%s" % channel] = colorise colorise["in"].setInput(self["in"]) colorise["channel"].setInput(self["source%s" % channel]) colorise["mapEnabled"].setValue(True) colorise["range"].setInput(self["range%s" % channel]) colorise["enabled"].setInput(colorise["channel"]) # Work around issue where setInput doesn't sync the number of knots colorise["map"].setValue(self["map%s" % channel].getValue()) colorise["map"].setInput(self["map%s" % channel]) cdl = GafferImage.CDL() self["__CDL_%s" % channel] = cdl cdl["in"].setInput(colorise["out"]) cdl["saturation"].setInput(self["saturation%s" % channel]) grade = GafferImage.Grade() self["__Grade_%s" % channel] = grade grade["in"].setInput(cdl["out"]) grade["multiply"].gang() grade["multiply"]["r"].setInput(self["multiply%s" % channel]) grade["gamma"].gang() grade["gamma"]["r"].setInput(self["gamma%s" % channel]) merge["in"][len(merge["in"]) - 1].setInput(grade["out"]) outputSwitch["in"][len(outputSwitch["in"]) - 1].setInput( grade["out"]) self["saturation"] = Gaffer.FloatPlug(defaultValue=1.0, minValue=0.0) self["blackPoint"] = Gaffer.FloatPlug(defaultValue=0.0) self["whitePoint"] = Gaffer.FloatPlug(defaultValue=1.0) self["multiply"] = Gaffer.Color4fPlug( defaultValue=imath.Color4f(1, 1, 1, 1)) self["gamma"] = Gaffer.FloatPlug(defaultValue=1.0, minValue=0.0) outputCdl = GafferImage.CDL() self["__CDL_output"] = outputCdl outputCdl["in"].setInput(outputSwitch["out"]) outputCdl["saturation"].setInput(self["saturation"]) outputGrade = GafferImage.Grade() self["__Grade_output"] = outputGrade outputGrade["in"].setInput(outputCdl["out"]) outputGrade["blackPoint"].gang() outputGrade["blackPoint"]["r"].setInput(self["blackPoint"]) outputGrade["whitePoint"].gang() outputGrade["whitePoint"]["r"].setInput(self["whitePoint"]) outputGrade["multiply"].setInput(self["multiply"]) outputGrade["gamma"].gang() outputGrade["gamma"]["r"].setInput(self["gamma"]) copyChannels = GafferImage.CopyChannels() self["__CopyChannels"] = copyChannels copyChannels["in"][0].setInput(self["in"]) copyChannels["in"][1].setInput(outputGrade["out"]) copyChannels["channels"].setValue("*") self["out"].setInput(copyChannels["out"])
def test( self ) : # Make a few input scenes script = Gaffer.ScriptNode() script["sphere"] = GafferScene.Sphere() script["sphere"]["sets"].setValue( "spheres" ) script["cube"] = GafferScene.Cube() script["cube"]["sets"].setValue( "cubes" ) script["group"] = GafferScene.Group() script["group"]["in"][0].setInput( script["sphere"]["out"] ) script["group"]["in"][1].setInput( script["cube"]["out"] ) script["switch"] = Gaffer.Switch() script["switch"].setup( GafferScene.ScenePlug() ) script["switch"]["in"][0].setInput( script["sphere"]["out"] ) script["switch"]["in"][1].setInput( script["cube"]["out"] ) script["switch"]["in"][2].setInput( script["group"]["out"] ) # Make an empty CollectScenes script["collect"] = GafferScene.CollectScenes() script["collect"]["in"].setInput( script["switch"]["out"] ) self.assertSceneValid( script["collect"]["out"] ) self.assertEqual( script["collect"]["out"].childNames( "/" ), IECore.InternedStringVectorData() ) # Configure it to collect the input scenes script["collect"]["rootNames"].setValue( IECore.StringVectorData( [ "sphere", "cube", "group" ] ) ) script["expression"] = Gaffer.Expression() script["expression"].setExpression( inspect.cleandoc( """ scenes = parent["collect"]["rootNames"] parent["switch"]["index"] = scenes.index( context.get( "collect:rootName", "sphere" ) ) """ ) ) # Check we get what we expect self.assertEqual( script["collect"]["out"].childNames( "/" ), IECore.InternedStringVectorData( [ "sphere", "cube", "group" ] ) ) self.assertSceneValid( script["collect"]["out"] ) script["subTree"] = GafferScene.SubTree() script["subTree"]["in"].setInput( script["collect"]["out"] ) script["subTree"]["root"].setValue( "/sphere" ) self.assertScenesEqual( script["subTree"]["out"], script["sphere"]["out"], checks = self.allSceneChecks - { "sets" } ) script["subTree"]["root"].setValue( "/cube" ) self.assertScenesEqual( script["subTree"]["out"], script["cube"]["out"], checks = self.allSceneChecks - { "sets" } ) script["subTree"]["root"].setValue( "/group" ) self.assertScenesEqual( script["subTree"]["out"], script["group"]["out"] ) # Check the sets too self.assertEqual( script["collect"]["out"]["setNames"].getValue(), IECore.InternedStringVectorData( [ "spheres", "cubes" ] ) ) self.assertEqual( script["collect"]["out"].set( "spheres" ).value, IECore.PathMatcher( [ "/sphere/sphere", "/group/group/sphere" ] ) ) self.assertEqual( script["collect"]["out"].set( "cubes" ).value, IECore.PathMatcher( [ "/cube/cube", "/group/group/cube" ] ) )
def testExceptionsDuringCompute(self): # Make this scene # # - bigSphere # - littleSphere (with exception in attributes expression) s = Gaffer.ScriptNode() s["s1"] = GafferScene.Sphere() s["s1"]["name"].setValue("bigSphere") s["s2"] = GafferScene.Sphere() s["s2"]["name"].setValue("littleSphere") s["s2"]["radius"].setValue(0.1) s["p"] = GafferScene.Parent() s["p"]["in"].setInput(s["s1"]["out"]) s["p"]["child"].setInput(s["s2"]["out"]) s["p"]["parent"].setValue("/bigSphere") s["a"] = GafferScene.StandardAttributes() s["a"]["in"].setInput(s["p"]["out"]) s["a"]["attributes"]["doubleSided"]["enabled"].setValue(True) s["e"] = Gaffer.Expression() s["e"].setExpression( 'parent["a"]["attributes"]["doubleSided"]["value"] = context["nonexistent"]' ) s["f"] = GafferScene.PathFilter() s["f"]["paths"].setValue( IECore.StringVectorData(["/bigSphere/littleSphere"])) s["a"]["filter"].setInput(s["f"]["out"]) # Try to view it sg = GafferSceneUI.SceneGadget() sg.setScene(s["a"]["out"]) sg.setMinimumExpansionDepth(4) with GafferUI.Window() as w: gw = GafferUI.GadgetWidget(sg) gw.getViewportGadget().setPlanarMovement(False) gw.getViewportGadget().setCamera( IECoreScene.Camera(parameters={ "projection": "perspective", })) originalMessageHandler = IECore.MessageHandler.getDefaultHandler() mh = IECore.CapturingMessageHandler() IECore.MessageHandler.setDefaultHandler( IECore.LevelFilteredMessageHandler( mh, IECore.LevelFilteredMessageHandler.defaultLevel())) try: w.setVisible(True) self.waitForIdle(1000) sg.waitForCompletion() # Check we were told about the problem self.assertEqual(len(mh.messages), 1) self.assertEqual(mh.messages[0].level, mh.Level.Error) self.assertTrue("nonexistent" in mh.messages[0].message) # And that there isn't some half-assed partial scene # being displayed. self.assertTrue(sg.bound().isEmpty()) gw.getViewportGadget().frame( imath.Box3f(imath.V3f(-1), imath.V3f(1))) self.assertObjectAt(sg, imath.V2f(0.5), None) # And that redraws don't cause more fruitless attempts # to compute the scene. gw.getViewportGadget().frame( imath.Box3f(imath.V3f(-1.1), imath.V3f(1.1))) self.waitForIdle(1000) self.assertEqual(len(mh.messages), 1) self.assertObjectAt(sg, imath.V2f(0.5), None) self.assertTrue(sg.bound().isEmpty()) # Fix the problem with the scene, and check that we can see something now s["f"]["enabled"].setValue(False) sg.waitForCompletion() self.assertEqual(len(mh.messages), 1) self.assertFalse(sg.bound().isEmpty()) self.assertObjectAt(sg, imath.V2f(0.5), IECore.InternedStringVectorData(["bigSphere"])) finally: IECore.MessageHandler.setDefaultHandler(originalMessageHandler)
def testSerialise(self): s = Gaffer.ScriptNode() s["c"] = GafferScene.Cube() ss = s.serialise()