controller.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. """!
  2. @package animation.controller
  3. @brief Animations management
  4. Classes:
  5. - controller::AnimationController
  6. (C) 2013 by the GRASS Development Team
  7. This program is free software under the GNU General Public License
  8. (>=v2). Read the file COPYING that comes with GRASS for details.
  9. @author Anna Petrasova <kratochanna gmail.com>
  10. """
  11. import os
  12. import wx
  13. from core.gcmd import GException, GError, GMessage
  14. from core.utils import _
  15. from grass.imaging import writeAvi, writeGif, writeIms, writeSwf
  16. from animation.temporal_manager import TemporalManager
  17. from animation.dialogs import InputDialog, EditDialog, ExportDialog
  18. from animation.utils import TemporalMode, Orientation, RenderText, WxImageToPil, \
  19. sampleCmdMatrixAndCreateNames, layerListToCmdsMatrix, HashCmds, getCpuCount
  20. from animation.data import AnimationData
  21. class AnimationController(wx.EvtHandler):
  22. def __init__(self, frame, sliders, animations, mapwindows, provider, bitmapPool, mapFilesPool):
  23. wx.EvtHandler.__init__(self)
  24. self.mapwindows = mapwindows
  25. self.frame = frame
  26. self.sliders = sliders
  27. self.slider = self.sliders['temporal']
  28. self.animationToolbar = None
  29. self.temporalMode = None
  30. self.animationData = []
  31. self.timer = wx.Timer(self, id=wx.NewId())
  32. self.animations = animations
  33. self.bitmapPool = bitmapPool
  34. self.mapFilesPool = mapFilesPool
  35. self.bitmapProvider = provider
  36. for anim, win in zip(self.animations, self.mapwindows):
  37. anim.SetCallbackUpdateFrame(
  38. lambda index, dataId, win=win: self.UpdateFrame(index, win, dataId))
  39. anim.SetCallbackEndAnimation(
  40. lambda index, dataId, win=win: self.UpdateFrameEnd(index, win, dataId))
  41. anim.SetCallbackOrientationChanged(self.OrientationChangedInReverseMode)
  42. for slider in self.sliders.values():
  43. slider.SetCallbackSliderChanging(self.SliderChanging)
  44. slider.SetCallbackSliderChanged(self.SliderChanged)
  45. slider.SetCallbackFrameIndexChanged(self.ChangeFrame)
  46. self.runAfterReleasingSlider = None
  47. self.temporalManager = TemporalManager()
  48. self.Bind(wx.EVT_TIMER, self.OnTimerTick, self.timer)
  49. self.timeTick = 200
  50. self._dialogs = {}
  51. def SetAnimationToolbar(self, toolbar):
  52. self.animationToolbar = toolbar
  53. def GetTimeTick(self):
  54. return self._timeTick
  55. def SetTimeTick(self, value):
  56. self._timeTick = value
  57. if self.timer.IsRunning():
  58. self.timer.Stop()
  59. self.timer.Start(self._timeTick)
  60. self.DisableSliderIfNeeded()
  61. timeTick = property(fget=GetTimeTick, fset=SetTimeTick)
  62. def OnTimerTick(self, event):
  63. for anim in self.animations:
  64. anim.Update()
  65. def StartAnimation(self):
  66. # if self.timer.IsRunning():
  67. # self.timer.Stop()
  68. for anim in self.animations:
  69. if self.timer.IsRunning():
  70. anim.NextFrameIndex()
  71. anim.Start()
  72. if not self.timer.IsRunning():
  73. self.timer.Start(self.timeTick)
  74. self.DisableSliderIfNeeded()
  75. def PauseAnimation(self, paused):
  76. if paused:
  77. if self.timer.IsRunning():
  78. self.timer.Stop()
  79. self.DisableSliderIfNeeded()
  80. else:
  81. if not self.timer.IsRunning():
  82. self.timer.Start(self.timeTick)
  83. self.DisableSliderIfNeeded()
  84. for anim in self.animations:
  85. anim.Pause(paused)
  86. def EndAnimation(self):
  87. if self.timer.IsRunning():
  88. self.timer.Stop()
  89. self.DisableSliderIfNeeded()
  90. for anim in self.animations:
  91. anim.Stop()
  92. def UpdateFrameEnd(self, index, win, dataId):
  93. if self.timer.IsRunning():
  94. self.timer.Stop()
  95. self.DisableSliderIfNeeded()
  96. self.animationToolbar.Stop()
  97. self.UpdateFrame(index, win, dataId)
  98. def UpdateFrame(self, index, win, dataId):
  99. bitmap = self.bitmapProvider.GetBitmap(dataId)
  100. if dataId is None:
  101. dataId = ''
  102. win.DrawBitmap(bitmap)
  103. # self.frame.SetStatusText(dataId)
  104. self.slider.UpdateFrame(index)
  105. def SliderChanging(self, index):
  106. if self.runAfterReleasingSlider is None:
  107. self.runAfterReleasingSlider = self.timer.IsRunning()
  108. self.PauseAnimation(True)
  109. self.ChangeFrame(index)
  110. def SliderChanged(self):
  111. if self.runAfterReleasingSlider:
  112. self.PauseAnimation(False)
  113. self.runAfterReleasingSlider = None
  114. def ChangeFrame(self, index):
  115. for anim in self.animations:
  116. anim.FrameChangedFromOutside(index)
  117. def DisableSliderIfNeeded(self):
  118. if self.timer.IsRunning() and self._timeTick < 100:
  119. self.slider.EnableSlider(False)
  120. else:
  121. self.slider.EnableSlider(True)
  122. def OrientationChangedInReverseMode(self, mode):
  123. if mode == Orientation.FORWARD:
  124. self.animationToolbar.PlayForward()
  125. elif mode == Orientation.BACKWARD:
  126. self.animationToolbar.PlayBack()
  127. def SetReplayMode(self, mode):
  128. for anim in self.animations:
  129. anim.replayMode = mode
  130. def SetOrientation(self, mode):
  131. for anim in self.animations:
  132. anim.orientation = mode
  133. def SetTemporalMode(self, mode):
  134. self._temporalMode = mode
  135. def GetTemporalMode(self):
  136. return self._temporalMode
  137. temporalMode = property(fget=GetTemporalMode, fset=SetTemporalMode)
  138. def GetTimeGranularity(self):
  139. if self.temporalMode == TemporalMode.TEMPORAL:
  140. return self.temporalManager.GetGranularity()
  141. return None
  142. def EditAnimations(self):
  143. # running = False
  144. # if self.timer.IsRunning():
  145. # running = True
  146. self.EndAnimation()
  147. dlg = EditDialog(parent=self.frame, evalFunction=self.EvaluateInput,
  148. animationData=self.animationData, maxAnimations=len(self.animations))
  149. dlg.CenterOnParent()
  150. if dlg.ShowModal() == wx.ID_CANCEL:
  151. dlg.Destroy()
  152. return
  153. self.animationData, self.temporalMode, self.temporalManager = dlg.GetResult()
  154. dlg.Destroy()
  155. self._setAnimations()
  156. def AddAnimation(self):
  157. # check if we can add more animations
  158. found = False
  159. indices = [anim.windowIndex for anim in self.animationData]
  160. for windowIndex in range(len(self.animations)):
  161. if windowIndex not in indices:
  162. found = True
  163. break
  164. if not found:
  165. GMessage(parent=self.frame,
  166. message=_("Maximum number of animations is %s.") % len(self.animations))
  167. return
  168. # running = False
  169. # if self.timer.IsRunning():
  170. # running = True
  171. self.EndAnimation()
  172. # self.PauseAnimation(True)
  173. animData = AnimationData()
  174. # number of active animations
  175. animationIndex = len([anim for anim in self.animations if anim.IsActive()])
  176. animData.SetDefaultValues(windowIndex, animationIndex)
  177. dlg = InputDialog(parent=self.frame, mode='add', animationData=animData)
  178. dlg.CenterOnParent()
  179. if dlg.ShowModal() == wx.ID_CANCEL:
  180. dlg.Destroy()
  181. return
  182. dlg.Destroy()
  183. # check compatibility
  184. if animData.windowIndex in indices:
  185. GMessage(parent=self.frame, message=_("More animations are using one window."
  186. " Please select different window for each animation."))
  187. return
  188. try:
  189. temporalMode, tempManager = self.EvaluateInput(self.animationData + [animData])
  190. except GException, e:
  191. GError(parent=self.frame, message=e.value, showTraceback=False)
  192. return
  193. # if ok, set temporal mode
  194. self.temporalMode = temporalMode
  195. self.temporalManager = tempManager
  196. # add data
  197. windowIndex = animData.windowIndex
  198. self.animationData.append(animData)
  199. self._setAnimations()
  200. def SetAnimations(self, layerLists):
  201. """!Set animation data directly.
  202. @param layerLists list of layerLists
  203. """
  204. try:
  205. animationData = []
  206. for i in range(len(self.animations)):
  207. if layerLists[i]:
  208. anim = AnimationData()
  209. anim.SetDefaultValues(i, i)
  210. anim.SetLayerList(layerLists[i])
  211. animationData.append(anim)
  212. except (GException, ValueError, IOError) as e:
  213. GError(parent=self.frame, message=str(e),
  214. showTraceback=False, caption=_("Invalid input"))
  215. return
  216. try:
  217. temporalMode, tempManager = self.EvaluateInput(animationData)
  218. except GException, e:
  219. GError(parent=self.frame, message=e.value, showTraceback=False)
  220. return
  221. self.animationData = animationData
  222. self.temporalManager = tempManager
  223. self.temporalMode = temporalMode
  224. self._setAnimations()
  225. def _setAnimations(self):
  226. indices = [anim.windowIndex for anim in self.animationData]
  227. self._updateWindows(activeIndices=indices)
  228. if self.temporalMode == TemporalMode.TEMPORAL:
  229. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  230. else:
  231. timeLabels, mapNamesDict = None, None
  232. for anim in self.animationData:
  233. if anim.viewMode == '2d':
  234. anim.cmdMatrix = layerListToCmdsMatrix(anim.layerList)
  235. else:
  236. anim.cmdMatrix = [(cmd,) for cmd in anim.GetNvizCommands()['commands']]
  237. self._updateSlider(timeLabels=timeLabels)
  238. self._updateAnimations(activeIndices=indices, mapNamesDict=mapNamesDict)
  239. wx.Yield()
  240. self._updateBitmapData()
  241. # if running:
  242. # self.PauseAnimation(False)
  243. # # self.StartAnimation()
  244. # else:
  245. self.EndAnimation()
  246. def _updateSlider(self, timeLabels=None):
  247. if self.temporalMode == TemporalMode.NONTEMPORAL:
  248. self.frame.SetSlider('nontemporal')
  249. self.slider = self.sliders['nontemporal']
  250. frameCount = self.animationData[0].mapCount
  251. self.slider.SetFrames(frameCount)
  252. elif self.temporalMode == TemporalMode.TEMPORAL:
  253. self.frame.SetSlider('temporal')
  254. self.slider = self.sliders['temporal']
  255. self.slider.SetTemporalType(self.temporalManager.temporalType)
  256. self.slider.SetFrames(timeLabels)
  257. else:
  258. self.frame.SetSlider(None)
  259. self.slider = None
  260. def _updateAnimations(self, activeIndices, mapNamesDict=None):
  261. if self.temporalMode == TemporalMode.NONTEMPORAL:
  262. for i in range(len(self.animations)):
  263. if i not in activeIndices:
  264. self.animations[i].SetActive(False)
  265. continue
  266. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  267. self.animations[i].SetFrames([HashCmds(cmdList) for cmdList in anim.cmdMatrix])
  268. self.animations[i].SetActive(True)
  269. else:
  270. for i in range(len(self.animations)):
  271. if i not in activeIndices:
  272. self.animations[i].SetActive(False)
  273. continue
  274. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  275. identifiers = sampleCmdMatrixAndCreateNames(anim.cmdMatrix,
  276. mapNamesDict[anim.firstStdsNameType[0]])
  277. self.animations[i].SetFrames(identifiers)
  278. self.animations[i].SetActive(True)
  279. def _updateWindows(self, activeIndices):
  280. # add or remove window
  281. for windowIndex in range(len(self.animations)):
  282. if not self.frame.IsWindowShown(windowIndex) and windowIndex in activeIndices:
  283. self.frame.AddWindow(windowIndex)
  284. elif self.frame.IsWindowShown(windowIndex) and windowIndex not in activeIndices:
  285. self.frame.RemoveWindow(windowIndex)
  286. def _updateBitmapData(self):
  287. # unload previous data
  288. self.bitmapProvider.Unload()
  289. # load new data
  290. for animData in self.animationData:
  291. if animData.viewMode == '2d':
  292. self._set2DData(animData)
  293. else:
  294. self._load3DData(animData)
  295. self._loadLegend(animData)
  296. self.bitmapProvider.Load(nprocs=getCpuCount())
  297. # clear pools
  298. self.bitmapPool.Clear()
  299. self.mapFilesPool.Clear()
  300. def _set2DData(self, animationData):
  301. opacities = [layer.opacity for layer in animationData.layerList if layer.active]
  302. self.bitmapProvider.SetCmds(animationData.cmdMatrix, opacities)
  303. def _load3DData(self, animationData):
  304. nviz = animationData.GetNvizCommands()
  305. self.bitmapProvider.SetCmds3D(nviz['commands'], nviz['region'])
  306. def _loadLegend(self, animationData):
  307. if animationData.legendCmd:
  308. try:
  309. bitmap = self.bitmapProvider.LoadOverlay(animationData.legendCmd)
  310. try:
  311. from PIL import Image
  312. for param in animationData.legendCmd:
  313. if param.startswith('at'):
  314. b, t, l, r = param.split('=')[1].split(',')
  315. x, y = float(l) / 100., 1 - float(t) / 100.
  316. break
  317. except ImportError:
  318. x, y = 0, 0
  319. self.mapwindows[animationData.windowIndex].SetOverlay(bitmap, x, y)
  320. except GException:
  321. GError(message=_("Failed to display legend."))
  322. else:
  323. self.mapwindows[animationData.windowIndex].ClearOverlay()
  324. def EvaluateInput(self, animationData):
  325. stds = 0
  326. maps = 0
  327. mapCount = set()
  328. tempManager = None
  329. windowIndex = []
  330. for anim in animationData:
  331. for layer in anim.layerList:
  332. if layer.active and hasattr(layer, 'maps'):
  333. if layer.mapType in ('strds', 'stvds'):
  334. stds += 1
  335. else:
  336. maps += 1
  337. mapCount.add(len(layer.maps))
  338. windowIndex.append(anim.windowIndex)
  339. if maps and stds:
  340. temporalMode = TemporalMode.NONTEMPORAL
  341. elif maps:
  342. temporalMode = TemporalMode.NONTEMPORAL
  343. elif stds:
  344. temporalMode = TemporalMode.TEMPORAL
  345. else:
  346. temporalMode = None
  347. if temporalMode == TemporalMode.NONTEMPORAL:
  348. if len(mapCount) > 1:
  349. raise GException(_("Inconsistent number of maps, please check input data."))
  350. elif temporalMode == TemporalMode.TEMPORAL:
  351. tempManager = TemporalManager()
  352. # these raise GException:
  353. for anim in animationData:
  354. tempManager.AddTimeSeries(*anim.firstStdsNameType)
  355. message = tempManager.EvaluateInputData()
  356. if message:
  357. GMessage(parent=self.frame, message=message)
  358. return temporalMode, tempManager
  359. def Reload(self):
  360. self.EndAnimation()
  361. self.bitmapProvider.Load(nprocs=getCpuCount(), force=True)
  362. self.EndAnimation()
  363. def Export(self):
  364. if not self.animationData:
  365. GMessage(parent=self.frame, message=_("No animation to export."))
  366. return
  367. if 'export' in self._dialogs:
  368. self._dialogs['export'].Show()
  369. self._dialogs['export'].Raise()
  370. else:
  371. dlg = ExportDialog(self.frame, temporal=self.temporalMode,
  372. timeTick=self.timeTick)
  373. dlg.doExport.connect(self._export)
  374. self._dialogs['export'] = dlg
  375. dlg.Show()
  376. def _export(self, exportInfo, decorations):
  377. size = self.frame.animationPanel.GetSize()
  378. if self.temporalMode == TemporalMode.TEMPORAL:
  379. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  380. frameCount = len(timeLabels)
  381. else:
  382. frameCount = self.animationData[0].mapCount # should be the same for all
  383. animWinSize = []
  384. animWinPos = []
  385. animWinIndex = []
  386. legends = [anim.legendCmd for anim in self.animationData]
  387. # determine position and sizes of bitmaps
  388. for i, (win, anim) in enumerate(zip(self.mapwindows, self.animations)):
  389. if anim.IsActive():
  390. pos = win.GetPosition()
  391. animWinPos.append(pos)
  392. animWinSize.append(win.GetSize())
  393. animWinIndex.append(i)
  394. images = []
  395. busy = wx.BusyInfo(message=_("Preparing export, please wait..."), parent=self.frame)
  396. wx.Yield()
  397. for frameIndex in range(frameCount):
  398. image = wx.EmptyImage(*size)
  399. image.Replace(0, 0, 0, 255, 255, 255)
  400. # collect bitmaps of all windows and paste them into the one
  401. for i in animWinIndex:
  402. frameId = self.animations[i].GetFrame(frameIndex)
  403. bitmap = self.bitmapProvider.GetBitmap(frameId)
  404. im = wx.ImageFromBitmap(bitmap)
  405. # add legend if used
  406. legend = legends[i]
  407. if legend:
  408. legendBitmap = self.bitmapProvider.LoadOverlay(legend)
  409. x, y = self.mapwindows[i].GetOverlayPos()
  410. legImage = wx.ImageFromBitmap(legendBitmap)
  411. # not so nice result, can we handle the transparency otherwise?
  412. legImage.ConvertAlphaToMask()
  413. im.Paste(legImage, x, y)
  414. if im.GetSize() != animWinSize[i]:
  415. im.Rescale(*animWinSize[i])
  416. image.Paste(im, *animWinPos[i])
  417. # paste decorations
  418. for decoration in decorations:
  419. # add image
  420. x = decoration['pos'][0] / 100. * size[0]
  421. y = decoration['pos'][1] / 100. * size[1]
  422. if decoration['name'] == 'image':
  423. decImage = wx.Image(decoration['file'])
  424. elif decoration['name'] == 'time':
  425. timeLabel = timeLabels[frameIndex]
  426. if timeLabel[1]:
  427. text = _("%(from)s %(dash)s %(to)s") % \
  428. {'from': timeLabel[0], 'dash': u"\u2013", 'to': timeLabel[1]}
  429. else:
  430. text = _("%(start)s %(unit)s") % \
  431. {'start': timeLabel[0], 'unit': timeLabel[2]}
  432. decImage = RenderText(text, decoration['font']).ConvertToImage()
  433. elif decoration['name'] == 'text':
  434. text = decoration['text']
  435. decImage = RenderText(text, decoration['font']).ConvertToImage()
  436. image.Paste(decImage, x, y)
  437. images.append(image)
  438. del busy
  439. # export
  440. pilImages = [WxImageToPil(image) for image in images]
  441. busy = wx.BusyInfo(message=_("Exporting animation, please wait..."),
  442. parent=self.frame)
  443. wx.Yield()
  444. try:
  445. if exportInfo['method'] == 'sequence':
  446. filename = os.path.join(exportInfo['directory'],
  447. exportInfo['prefix'] + '.' + exportInfo['format'].lower())
  448. writeIms(filename=filename, images=pilImages)
  449. elif exportInfo['method'] == 'gif':
  450. writeGif(filename=exportInfo['file'], images=pilImages,
  451. duration=self.timeTick / float(1000), repeat=True)
  452. elif exportInfo['method'] == 'swf':
  453. writeSwf(filename=exportInfo['file'], images=pilImages,
  454. duration=self.timeTick / float(1000), repeat=True)
  455. elif exportInfo['method'] == 'avi':
  456. writeAvi(filename=exportInfo['file'], images=pilImages,
  457. duration=self.timeTick / float(1000),
  458. encoding=exportInfo['encoding'],
  459. inputOptions=exportInfo['options'])
  460. except Exception, e:
  461. del busy
  462. GError(parent=self.frame, message=str(e))
  463. return
  464. del busy