def test_removeObserver(self): foo = Foo() object = vtk.vtkObject() object2 = vtk.vtkObject() event = vtk.vtkCommand.ModifiedEvent callback = foo.onObjectModified callback2 = foo.onObjectModifiedAgain self.assertEqual(len(foo.Observations), 0) foo.addObserver(object, event, callback) foo.addObserver(object2, event, callback) foo.addObserver(object, event, callback2) foo.addObserver(object2, event, callback2) self.assertEqual(len(foo.Observations), 4) foo.removeObserver(object2, event, callback) self.assertEqual(len(foo.Observations), 3) foo.removeObserver(object, event, callback) self.assertEqual(len(foo.Observations), 2) foo.removeObserver(object, event, callback2) self.assertEqual(len(foo.Observations), 1) foo.removeObserver(object2, event, callback2) self.assertEqual(len(foo.Observations), 0)
def testObjId(self): map = vtk.vtkObjectIdMap() # Just make sure if we call it twice with None, the results match objId1 = map.GetGlobalId(None) objId1b = map.GetGlobalId(None) print('Object ids for None: objId1 => ',objId1,', objId1b => ',objId1b) self.assertTrue(objId1 == objId1b) object2 = vtk.vtkObject() addr2 = object2.__this__ addr2 = addr2[1:addr2.find('_', 1)] addr2 = int(addr2, 16) object3 = vtk.vtkObject() addr3 = object3.__this__ addr3 = addr3[1:addr3.find('_', 1)] addr3 = int(addr3, 16) # insert the bigger address first if (addr2 < addr3): object2, object3 = object3, object2 objId2 = map.GetGlobalId(object2) objId2b = map.GetGlobalId(object2) print('Object ids for object2: objId2 => ',objId2,', objId2b => ',objId2b) self.assertTrue(objId2 == objId2b) objId3 = map.GetGlobalId(object3) objId3b = map.GetGlobalId(object3) print('Object ids for object3: objId3 => ',objId3,', objId3b => ',objId3b) self.assertTrue(objId3 == objId3b)
def testObjId(self): map = vtk.vtkObjectIdMap() # Just make sure if we call it twice with None, the results match objId1 = map.GetGlobalId(None) objId1b = map.GetGlobalId(None) print('Object ids for None: objId1 => ', objId1, ', objId1b => ', objId1b) self.assertTrue(objId1 == objId1b) object2 = vtk.vtkObject() addr2 = object2.__this__ addr2 = addr2[1:addr2.find('_', 1)] addr2 = int(addr2, 16) object3 = vtk.vtkObject() addr3 = object3.__this__ addr3 = addr3[1:addr3.find('_', 1)] addr3 = int(addr3, 16) # insert the bigger address first if (addr2 < addr3): object2, object3 = object3, object2 objId2 = map.GetGlobalId(object2) objId2b = map.GetGlobalId(object2) print('Object ids for object2: objId2 => ', objId2, ', objId2b => ', objId2b) self.assertTrue(objId2 == objId2b) objId3 = map.GetGlobalId(object3) objId3b = map.GetGlobalId(object3) print('Object ids for object3: objId3 => ', objId3, ', objId3b => ', objId3b) self.assertTrue(objId3 == objId3b)
def __init__(self): EventHandler.EventHandler.__init__(self) # default name is the class name, minus the "Factory" self._Name = self.__class__.__name__ if self._Name[-7:] == 'Factory': self._Name = self._Name[0:-7] # Store the modified time self._MTime = vtk.vtkObject() self._RenderTime = vtk.vtkObject() # list of renderers the actors are displayed in self._Renderers = [] # dictionary of actors for each renderer self._ActorDict = {} # ActorFactories which are children of this one self._Children = [] # the transform for all of the actors self._Transform = vtk.vtkTransform() # this transform is used as a spare self._DummyTransform = vtk.vtkTransform()
def testGhostForDict(self): """Ghost an object to save the dict""" o = vtk.vtkObject() o.customattr = 'hello' a = vtk.vtkVariantArray() a.InsertNextValue(o) i = id(o) del o o = vtk.vtkObject() o = a.GetValue(0).ToVTKObject() # make sure the id has changed, but dict the same self.assertEqual(o.customattr, 'hello') self.assertNotEqual(i, id(o))
def setUp(self): self.vtkObjs = [vtk.vtkObject() for _ in range(30)] self.collection = vtk.vtkCollection() for obj in self.vtkObjs: self.collection.AddItem(obj) self.emptyCollection = vtk.vtkCollection()
def __init__(self): ActorFactory.ActorFactory.__init__(self) self.markList = [] self.positionList = [] # none transformed position list self.captions = [] self.activeIndex = None self._defaultCaptionVisibility = False self.cursorMark = None self.curpos = None # sizes self.markSize = 10. self.cursorMarkSize = 12. # colors self.cursorMarkColor = (1, 0, 0) # red self.markColor = (1, 1, 0) # yellow self._markTransform = vtk.vtkTransform() self._markTransform.AddObserver('ModifiedEvent', self._OnTransformModified) self._transformedView = False self.eventObject = vtk.vtkObject()
def testProxy(self): o = vtk.vtkObject() proxy = weakref.proxy(o) self.assertEqual(proxy.GetClassName(), 'vtkObject') del o self.assertRaises(weakref.ReferenceError, getattr, proxy, 'GetClassName')
def test_hasObserver(self): foo = Foo() object = vtk.vtkObject() object2 = vtk.vtkObject() event = vtk.vtkCommand.ModifiedEvent callback = foo.onObjectModified self.assertFalse(foo.hasObserver(object, event, callback)) self.assertFalse(foo.hasObserver(object2, event, callback)) foo.addObserver(object, event, callback) self.assertTrue(foo.hasObserver(object, event, callback)) self.assertFalse(foo.hasObserver(object2, event, callback)) foo.addObserver(object2, event, callback) self.assertTrue(foo.hasObserver(object, event, callback)) self.assertTrue(foo.hasObserver(object2, event, callback))
def __init__(self): ActorFactory.ActorFactory.__init__(self) self.markList = [] self.positionList = [] # none transformed position list self.captions = [] self.activeIndex = None self._defaultCaptionVisibility = False self.cursorMark = None self.curpos = None # sizes self.markSize = 10. self.cursorMarkSize = 12. # colors self.cursorMarkColor = (1, 0, 0) # red self.markColor = (1, 1, 0) # yellow self._markTransform = vtk.vtkTransform() self._markTransform.AddObserver( 'ModifiedEvent', self._OnTransformModified) self._transformedView = False self.eventObject = vtk.vtkObject()
def test_observer(self): foo = Foo() object = vtk.vtkObject() object2 = vtk.vtkObject() event = vtk.vtkCommand.ModifiedEvent callback = foo.onObjectModified callback2 = foo.onObjectModifiedAgain self.assertEqual(foo.observer(event, callback), None) foo.addObserver(object, event, callback) self.assertEqual(foo.observer(event, callback), object) # observer function return the first observer foo.addObserver(object2, event, callback) self.assertEqual(foo.observer(event, callback), object) foo.addObserver(object2, event, callback2) self.assertEqual(foo.observer(event, callback2), object2)
def testPriorityArg(self): """Test the optional priority argument """ cb = callback() o = vtk.vtkObject() o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb, 0.5) o.Modified() self.assertEqual(cb.caller, o)
def testCommandWithArgs(self): """Test binding a command that has arguments. """ cb = callback() o = vtk.vtkObject() o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb) o.Modified() self.assertEqual(cb.caller, o) self.assertEqual(cb.event, "ModifiedEvent")
def testUseEventNameString(self): """Test binding with a string event name. """ cb = callback() o = vtk.vtkObject() o.AddObserver("ModifiedEvent", cb) o.Modified() self.assertEqual(cb.caller, o) self.assertEqual(cb.event, "ModifiedEvent")
def test_addObserver(self): foo = Foo() object = vtk.vtkObject() object2 = vtk.vtkObject() event = vtk.vtkCommand.ModifiedEvent callback = foo.onObjectModified self.assertEqual(len(foo.Observations), 0) foo.ModifiedEventCount = {} foo.addObserver(object, event, callback) object.Modified() self.assertEqual(len(foo.Observations), 1) self.assertEqual(foo.modifiedEventCount(object), 1) self.assertEqual(foo.modifiedEventCount(object2), 0) foo.ModifiedEventCount = {} with self.assertWarns(UserWarning): foo.addObserver(object, event, callback) object.Modified() self.assertEqual(len(foo.Observations), 1) self.assertEqual(foo.modifiedEventCount(object), 1) self.assertEqual(foo.modifiedEventCount(object2), 0) foo.ModifiedEventCount = {} foo.addObserver(object, event, callback, group='a') object.Modified() self.assertEqual(len(foo.Observations), 1) self.assertEqual(foo.modifiedEventCount(object), 1) self.assertEqual(foo.modifiedEventCount(object2), 0) foo.ModifiedEventCount = {} foo.addObserver(object2, event, callback) object.Modified() self.assertEqual(len(foo.Observations), 2) self.assertEqual(foo.modifiedEventCount(object), 1) self.assertEqual(foo.modifiedEventCount(object2), 0) foo.ModifiedEventCount = {} object2.Modified() self.assertEqual(len(foo.Observations), 2) self.assertEqual(foo.modifiedEventCount(object), 0) self.assertEqual(foo.modifiedEventCount(object2), 1)
def testCommandCircularRef(self): """Test correct reference loop reporting for commands """ cb = callback() o = vtk.vtkObject() o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb) cb.circular_ref = o # referent to check if "o" is deleted referent = vtk.vtkObject() o.referent = referent # make sure gc removes referer "o" from referent s1 = repr(gc.get_referrers(referent)) del o del cb gc.collect() s2 = repr(gc.get_referrers(referent)) self.assertNotEqual(s1, s2) self.assertNotEqual(s1.count("vtkObject"), 0) self.assertEqual(s2.count("vtkObject"), 0)
def test_addObserver(self): foo = Foo() object = vtk.vtkObject() object2 = vtk.vtkObject() event = vtk.vtkCommand.ModifiedEvent callback = foo.onObjectModified self.assertEqual(len(foo.Observations), 0) foo.ModifiedEventCount = {} foo.addObserver(object, event, callback) object.Modified() self.assertEqual(len(foo.Observations), 1) self.assertEqual(foo.modifiedEventCount(object), 1) self.assertEqual(foo.modifiedEventCount(object2), 0) foo.ModifiedEventCount = {} foo.addObserver(object, event, callback) object.Modified() self.assertEqual(len(foo.Observations), 1) self.assertEqual(foo.modifiedEventCount(object), 1) self.assertEqual(foo.modifiedEventCount(object2), 0) foo.ModifiedEventCount = {} foo.addObserver(object, event, callback, group='a') object.Modified() self.assertEqual(len(foo.Observations), 1) self.assertEqual(foo.modifiedEventCount(object), 1) self.assertEqual(foo.modifiedEventCount(object2), 0) foo.ModifiedEventCount = {} foo.addObserver(object2, event, callback) object.Modified() self.assertEqual(len(foo.Observations), 2) self.assertEqual(foo.modifiedEventCount(object), 1) self.assertEqual(foo.modifiedEventCount(object2), 0) foo.ModifiedEventCount = {} object2.Modified() self.assertEqual(len(foo.Observations), 2) self.assertEqual(foo.modifiedEventCount(object), 0) self.assertEqual(foo.modifiedEventCount(object2), 1)
def testObjectPointer(self): a = vtk.vtkInformation() ptr = a.__this__ # check the format _0123456789abcdef_p_vtkInformation self.assertEqual(ptr[0:1], "_") self.assertEqual(ptr[-17:], "_p_vtkInformation") address = int(ptr[1:-17], 16) # create a VTK object from the swig pointer b = vtk.vtkObject(ptr) self.assertEqual(b.GetClassName(), a.GetClassName()) self.assertEqual(a.__this__, b.__this__) self.assertEqual(a, b)
def test_releaseNodes(self): foo = Foo() node = vtk.vtkObject() callback = unittest.mock.Mock() foo.addObserver(node, vtk.vtkCommand.DeleteEvent, callback) self.assertEqual(len(foo.Observations), 1) callback.assert_not_called() del node callback.assert_called_once() self.assertEqual(len(foo.Observations), 0)
def testSubclassGhost(self): """Make sure ghosting of the class works""" o = vtkCustomObject() c = vtk.vtkCollection() c.AddItem(o) i = id(o) del o o = vtk.vtkObject() o = c.GetItemAsObject(0) # make sure the id has changed, but class the same self.assertEqual(o.__class__, vtkCustomObject) self.assertNotEqual(i, id(o))
def testGhostForClass(self): """Ghost an object to save the class""" o = vtkCustomObject() a = vtk.vtkVariantArray() a.InsertNextValue(o) i = id(o) del o o = vtk.vtkObject() o = a.GetValue(0).ToVTKObject() # make sure the id has changed, but class the same self.assertEqual(o.__class__, vtkCustomObject) self.assertNotEqual(i, id(o))
def testRemoveCommand(self): """Test the removal of an observer. """ cb = callback() o = vtk.vtkObject() o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb) o.Modified() self.assertEqual(cb.caller, o) o.RemoveObservers(vtk.vtkCommand.ModifiedEvent) cb.caller = None cb.event = None o.Modified() self.assertEqual(cb.caller, None)
def testArgumentConversion(self): """Test argument conversion via implicit constructors""" # automatic conversion to vtkVariant a = vtk.vtkVariantArray() a.InsertNextValue(2.5) a.InsertNextValue(vtk.vtkObject()) self.assertEqual(a.GetValue(0), vtk.vtkVariant(2.5)) self.assertEqual(a.GetValue(1).GetType(), vtk.VTK_OBJECT) # same, but this one is via "const vtkVariant&" argument a = vtk.vtkDenseArray[float]() a.Resize(1) a.SetVariantValue(0, 2.5) self.assertEqual(a.GetVariantValue(0).ToDouble(), 2.5)
def __init__(self, parent=None, x=0, y=0, width=0, height=0, rx=0.0, ry=0.0, rwidth=0.0, rheight=0.0, background=(0.75, 0.75, 0.75), foreground=(0.0, 0.0, 0.0)): EventHandler.__init__(self) # Store the modified time self._MTime = vtk.vtkObject() # the basic allowed flags self._Config = { 'x': x, 'y': y, 'width': width, 'height': height, 'rx': rx, 'ry': ry, 'rwidth': rwidth, 'rheight': rheight, 'background': background, 'foreground': foreground } # the child widgets of this widget self._Widgets = [] self._CurrentWidget = None self._FocusWidget = None # the renderer that these widgets are located in self._Renderer = None self._Actors = [] # lookup table for shading of bevels self._LookupTable = vtk.vtkLookupTable() self._LookupTable.SetNumberOfColors(4) self._LookupTable.SetTableRange(0, 3) self._BuildLookupTable(self._Config['background']) if parent: parent.AddWidget(self) self.ConfigureGeometry(parent.GetDisplayOrigin(), parent.GetDisplaySize())
def test_getObserver(self): foo = Foo() obj = vtk.vtkObject() event = vtk.vtkCommand.ModifiedEvent callback = foo.onObjectModified group = 'a' priority = 42.0 foo.addObserver(obj, event, callback, group=group, priority=priority) group_, tag_, priority_ = foo.getObserver(obj, event, callback) self.assertEqual(group, group_) self.assertEqual(priority, priority_)
def test_moduleTestMixin(self): class MyModuleTest(ScriptedLoadableModuleTest, VTKObservationMixin): pass test = MyModuleTest() obj = vtk.vtkObject() event = vtk.vtkCommand.ModifiedEvent callback = unittest.mock.Mock() test.addObserver(obj, event, callback) callback.assert_not_called() obj.Modified() callback.assert_called()
def testGetCommand(self): """Test getting the vtkCommand object """ cb = callback() o = vtk.vtkObject() n = o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb) o.Modified() self.assertEqual(cb.caller, o) c = o.GetCommand(n) self.assertEqual((c.IsA("vtkCommand") != 0), True) # in the future, o.RemoveObserver(c) should also be made to work o.RemoveObserver(n) cb.caller = None cb.event = None o.Modified() self.assertEqual(cb.caller, None)
def testConstructors(self): """Test overloaded constructors""" # resolve by number of arguments v = vtk.vtkVector3d(3, 4, 5) self.assertEqual((v[0], v[1], v[2]), (3, 4, 5)) v = vtk.vtkVector3d(6) self.assertEqual((v[0], v[1], v[2]), (6, 6, 6)) # resolve by argument type v = vtk.vtkVariant(3.0) self.assertEqual(v.GetType(), vtk.VTK_DOUBLE) v = vtk.vtkVariant(1) self.assertEqual(v.GetType(), vtk.VTK_INT) v = vtk.vtkVariant("hello") self.assertEqual(v.GetType(), vtk.VTK_STRING) v = vtk.vtkVariant(vtk.vtkObject()) self.assertEqual(v.GetType(), vtk.VTK_OBJECT)
def __init__(self, obj): self.vtkObj = volScalarFieldSource(obj) self.getVTKWindows() self.internalMesh = vtk.vtkObject(self.vtkObj.internalMesh().__hex__()) self.getVTKActor(self.internalMesh) self.mapper.SetScalarModeToUseCellData() self.istyle = vtk.vtkInteractorStyleSwitch() self.istyle.SetCurrentStyleToTrackballCamera() self.iren.SetInteractorStyle(self.istyle) self.update() self.iren.Start()
def suppress_vtk_warnings(): """A context manager to suppress VTK warnings. This is handy when trying to find something dynamically with VTK. **Example** with supress_vtk_warnings(): x = tvtk.VolumeRayCastMapper() """ try: obj = vtk.vtkObject() obj.GlobalWarningDisplayOff() yield finally: obj.GlobalWarningDisplayOn()
def __init__(self, master, **kw): self._master = master self._index = 0 self._pane_name = kw['name'] if 'index' in kw: self._index = kw['index'] del(kw['index']) else: logging.error("EVSRenderPane2D requires an image index!") RenderPane2D.RenderPane2D.__init__(self, master, **kw) self.SetBorderWidth(2) # event object self._eventObject = vtk.vtkObject() # OrthoPlaneFactory -- we need to set the orthocenter self.__orthoPlanes = None self._tracked_sliceplane_index = 0 # the Button 1 action binding self._B1Action = 'pan' # create some default cursors self._cursors = {'winlev': wx.StockCursor(wx.CURSOR_ARROW), 'rotate': wx.StockCursor(wx.CURSOR_ARROW), 'zoom': wx.StockCursor(wx.CURSOR_MAGNIFIER), 'pan': wx.StockCursor(wx.CURSOR_HAND), 'slice': wx.StockCursor(wx.CURSOR_ARROW), 'spin': wx.StockCursor(wx.CURSOR_ARROW), } # override some of the default with cursor if we find them on disk for action in ('pan', 'winlev', 'zoom', 'slice', 'spin'): filename = os.path.join('Cursors', '%s.gif' % action) if os.path.exists(filename): try: image = wx.Image(filename) image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_X, 1) image.SetOptionInt(wx.IMAGE_OPTION_CUR_HOTSPOT_Y, 1) self._cursors[action] = wx.CursorFromImage(image) except: logging.exception("EVSRenderPane2D")
def __init__(self, parent=None, x=0, y=0, width=0, height=0, rx=0.0, ry=0.0, rwidth=0.0, rheight=0.0, background=(0.75, 0.75, 0.75), foreground=(0.0, 0.0, 0.0)): EventHandler.__init__(self) # Store the modified time self._MTime = vtk.vtkObject() # the basic allowed flags self._Config = {'x': x, 'y': y, 'width': width, 'height': height, 'rx': rx, 'ry': ry, 'rwidth': rwidth, 'rheight': rheight, 'background': background, 'foreground': foreground} # the child widgets of this widget self._Widgets = [] self._CurrentWidget = None self._FocusWidget = None # the renderer that these widgets are located in self._Renderer = None self._Actors = [] # lookup table for shading of bevels self._LookupTable = vtk.vtkLookupTable() self._LookupTable.SetNumberOfColors(4) self._LookupTable.SetTableRange(0, 3) self._BuildLookupTable(self._Config['background']) if parent: parent.AddWidget(self) self.ConfigureGeometry(parent.GetDisplayOrigin(), parent.GetDisplaySize())
def __init__( self, parent=None, x=0, y=0, width=100, height=27, fontsize=_FS, **kw): kw["height"] = height kw["width"] = width kw["x"] = x kw["y"] = y kw["fontsize"] = fontsize kw["font"] = "arial" kw["text"] = "W/L" apply(Label.__init__, (self, parent), kw) self._Table = None self._DataRange = None self._Window = None self._Level = None self._Shift = 0.0 self._Scale = 1.0 self._Pressed = 0 self._Mapper = None self._minmax = False self._eventObject = vtk.vtkObject() self._actionColor = (1, 0, 0) self._defaultColor = kw["foreground"] self._highlightColor = (1, 1, 0) # add to the configuration dictionary self._Config['font'] = 'arial' self.BindEvent("<ButtonPress>", self.DoPress) self.BindEvent("<ButtonRelease>", self.DoRelease) self.BindEvent("<Enter>", self.DoEnter) self.BindEvent("<Leave>", self.DoLeave) self._SetColor(self._defaultColor)
def testAddRemoveObservers(self): """Test adding and removing observers """ cb = callback() cb2 = callback() o = vtk.vtkObject() n = o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb) n2 = o.AddObserver(vtk.vtkCommand.ModifiedEvent, cb2) o.Modified() self.assertEqual(cb.caller, o) self.assertEqual(cb2.caller, o) o.RemoveObserver(n) cb.reset() cb2.reset() o.Modified() self.assertEqual(cb.caller, None) self.assertEqual(cb2.caller, o) o.RemoveObserver(n2) cb.reset() cb2.reset() o.Modified() self.assertEqual(cb.caller, None) self.assertEqual(cb2.caller, None)
def test_parse(self): """Check if the methods are organized correctly.""" p = self.p # Simple case of a vtkObject. p.parse(vtk.vtkObject()) self.assertEqual(p.get_toggle_methods(), {'Debug': 0, 'GlobalWarningDisplay': 1}) if (vtk_major_version >= 5 and vtk_minor_version >= 10) or \ (vtk_major_version >= 6): self.assertEqual(p.get_state_methods(), {}) self.assertEqual(p.get_get_methods(), ['GetCommand', 'GetMTime']) elif vtk_major_version >= 5 and vtk_minor_version >= 6: self.assertEqual(p.get_state_methods(), {}) self.assertEqual(p.get_get_methods(), ['GetMTime']) else: self.assertEqual(p.get_state_methods(), {'ReferenceCount':(1, None)}) self.assertEqual(p.get_get_methods(), ['GetMTime']) self.assertEqual(p.get_get_set_methods(), {}) res = ['AddObserver', 'BreakOnError', 'HasObserver', 'InvokeEvent', 'IsA', 'Modified', 'NewInstance', 'Register', 'RemoveObserver', 'RemoveObservers', 'SafeDownCast', 'UnRegister', 'RemoveAllObservers'] for i in p.get_other_methods(): self.assertEqual(i in res, True) # Parse a fairly complex case of a vtkProperty with the same # parser object. p.parse(vtk.vtkProperty) self.assertEqual(p.toggle_meths, p.get_toggle_methods()) res = {'EdgeVisibility': 0, 'BackfaceCulling': 0, 'FrontfaceCulling': 0} if 'Shading' in p.get_toggle_methods(): res['Shading'] = 0 result = p.get_toggle_methods() for key in res: self.assertEqual(key in result, True) self.assertEqual(result[key], res[key]) res = {'Interpolation': [['Gouraud', 1], ['Flat', 0], ['Gouraud', 1], ['Phong', 2]], 'Representation': [['Surface', 2], ['Points', 0], ['Surface', 2], ['Wireframe', 1]]} self.assertEqual(p.get_state_methods(), res) self.assertEqual(p.state_meths, p.get_state_methods()) obj = vtk.vtkProperty() if hasattr(vtk, 'VTK_LARGE_FLOAT'): int_max = vtk.VTK_LARGE_INTEGER float_max = vtk.VTK_LARGE_FLOAT else: int_max = vtk.VTK_INT_MAX float_max = vtk.VTK_FLOAT_MAX res = {'Ambient': (0.0, (0.0, 1.0)), 'AmbientColor': ((1.0, 1.0, 1.0), None), 'Color': ((1.0, 1.0, 1.0), None), 'Diffuse': (1.0, (0.0, 1.0)), 'DiffuseColor': ((1.0, 1.0, 1.0), None), 'EdgeColor': ((1.0, 1.0, 1.0), None), 'LineStipplePattern': (65535, None), 'LineStippleRepeatFactor': (1, (1, int_max)), 'LineWidth': (1.0, (0.0, float_max)), 'Opacity': (1.0, (0.0, 1.0)), 'PointSize': (1.0, (0.0, float_max)), 'ReferenceCount': (1, None), 'Specular': (0.0, (0.0, 1.0)), 'SpecularColor': ((1.0, 1.0, 1.0), None), 'SpecularPower': (1.0, (0.0, 100.0))} if ('ReferenceCount' not in p.get_get_set_methods()): del res['ReferenceCount'] result = list(p.get_get_set_methods().keys()) if hasattr(obj, 'GetTexture'): result.remove('Texture') self.assertEqual(sorted(res.keys()), sorted(result)) self.assertEqual(p.get_set_meths, p.get_get_set_methods()) for x in res: if res[x][1]: # This is necessary since the returned value is not # usually exactly the same as defined in the header file. default = getattr(obj, 'Get%s'%x)() val = getattr(obj, 'Get%sMinValue'%x)(), \ getattr(obj, 'Get%sMaxValue'%x)() self.assertEqual(p.get_get_set_methods()[x], (default, val)) if hasattr(obj, 'GetTexture'): expect = ['GetMaterial', 'GetMaterialName', 'GetNumberOfTextures', 'GetShaderProgram'] if hasattr(obj, 'GetMaterialName'): if hasattr(obj, 'GetShaderDeviceAdapter2'): expect.append('GetShaderDeviceAdapter2') msg = "%s not in %s"%(p.get_get_methods(), expect) self.assertTrue(all([x in expect for x in sorted(p.get_get_methods())]), msg) else: expect.remove('GetMaterialName') self.assertEqual(p.get_get_methods(), expect) else: self.assertEqual(p.get_get_methods(), []) self.assertEqual(p.get_meths, p.get_get_methods()) res = ['BackfaceRender', 'DeepCopy', 'Render'] if hasattr(obj, 'GetTexture'): if vtk_major_version == 6: res = ['AddShaderVariable', 'BackfaceRender', 'DeepCopy', 'ReleaseGraphicsResources', 'RemoveAllTextures', 'RemoveTexture', 'Render'] if vtk_minor_version >= 2: res.append('VTKTextureUnit') else: res = ['AddShaderVariable', 'BackfaceRender', 'DeepCopy', 'LoadMaterial', 'LoadMaterialFromString', 'ReleaseGraphicsResources', 'RemoveAllTextures', 'RemoveTexture', 'Render'] if hasattr(obj, 'PostRender'): res.append('PostRender') res.sort() self.assertEqual(p.get_other_methods(), res) self.assertEqual(p.other_meths, p.get_other_methods())
def __init__(self) : self.Object = vtk.vtkObject() self.Object.AddObserver('StartEvent', self.Handler)
# Useful constants for VTK arrays. VTK_ID_TYPE_SIZE = vtk.vtkIdTypeArray().GetDataTypeSize() if VTK_ID_TYPE_SIZE == 4: ID_TYPE_CODE = numpy.int32 elif VTK_ID_TYPE_SIZE == 8: ID_TYPE_CODE = numpy.int64 VTK_LONG_TYPE_SIZE = vtk.vtkLongArray().GetDataTypeSize() if VTK_LONG_TYPE_SIZE == 4: LONG_TYPE_CODE = numpy.int32 ULONG_TYPE_CODE = numpy.uint32 elif VTK_LONG_TYPE_SIZE == 8: LONG_TYPE_CODE = numpy.int64 ULONG_TYPE_CODE = numpy.uint64 BASE_REFERENCE_COUNT = vtk.vtkObject().GetReferenceCount() if sys.version_info[0] > 2: unicode = str def getbuffer(array): return getattr(numpy, 'getbuffer', memoryview)(array) ###################################################################### # The array cache. ###################################################################### class ArrayCache(object): """Caches references to numpy arrays that are not copied but views of which are converted to VTK arrays. The caching prevents the user
def test_parse(self): """Check if the methods are organized correctly.""" p = self.p # Simple case of a vtkObject. p.parse(vtk.vtkObject()) if vtk_major_version < 9: self.assertEqual(p.get_toggle_methods(), { 'Debug': 0, 'GlobalWarningDisplay': 1 }) else: self.assertIn(p.get_toggle_methods(), [{ 'Debug': False, 'GlobalWarningDisplay': 1 }, { 'Debug': False, 'GlobalWarningDisplay': 0 }]) if (vtk_major_version >= 5 and vtk_minor_version >= 10) or \ (vtk_major_version >= 6): self.assertEqual(p.get_state_methods(), {}) self.assertEqual(p.get_get_methods(), ['GetCommand', 'GetMTime']) elif vtk_major_version >= 5 and vtk_minor_version >= 6: self.assertEqual(p.get_state_methods(), {}) self.assertEqual(p.get_get_methods(), ['GetMTime']) else: self.assertEqual(p.get_state_methods(), {'ReferenceCount': (1, None)}) self.assertEqual(p.get_get_methods(), ['GetMTime']) self.assertEqual(p.get_get_set_methods(), {}) res = [ 'AddObserver', 'BreakOnError', 'HasObserver', 'InvokeEvent', 'IsA', 'Modified', 'NewInstance', 'Register', 'RemoveObserver', 'RemoveObservers', 'SafeDownCast', 'UnRegister', 'RemoveAllObservers' ] for i in p.get_other_methods(): self.assertEqual(i in res, True) # Parse a fairly complex case of a vtkProperty with the same # parser object. p.parse(vtk.vtkProperty) self.assertEqual(p.toggle_meths, p.get_toggle_methods()) res = { 'EdgeVisibility': 0, 'BackfaceCulling': 0, 'FrontfaceCulling': 0 } if 'Shading' in p.get_toggle_methods(): res['Shading'] = 0 result = p.get_toggle_methods() for key in res: self.assertEqual(key in result, True) self.assertEqual(result[key], res[key]) res = { 'Interpolation': [['Gouraud', 1], ['Flat', 0], ['Gouraud', 1], ['Phong', 2]], 'Representation': [['Surface', 2], ['Points', 0], ['Surface', 2], ['Wireframe', 1]] } if vtk_major_version >= 9: res['Interpolation'].insert(-1, ['PBR', 3]) self.assertEqual(p.get_state_methods(), res) self.assertEqual(p.state_meths, p.get_state_methods()) obj = vtk.vtkProperty() if hasattr(vtk, 'VTK_LARGE_FLOAT'): int_max = vtk.VTK_LARGE_INTEGER float_max = vtk.VTK_LARGE_FLOAT else: int_max = vtk.VTK_INT_MAX float_max = vtk.VTK_FLOAT_MAX res = { 'Ambient': (0.0, (0.0, 1.0)), 'AmbientColor': ((1.0, 1.0, 1.0), None), 'Color': ((1.0, 1.0, 1.0), None), 'Diffuse': (1.0, (0.0, 1.0)), 'DiffuseColor': ((1.0, 1.0, 1.0), None), 'EdgeColor': ((1.0, 1.0, 1.0), None), 'LineStipplePattern': (65535, None), 'LineStippleRepeatFactor': (1, (1, int_max)), 'LineWidth': (1.0, (0.0, float_max)), 'Opacity': (1.0, (0.0, 1.0)), 'PointSize': (1.0, (0.0, float_max)), 'ReferenceCount': (1, None), 'Specular': (0.0, (0.0, 1.0)), 'SpecularColor': ((1.0, 1.0, 1.0), None), 'SpecularPower': (1.0, (0.0, 100.0)) } if ('ReferenceCount' not in p.get_get_set_methods()): del res['ReferenceCount'] if vtk_major_version > 7: res['MaterialName'] = (None, None) res['VertexColor'] = ((0.5, 1.0, 0.5), None) if vtk_major_version >= 9: res['EmissiveFactor'] = ((1.0, 1.0, 1.0), None) res['Metallic'] = (0., float_max) res['NormalScale'] = (1., None) res['OcclusionStrength'] = (1., float_max) res['Roughness'] = (0.5, float_max) result = list(p.get_get_set_methods().keys()) if hasattr(obj, 'GetTexture'): result.remove('Texture') if hasattr(obj, 'GetInformation'): result.remove('Information') self.assertEqual(sorted(res.keys()), sorted(result)) self.assertEqual(p.get_set_meths, p.get_get_set_methods()) for x in res: if res[x][1]: # This is necessary since the returned value is not # usually exactly the same as defined in the header file. default = getattr(obj, 'Get%s' % x)() val = getattr(obj, 'Get%sMinValue' % x)(), \ getattr(obj, 'Get%sMaxValue' % x)() self.assertEqual(p.get_get_set_methods()[x], (default, val)) if hasattr(obj, 'GetTexture'): expect = [ 'GetMaterial', 'GetMaterialName', 'GetNumberOfTextures', 'GetShaderProgram' ] if hasattr(obj, 'GetMaterialName'): if hasattr(obj, 'GetShaderDeviceAdapter2'): expect.append('GetShaderDeviceAdapter2') msg = "%s not in %s" % (p.get_get_methods(), expect) self.assertTrue( all([x in expect for x in sorted(p.get_get_methods())]), msg) else: expect.remove('GetMaterialName') self.assertEqual(p.get_get_methods(), expect) else: self.assertEqual(p.get_get_methods(), []) self.assertEqual(p.get_meths, p.get_get_methods()) res = ['BackfaceRender', 'DeepCopy', 'Render'] if hasattr(obj, 'GetTexture'): if vtk_major_version >= 6: res = [ 'AddShaderVariable', 'BackfaceRender', 'DeepCopy', 'ReleaseGraphicsResources', 'RemoveAllTextures', 'RemoveTexture', 'Render' ] if (vtk_major_version >= 7 or vtk_minor_version >= 2) and \ vtk_major_version < 9: res.append('VTKTextureUnit') if vtk_major_version >= 9: res.extend([ 'SetBaseColorTexture', 'SetEmissiveTexture', 'SetNormalTexture', 'SetORMTexture' ]) else: res = [ 'AddShaderVariable', 'BackfaceRender', 'DeepCopy', 'LoadMaterial', 'LoadMaterialFromString', 'ReleaseGraphicsResources', 'RemoveAllTextures', 'RemoveTexture', 'Render' ] if hasattr(obj, 'PostRender'): res.append('PostRender') res.sort() self.assertEqual(p.get_other_methods(), res) self.assertEqual(p.other_meths, p.get_other_methods())
def testVariantExtract(self): """Use vtkVariantExtract""" l = [1, '2', cedilla, 4.0, vtk.vtkObject()] s = [vtk.vtkVariant(x) for x in l] m = [vtk.vtkVariantExtract(x) for x in s] self.assertEqual(l, m)