controller.py 22 KB

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