controller.py 23 KB

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