wxVTKRenderWindowInteractor.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713
  1. """
  2. A VTK RenderWindowInteractor widget for wxPython.
  3. Find wxPython info at http://wxPython.org
  4. Created by Prabhu Ramachandran, April 2002
  5. Based on wxVTKRenderWindow.py
  6. Fixes and updates by Charl P. Botha 2003-2008
  7. Updated to new wx namespace and some cleaning up by Andrea Gavana,
  8. December 2006
  9. """
  10. """
  11. Please see the example at the end of this file.
  12. ----------------------------------------
  13. Creation:
  14. wxVTKRenderWindowInteractor(parent, ID, stereo=0, [wx keywords]):
  15. You should create a wx.App(False) or some other wx.App subclass
  16. before creating the window.
  17. Behaviour:
  18. Uses __getattr__ to make the wxVTKRenderWindowInteractor behave just
  19. like a vtkGenericRenderWindowInteractor.
  20. ----------------------------------------
  21. """
  22. # import usual libraries
  23. import math, os, sys
  24. import wx
  25. from vtkmodules.vtkRenderingCore import vtkRenderWindow
  26. from vtkmodules.vtkRenderingUI import vtkGenericRenderWindowInteractor
  27. # a few configuration items, see what works best on your system
  28. # Use GLCanvas as base class instead of wx.Window.
  29. # This is sometimes necessary under wxGTK or the image is blank.
  30. # (in wxWindows 2.3.1 and earlier, the GLCanvas had scroll bars)
  31. baseClass = wx.Window
  32. if wx.Platform == "__WXGTK__":
  33. import wx.glcanvas
  34. baseClass = wx.glcanvas.GLCanvas
  35. # Keep capturing mouse after mouse is dragged out of window
  36. # (in wxGTK 2.3.2 there is a bug that keeps this from working,
  37. # but it is only relevant in wxGTK if there are multiple windows)
  38. _useCapture = (wx.Platform == "__WXMSW__")
  39. # end of configuration items
  40. class EventTimer(wx.Timer):
  41. """Simple wx.Timer class.
  42. """
  43. def __init__(self, iren):
  44. """Default class constructor.
  45. @param iren: current render window
  46. """
  47. wx.Timer.__init__(self)
  48. self.iren = iren
  49. def Notify(self):
  50. """ The timer has expired.
  51. """
  52. self.iren.TimerEvent()
  53. class wxVTKRenderWindowInteractor(baseClass):
  54. """
  55. A wxRenderWindow for wxPython.
  56. Use GetRenderWindow() to get the vtkRenderWindow.
  57. Create with the keyword stereo=1 in order to
  58. generate a stereo-capable window.
  59. """
  60. # class variable that can also be used to request instances that use
  61. # stereo; this is overridden by the stereo=1/0 parameter. If you set
  62. # it to True, the NEXT instantiated object will attempt to allocate a
  63. # stereo visual. E.g.:
  64. # wxVTKRenderWindowInteractor.USE_STEREO = True
  65. # myRWI = wxVTKRenderWindowInteractor(parent, -1)
  66. USE_STEREO = False
  67. def __init__(self, parent, ID, *args, **kw):
  68. """Default class constructor.
  69. @param parent: parent window
  70. @param ID: window id
  71. @param **kw: wxPython keywords (position, size, style) plus the
  72. 'stereo' keyword
  73. """
  74. # private attributes
  75. self.__RenderWhenDisabled = 0
  76. # First do special handling of some keywords:
  77. # stereo, position, size, width, height, style
  78. try:
  79. stereo = bool(kw['stereo'])
  80. del kw['stereo']
  81. except KeyError:
  82. stereo = False
  83. try:
  84. position = kw['position']
  85. del kw['position']
  86. except KeyError:
  87. position = wx.DefaultPosition
  88. try:
  89. size = kw['size']
  90. del kw['size']
  91. except KeyError:
  92. try:
  93. size = parent.GetSize()
  94. except AttributeError:
  95. size = wx.DefaultSize
  96. # wx.WANTS_CHARS says to give us e.g. TAB
  97. # wx.NO_FULL_REPAINT_ON_RESIZE cuts down resize flicker under GTK
  98. style = wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE
  99. try:
  100. style = style | kw['style']
  101. del kw['style']
  102. except KeyError:
  103. pass
  104. # the enclosing frame must be shown under GTK or the windows
  105. # don't connect together properly
  106. if wx.Platform != '__WXMSW__':
  107. l = []
  108. p = parent
  109. while p: # make a list of all parents
  110. l.append(p)
  111. p = p.GetParent()
  112. l.reverse() # sort list into descending order
  113. for p in l:
  114. p.Show(1)
  115. if baseClass.__name__ == 'GLCanvas':
  116. # code added by cpbotha to enable stereo and double
  117. # buffering correctly where the user requests this; remember
  118. # that the glXContext in this case is NOT allocated by VTK,
  119. # but by WX, hence all of this.
  120. # Initialize GLCanvas with correct attriblist
  121. attribList = [wx.glcanvas.WX_GL_RGBA,
  122. wx.glcanvas.WX_GL_MIN_RED, 1,
  123. wx.glcanvas.WX_GL_MIN_GREEN, 1,
  124. wx.glcanvas.WX_GL_MIN_BLUE, 1,
  125. wx.glcanvas.WX_GL_DEPTH_SIZE, 16,
  126. wx.glcanvas.WX_GL_DOUBLEBUFFER]
  127. if stereo:
  128. attribList.append(wx.glcanvas.WX_GL_STEREO)
  129. try:
  130. baseClass.__init__(self, parent, ID, pos=position, size=size,
  131. style=style,
  132. attribList=attribList)
  133. except wx.PyAssertionError:
  134. # visual couldn't be allocated, so we go back to default
  135. baseClass.__init__(self, parent, ID, pos=position, size=size,
  136. style=style)
  137. if stereo:
  138. # and make sure everyone knows that the stereo
  139. # visual wasn't set.
  140. stereo = 0
  141. else:
  142. baseClass.__init__(self, parent, ID, pos=position, size=size,
  143. style=style)
  144. # create the RenderWindow and initialize it
  145. self._Iren = vtkGenericRenderWindowInteractor()
  146. self._Iren.SetRenderWindow( vtkRenderWindow() )
  147. self._Iren.AddObserver('CreateTimerEvent', self.CreateTimer)
  148. self._Iren.AddObserver('DestroyTimerEvent', self.DestroyTimer)
  149. self._Iren.GetRenderWindow().AddObserver('CursorChangedEvent',
  150. self.CursorChangedEvent)
  151. try:
  152. self._Iren.GetRenderWindow().SetSize(size.width, size.height)
  153. except AttributeError:
  154. self._Iren.GetRenderWindow().SetSize(size[0], size[1])
  155. if stereo:
  156. self._Iren.GetRenderWindow().StereoCapableWindowOn()
  157. self._Iren.GetRenderWindow().SetStereoTypeToCrystalEyes()
  158. self.__handle = None
  159. self.BindEvents()
  160. # with this, we can make sure that the reparenting logic in
  161. # Render() isn't called before the first OnPaint() has
  162. # successfully been run (and set up the VTK/WX display links)
  163. self.__has_painted = False
  164. # set when we have captured the mouse.
  165. self._own_mouse = False
  166. # used to store WHICH mouse button led to mouse capture
  167. self._mouse_capture_button = 0
  168. # A mapping for cursor changes.
  169. self._cursor_map = {0: wx.CURSOR_ARROW, # VTK_CURSOR_DEFAULT
  170. 1: wx.CURSOR_ARROW, # VTK_CURSOR_ARROW
  171. 2: wx.CURSOR_SIZENESW, # VTK_CURSOR_SIZENE
  172. 3: wx.CURSOR_SIZENWSE, # VTK_CURSOR_SIZENWSE
  173. 4: wx.CURSOR_SIZENESW, # VTK_CURSOR_SIZESW
  174. 5: wx.CURSOR_SIZENWSE, # VTK_CURSOR_SIZESE
  175. 6: wx.CURSOR_SIZENS, # VTK_CURSOR_SIZENS
  176. 7: wx.CURSOR_SIZEWE, # VTK_CURSOR_SIZEWE
  177. 8: wx.CURSOR_SIZING, # VTK_CURSOR_SIZEALL
  178. 9: wx.CURSOR_HAND, # VTK_CURSOR_HAND
  179. 10: wx.CURSOR_CROSS, # VTK_CURSOR_CROSSHAIR
  180. }
  181. def BindEvents(self):
  182. """Binds all the necessary events for navigation, sizing,
  183. drawing.
  184. """
  185. # refresh window by doing a Render
  186. self.Bind(wx.EVT_PAINT, self.OnPaint)
  187. # turn off background erase to reduce flicker
  188. self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
  189. # Bind the events to the event converters
  190. self.Bind(wx.EVT_RIGHT_DOWN, self.OnButtonDown)
  191. self.Bind(wx.EVT_LEFT_DOWN, self.OnButtonDown)
  192. self.Bind(wx.EVT_MIDDLE_DOWN, self.OnButtonDown)
  193. self.Bind(wx.EVT_RIGHT_UP, self.OnButtonUp)
  194. self.Bind(wx.EVT_LEFT_UP, self.OnButtonUp)
  195. self.Bind(wx.EVT_MIDDLE_UP, self.OnButtonUp)
  196. self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
  197. self.Bind(wx.EVT_MOTION, self.OnMotion)
  198. self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
  199. self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
  200. # If we use EVT_KEY_DOWN instead of EVT_CHAR, capital versions
  201. # of all characters are always returned. EVT_CHAR also performs
  202. # other necessary keyboard-dependent translations.
  203. self.Bind(wx.EVT_CHAR, self.OnKeyDown)
  204. self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
  205. self.Bind(wx.EVT_SIZE, self.OnSize)
  206. # the wx 2.8.7.1 documentation states that you HAVE to handle
  207. # this event if you make use of CaptureMouse, which we do.
  208. if _useCapture and hasattr(wx, 'EVT_MOUSE_CAPTURE_LOST'):
  209. self.Bind(wx.EVT_MOUSE_CAPTURE_LOST,
  210. self.OnMouseCaptureLost)
  211. def __getattr__(self, attr):
  212. """Makes the object behave like a
  213. vtkGenericRenderWindowInteractor.
  214. """
  215. if attr == '__vtk__':
  216. return lambda t=self._Iren: t
  217. elif hasattr(self._Iren, attr):
  218. return getattr(self._Iren, attr)
  219. else:
  220. raise AttributeError(self.__class__.__name__ +
  221. " has no attribute named " + attr)
  222. def CreateTimer(self, obj, evt):
  223. """ Creates a timer.
  224. """
  225. self._timer = EventTimer(self)
  226. self._timer.Start(10, True)
  227. def DestroyTimer(self, obj, evt):
  228. """The timer is a one shot timer so will expire automatically.
  229. """
  230. return 1
  231. def _CursorChangedEvent(self, obj, evt):
  232. """Change the wx cursor if the renderwindow's cursor was
  233. changed.
  234. """
  235. cur = self._cursor_map[obj.GetCurrentCursor()]
  236. c = wx.StockCursor(cur)
  237. self.SetCursor(c)
  238. def CursorChangedEvent(self, obj, evt):
  239. """Called when the CursorChangedEvent fires on the render
  240. window."""
  241. # This indirection is needed since when the event fires, the
  242. # current cursor is not yet set so we defer this by which time
  243. # the current cursor should have been set.
  244. wx.CallAfter(self._CursorChangedEvent, obj, evt)
  245. def HideCursor(self):
  246. """Hides the cursor."""
  247. c = wx.StockCursor(wx.CURSOR_BLANK)
  248. self.SetCursor(c)
  249. def ShowCursor(self):
  250. """Shows the cursor."""
  251. rw = self._Iren.GetRenderWindow()
  252. cur = self._cursor_map[rw.GetCurrentCursor()]
  253. c = wx.StockCursor(cur)
  254. self.SetCursor(c)
  255. def GetDisplayId(self):
  256. """Function to get X11 Display ID from WX and return it in a format
  257. that can be used by VTK Python.
  258. We query the X11 Display with a new call that was added in wxPython
  259. 2.6.0.1. The call returns a SWIG object which we can query for the
  260. address and subsequently turn into an old-style SWIG-mangled string
  261. representation to pass to VTK.
  262. """
  263. d = None
  264. try:
  265. d = wx.GetXDisplay()
  266. except AttributeError:
  267. # wx.GetXDisplay was added by Robin Dunn in wxPython 2.6.0.1
  268. # if it's not available, we can't pass it. In general,
  269. # things will still work; on some setups, it'll break.
  270. pass
  271. else:
  272. # wx returns None on platforms where wx.GetXDisplay is not relevant
  273. if d:
  274. d = hex(d)
  275. # On wxPython-2.6.3.2 and above there is no leading '0x'.
  276. if not d.startswith('0x'):
  277. d = '0x' + d
  278. # VTK wants it as: _xxxxxxxx_p_void (SWIG pointer)
  279. d = '_%s_%s\0' % (d[2:], 'p_void')
  280. return d
  281. def OnMouseCaptureLost(self, event):
  282. """This is signalled when we lose mouse capture due to an
  283. external event, such as when a dialog box is shown. See the
  284. wx documentation.
  285. """
  286. # the documentation seems to imply that by this time we've
  287. # already lost capture. I have to assume that we don't need
  288. # to call ReleaseMouse ourselves.
  289. if _useCapture and self._own_mouse:
  290. self._own_mouse = False
  291. def OnPaint(self,event):
  292. """Handles the wx.EVT_PAINT event for
  293. wxVTKRenderWindowInteractor.
  294. """
  295. # wx should continue event processing after this handler.
  296. # We call this BEFORE Render(), so that if Render() raises
  297. # an exception, wx doesn't re-call OnPaint repeatedly.
  298. event.Skip()
  299. dc = wx.PaintDC(self)
  300. # make sure the RenderWindow is sized correctly
  301. self._Iren.GetRenderWindow().SetSize(self.GetSize())
  302. # Tell the RenderWindow to render inside the wx.Window.
  303. if not self.__handle:
  304. # on relevant platforms, set the X11 Display ID
  305. d = self.GetDisplayId()
  306. if d and self.__has_painted:
  307. self._Iren.GetRenderWindow().SetDisplayId(d)
  308. # store the handle
  309. self.__handle = self.GetHandle()
  310. # and give it to VTK
  311. self._Iren.GetRenderWindow().SetWindowInfo(str(self.__handle))
  312. # now that we've painted once, the Render() reparenting logic
  313. # is safe
  314. self.__has_painted = True
  315. self.Render()
  316. def OnSize(self,event):
  317. """Handles the wx.EVT_SIZE event for
  318. wxVTKRenderWindowInteractor.
  319. """
  320. # event processing should continue (we call this before the
  321. # Render(), in case it raises an exception)
  322. event.Skip()
  323. try:
  324. width, height = event.GetSize()
  325. except:
  326. width = event.GetSize().width
  327. height = event.GetSize().height
  328. self._Iren.SetSize(width, height)
  329. self._Iren.ConfigureEvent()
  330. # this will check for __handle
  331. self.Render()
  332. def OnMotion(self,event):
  333. """Handles the wx.EVT_MOTION event for
  334. wxVTKRenderWindowInteractor.
  335. """
  336. # event processing should continue
  337. # we call this early in case any of the VTK code raises an
  338. # exception.
  339. event.Skip()
  340. self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
  341. event.ControlDown(),
  342. event.ShiftDown(),
  343. chr(0), 0, None)
  344. self._Iren.MouseMoveEvent()
  345. def OnEnter(self,event):
  346. """Handles the wx.EVT_ENTER_WINDOW event for
  347. wxVTKRenderWindowInteractor.
  348. """
  349. # event processing should continue
  350. event.Skip()
  351. self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
  352. event.ControlDown(),
  353. event.ShiftDown(),
  354. chr(0), 0, None)
  355. self._Iren.EnterEvent()
  356. def OnLeave(self,event):
  357. """Handles the wx.EVT_LEAVE_WINDOW event for
  358. wxVTKRenderWindowInteractor.
  359. """
  360. # event processing should continue
  361. event.Skip()
  362. self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
  363. event.ControlDown(),
  364. event.ShiftDown(),
  365. chr(0), 0, None)
  366. self._Iren.LeaveEvent()
  367. def OnButtonDown(self,event):
  368. """Handles the wx.EVT_LEFT/RIGHT/MIDDLE_DOWN events for
  369. wxVTKRenderWindowInteractor.
  370. """
  371. # allow wx event processing to continue
  372. # on wxPython 2.6.0.1, omitting this will cause problems with
  373. # the initial focus, resulting in the wxVTKRWI ignoring keypresses
  374. # until we focus elsewhere and then refocus the wxVTKRWI frame
  375. # we do it this early in case any of the following VTK code
  376. # raises an exception.
  377. event.Skip()
  378. ctrl, shift = event.ControlDown(), event.ShiftDown()
  379. self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
  380. ctrl, shift, chr(0), 0, None)
  381. button = 0
  382. if event.RightDown():
  383. self._Iren.RightButtonPressEvent()
  384. button = 'Right'
  385. elif event.LeftDown():
  386. self._Iren.LeftButtonPressEvent()
  387. button = 'Left'
  388. elif event.MiddleDown():
  389. self._Iren.MiddleButtonPressEvent()
  390. button = 'Middle'
  391. # save the button and capture mouse until the button is released
  392. # we only capture the mouse if it hasn't already been captured
  393. if _useCapture and not self._own_mouse:
  394. self._own_mouse = True
  395. self._mouse_capture_button = button
  396. self.CaptureMouse()
  397. def OnButtonUp(self,event):
  398. """Handles the wx.EVT_LEFT/RIGHT/MIDDLE_UP events for
  399. wxVTKRenderWindowInteractor.
  400. """
  401. # event processing should continue
  402. event.Skip()
  403. button = 0
  404. if event.RightUp():
  405. button = 'Right'
  406. elif event.LeftUp():
  407. button = 'Left'
  408. elif event.MiddleUp():
  409. button = 'Middle'
  410. # if the same button is released that captured the mouse, and
  411. # we have the mouse, release it.
  412. # (we need to get rid of this as soon as possible; if we don't
  413. # and one of the event handlers raises an exception, mouse
  414. # is never released.)
  415. if _useCapture and self._own_mouse and \
  416. button==self._mouse_capture_button:
  417. self.ReleaseMouse()
  418. self._own_mouse = False
  419. ctrl, shift = event.ControlDown(), event.ShiftDown()
  420. self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
  421. ctrl, shift, chr(0), 0, None)
  422. if button == 'Right':
  423. self._Iren.RightButtonReleaseEvent()
  424. elif button == 'Left':
  425. self._Iren.LeftButtonReleaseEvent()
  426. elif button == 'Middle':
  427. self._Iren.MiddleButtonReleaseEvent()
  428. def OnMouseWheel(self,event):
  429. """Handles the wx.EVT_MOUSEWHEEL event for
  430. wxVTKRenderWindowInteractor.
  431. """
  432. # event processing should continue
  433. event.Skip()
  434. ctrl, shift = event.ControlDown(), event.ShiftDown()
  435. self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
  436. ctrl, shift, chr(0), 0, None)
  437. if event.GetWheelRotation() > 0:
  438. self._Iren.MouseWheelForwardEvent()
  439. else:
  440. self._Iren.MouseWheelBackwardEvent()
  441. def OnKeyDown(self,event):
  442. """Handles the wx.EVT_KEY_DOWN event for
  443. wxVTKRenderWindowInteractor.
  444. """
  445. # event processing should continue
  446. event.Skip()
  447. ctrl, shift = event.ControlDown(), event.ShiftDown()
  448. keycode, keysym = event.GetKeyCode(), None
  449. key = chr(0)
  450. if keycode < 256:
  451. key = chr(keycode)
  452. # wxPython 2.6.0.1 does not return a valid event.Get{X,Y}()
  453. # for this event, so we use the cached position.
  454. (x,y)= self._Iren.GetEventPosition()
  455. self._Iren.SetEventInformation(x, y,
  456. ctrl, shift, key, 0,
  457. keysym)
  458. self._Iren.KeyPressEvent()
  459. self._Iren.CharEvent()
  460. def OnKeyUp(self,event):
  461. """Handles the wx.EVT_KEY_UP event for
  462. wxVTKRenderWindowInteractor.
  463. """
  464. # event processing should continue
  465. event.Skip()
  466. ctrl, shift = event.ControlDown(), event.ShiftDown()
  467. keycode, keysym = event.GetKeyCode(), None
  468. key = chr(0)
  469. if keycode < 256:
  470. key = chr(keycode)
  471. self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
  472. ctrl, shift, key, 0,
  473. keysym)
  474. self._Iren.KeyReleaseEvent()
  475. def GetRenderWindow(self):
  476. """Returns the render window (vtkRenderWindow).
  477. """
  478. return self._Iren.GetRenderWindow()
  479. def Render(self):
  480. """Actually renders the VTK scene on screen.
  481. """
  482. RenderAllowed = 1
  483. if not self.__RenderWhenDisabled:
  484. # the user doesn't want us to render when the toplevel frame
  485. # is disabled - first find the top level parent
  486. topParent = wx.GetTopLevelParent(self)
  487. if topParent:
  488. # if it exists, check whether it's enabled
  489. # if it's not enabeld, RenderAllowed will be false
  490. RenderAllowed = topParent.IsEnabled()
  491. if RenderAllowed:
  492. if self.__handle and self.__handle == self.GetHandle():
  493. self._Iren.GetRenderWindow().Render()
  494. elif self.GetHandle() and self.__has_painted:
  495. # this means the user has reparented us; let's adapt to the
  496. # new situation by doing the WindowRemap dance
  497. self._Iren.GetRenderWindow().SetNextWindowInfo(
  498. str(self.GetHandle()))
  499. # make sure the DisplayId is also set correctly
  500. d = self.GetDisplayId()
  501. if d:
  502. self._Iren.GetRenderWindow().SetDisplayId(d)
  503. # do the actual remap with the new parent information
  504. self._Iren.GetRenderWindow().WindowRemap()
  505. # store the new situation
  506. self.__handle = self.GetHandle()
  507. self._Iren.GetRenderWindow().Render()
  508. def SetRenderWhenDisabled(self, newValue):
  509. """Change value of __RenderWhenDisabled ivar.
  510. If __RenderWhenDisabled is false (the default), this widget will not
  511. call Render() on the RenderWindow if the top level frame (i.e. the
  512. containing frame) has been disabled.
  513. This prevents recursive rendering during wx.SafeYield() calls.
  514. wx.SafeYield() can be called during the ProgressMethod() callback of
  515. a VTK object to have progress bars and other GUI elements updated -
  516. it does this by disabling all windows (disallowing user-input to
  517. prevent re-entrancy of code) and then handling all outstanding
  518. GUI events.
  519. However, this often triggers an OnPaint() method for wxVTKRWIs,
  520. resulting in a Render(), resulting in Update() being called whilst
  521. still in progress.
  522. """
  523. self.__RenderWhenDisabled = bool(newValue)
  524. #--------------------------------------------------------------------
  525. def wxVTKRenderWindowInteractorConeExample():
  526. """Like it says, just a simple example
  527. """
  528. from vtkmodules.vtkFiltersSources import vtkConeSource
  529. from vtkmodules.vtkRenderingCore import vtkActor, vtkPolyDataMapper, vtkRenderer
  530. # load implementations for rendering and interaction factory classes
  531. import vtkmodules.vtkRenderingOpenGL2
  532. import vtkmodules.vtkInteractionStyle
  533. # every wx app needs an app
  534. app = wx.App(False)
  535. # create the top-level frame, sizer and wxVTKRWI
  536. frame = wx.Frame(None, -1, "wxVTKRenderWindowInteractor", size=(400,400))
  537. widget = wxVTKRenderWindowInteractor(frame, -1)
  538. sizer = wx.BoxSizer(wx.VERTICAL)
  539. sizer.Add(widget, 1, wx.EXPAND)
  540. frame.SetSizer(sizer)
  541. frame.Layout()
  542. # It would be more correct (API-wise) to call widget.Initialize() and
  543. # widget.Start() here, but Initialize() calls RenderWindow.Render().
  544. # That Render() call will get through before we can setup the
  545. # RenderWindow() to render via the wxWidgets-created context; this
  546. # causes flashing on some platforms and downright breaks things on
  547. # other platforms. Instead, we call widget.Enable(). This means
  548. # that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE,
  549. # that doesn't matter.
  550. widget.Enable(1)
  551. widget.AddObserver("ExitEvent", lambda o,e,f=frame: f.Close())
  552. ren = vtkRenderer()
  553. widget.GetRenderWindow().AddRenderer(ren)
  554. cone = vtkConeSource()
  555. cone.SetResolution(8)
  556. coneMapper = vtkPolyDataMapper()
  557. coneMapper.SetInputConnection(cone.GetOutputPort())
  558. coneActor = vtkActor()
  559. coneActor.SetMapper(coneMapper)
  560. ren.AddActor(coneActor)
  561. # show the window
  562. frame.Show()
  563. app.MainLoop()
  564. if __name__ == "__main__":
  565. wxVTKRenderWindowInteractorConeExample()