controller.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. """!
  2. @package animation.controller
  3. @brief Animations management
  4. Classes:
  5. - controller::AnimationController
  6. (C) 2012 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 Kratochvilova <kratochanna gmail.com>
  10. """
  11. import os
  12. import wx
  13. try:
  14. import visvis.vvmovie as vv
  15. hasVisvis = True
  16. except ImportError:
  17. # if visvis.vvmovie is in grass python library
  18. # import grass.visvis as vv
  19. #
  20. # question: if integrate visvis, if integrate visvis.vvmovie or only
  21. # images2swf.py, images2gif.py?
  22. hasVisvis = False
  23. from core.gcmd import GException, GError, GMessage
  24. import grass.script as grass
  25. from temporal_manager import TemporalManager
  26. from dialogs import InputDialog, EditDialog, AnimationData, ExportDialog
  27. from utils import TemporalMode, Orientation, RenderText, WxImageToPil
  28. class AnimationController(wx.EvtHandler):
  29. def __init__(self, frame, sliders, animations, mapwindows, providers, bitmapPool):
  30. wx.EvtHandler.__init__(self)
  31. self.mapwindows = mapwindows
  32. self.frame = frame
  33. self.sliders = sliders
  34. self.slider = self.sliders['temporal']
  35. self.animationToolbar = None
  36. self.temporalMode = None
  37. self.animationData = []
  38. self.timer = wx.Timer(self, id = wx.NewId())
  39. self.animations = animations
  40. self.bitmapPool = bitmapPool
  41. self.bitmapProviders = providers
  42. for anim, win, provider in zip(self.animations, self.mapwindows, self.bitmapProviders):
  43. anim.SetCallbackUpdateFrame(lambda index, dataId, win = win, provider = provider : self.UpdateFrame(index, win, provider, dataId))
  44. anim.SetCallbackEndAnimation(lambda index, dataId, win = win, provider = provider: self.UpdateFrameEnd(index, win, provider, dataId))
  45. anim.SetCallbackOrientationChanged(self.OrientationChangedInReverseMode)
  46. for slider in self.sliders.values():
  47. slider.SetCallbackSliderChanging(self.SliderChanging)
  48. slider.SetCallbackSliderChanged(self.SliderChanged)
  49. slider.SetCallbackFrameIndexChanged(self.ChangeFrame)
  50. self.runAfterReleasingSlider = None
  51. self.temporalManager = TemporalManager()
  52. self.Bind(wx.EVT_TIMER, self.OnTimerTick, self.timer)
  53. self.timeTick = 200
  54. def SetAnimationToolbar(self, toolbar):
  55. self.animationToolbar = toolbar
  56. def GetTimeTick(self):
  57. return self._timeTick
  58. def SetTimeTick(self, value):
  59. self._timeTick = value
  60. if self.timer.IsRunning():
  61. self.timer.Stop()
  62. self.timer.Start(self._timeTick)
  63. self.DisableSliderIfNeeded()
  64. timeTick = property(fget = GetTimeTick, fset = SetTimeTick)
  65. def OnTimerTick(self, event):
  66. for anim in self.animations:
  67. anim.Update()
  68. def StartAnimation(self):
  69. # if self.timer.IsRunning():
  70. # self.timer.Stop()
  71. for anim in self.animations:
  72. if self.timer.IsRunning():
  73. anim.NextFrameIndex()
  74. anim.Start()
  75. if not self.timer.IsRunning():
  76. self.timer.Start(self.timeTick)
  77. self.DisableSliderIfNeeded()
  78. def PauseAnimation(self, paused):
  79. if paused:
  80. if self.timer.IsRunning():
  81. self.timer.Stop()
  82. self.DisableSliderIfNeeded()
  83. else:
  84. if not self.timer.IsRunning():
  85. self.timer.Start(self.timeTick)
  86. self.DisableSliderIfNeeded()
  87. for anim in self.animations:
  88. anim.Pause(paused)
  89. def EndAnimation(self):
  90. if self.timer.IsRunning():
  91. self.timer.Stop()
  92. self.DisableSliderIfNeeded()
  93. for anim in self.animations:
  94. anim.Stop()
  95. def UpdateFrameEnd(self, index, win, provider, dataId):
  96. if self.timer.IsRunning():
  97. self.timer.Stop()
  98. self.DisableSliderIfNeeded()
  99. self.animationToolbar.Stop()
  100. self.UpdateFrame(index, win, provider, dataId)
  101. def UpdateFrame(self, index, win, provider, dataId):
  102. bitmap = provider.GetBitmap(dataId)
  103. if dataId is None:
  104. dataId = ''
  105. win.DrawBitmap(bitmap, dataId)
  106. # self.frame.SetStatusText(dataId)
  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 EditAnimations(self):
  146. # running = False
  147. # if self.timer.IsRunning():
  148. # running = True
  149. self.EndAnimation()
  150. dlg = EditDialog(parent = self.frame, evalFunction = self.EvaluateInput,
  151. animationData = self.animationData, maxAnimations = len(self.animations))
  152. if dlg.ShowModal() == wx.ID_CANCEL:
  153. dlg.Destroy()
  154. return
  155. self.animationData, self.temporalMode, self.temporalManager = dlg.GetResult()
  156. dlg.Destroy()
  157. self._setAnimations()
  158. def AddAnimation(self):
  159. # check if we can add more animations
  160. found = False
  161. indices = [anim.windowIndex for anim in self.animationData]
  162. for windowIndex in range(len(self.animations)):
  163. if windowIndex not in indices:
  164. found = True
  165. break
  166. if not found:
  167. GMessage(parent = self.frame, message = _("Maximum number of animations is %s.") % len(self.animations))
  168. return
  169. # running = False
  170. # if self.timer.IsRunning():
  171. # running = True
  172. self.EndAnimation()
  173. # self.PauseAnimation(True)
  174. animData = AnimationData()
  175. # number of active animations
  176. animationIndex = len([anim for anim in self.animations if anim.IsActive()])
  177. animData.SetDefaultValues(windowIndex, animationIndex)
  178. dlg = InputDialog(parent = self.frame, mode = 'add', animationData = animData)
  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, raster = None, strds = None):
  201. """!Set animation data directly.
  202. @param raster list of lists of raster maps or None
  203. @param strds list of strds or None
  204. """
  205. try:
  206. animationData = []
  207. for i in range(len(self.animations)):
  208. if raster is not None and type(raster[i]) == list and raster[i]:
  209. anim = AnimationData()
  210. anim.SetDefaultValues(i, i)
  211. anim.inputMapType = 'rast'
  212. anim.inputData = ','.join(raster[i])
  213. animationData.append(anim)
  214. elif strds is not None and strds[i]:
  215. anim = AnimationData()
  216. anim.SetDefaultValues(i, i)
  217. anim.inputMapType = 'strds'
  218. anim.inputData = strds[i]
  219. animationData.append(anim)
  220. except (GException, ValueError, IOError) as e:
  221. GError(parent = self.frame, message = str(e),
  222. showTraceback = False, caption = _("Invalid input"))
  223. return
  224. try:
  225. temporalMode, tempManager = self.EvaluateInput(animationData)
  226. except GException, e:
  227. GError(parent = self.frame, message = e.value, showTraceback = False)
  228. return
  229. self.animationData = animationData
  230. self.temporalManager = tempManager
  231. self.temporalMode = temporalMode
  232. self._setAnimations()
  233. def _setAnimations(self):
  234. indices = [anim.windowIndex for anim in self.animationData]
  235. self._updateWindows(activeIndices = indices)
  236. if self.temporalMode == TemporalMode.TEMPORAL:
  237. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  238. else:
  239. timeLabels, mapNamesDict = None, None
  240. self._updateSlider(timeLabels = timeLabels)
  241. self._updateAnimations(activeIndices = indices, mapNamesDict = mapNamesDict)
  242. self._updateBitmapData()
  243. # if running:
  244. # self.PauseAnimation(False)
  245. # # self.StartAnimation()
  246. # else:
  247. self.EndAnimation()
  248. def _updateSlider(self, timeLabels = None):
  249. if self.temporalMode == TemporalMode.NONTEMPORAL:
  250. self.frame.SetSlider('nontemporal')
  251. self.slider = self.sliders['nontemporal']
  252. frameCount = len(self.animationData[0].mapData) # should be the same for all
  253. self.slider.SetFrames(frameCount)
  254. elif self.temporalMode == TemporalMode.TEMPORAL:
  255. self.frame.SetSlider('temporal')
  256. self.slider = self.sliders['temporal']
  257. self.slider.SetTemporalType(self.temporalManager.temporalType)
  258. self.slider.SetFrames(timeLabels)
  259. else:
  260. self.frame.SetSlider(None)
  261. self.slider = None
  262. def _updateAnimations(self, activeIndices, mapNamesDict = None):
  263. if self.temporalMode == TemporalMode.NONTEMPORAL:
  264. for i in range(len(self.animations)):
  265. if i not in activeIndices:
  266. self.animations[i].SetActive(False)
  267. continue
  268. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  269. self.animations[i].SetFrames(anim.mapData)
  270. self.animations[i].SetActive(True)
  271. else:
  272. for i in range(len(self.animations)):
  273. if i not in activeIndices:
  274. self.animations[i].SetActive(False)
  275. continue
  276. anim = [anim for anim in self.animationData if anim.windowIndex == i][0]
  277. self.animations[i].SetFrames(mapNamesDict[anim.inputData])
  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 data:
  288. for prov in self.bitmapProviders:
  289. prov.Unload()
  290. # load data
  291. for animData in self.animationData:
  292. if animData.viewMode == '2d':
  293. self._load2DData(animData)
  294. else:
  295. self._load3DData(animData)
  296. # clear bitmapPool
  297. usedNames = []
  298. for prov in self.bitmapProviders:
  299. names = prov.GetDataNames()
  300. if names:
  301. usedNames.extend(names)
  302. self.bitmapPool.Clear(usedNames)
  303. def _load2DData(self, animationData):
  304. prov = self.bitmapProviders[animationData.windowIndex]
  305. prov.SetData(datasource = animationData.mapData)
  306. self.bitmapProviders[animationData.windowIndex].Load()
  307. def _load3DData(self, animationData):
  308. prov = self.bitmapProviders[animationData.windowIndex]
  309. nviz = animationData.GetNvizCommands()
  310. prov.SetData(datasource = nviz['commands'],
  311. dataNames = animationData.mapData, dataType = 'nviz',
  312. suffix = animationData.nvizParameter,
  313. nvizRegion = nviz['region'])
  314. self.bitmapProviders[animationData.windowIndex].Load()
  315. def EvaluateInput(self, animationData):
  316. stds = 0
  317. maps = 0
  318. mapCount = set()
  319. tempManager = None
  320. windowIndex = []
  321. for anim in animationData:
  322. mapCount.add(len(anim.mapData))
  323. windowIndex.append(anim.windowIndex)
  324. if anim.inputMapType in ('rast', 'vect'):
  325. maps += 1
  326. elif anim.inputMapType in ('strds', 'stvds'):
  327. stds += 1
  328. if maps and stds:
  329. temporalMode = TemporalMode.NONTEMPORAL
  330. elif maps:
  331. temporalMode = TemporalMode.NONTEMPORAL
  332. elif stds:
  333. temporalMode = TemporalMode.TEMPORAL
  334. else:
  335. temporalMode = None
  336. if temporalMode == TemporalMode.NONTEMPORAL:
  337. if len(mapCount) > 1:
  338. raise GException(_("Inconsistent number of maps, please check input data."))
  339. elif temporalMode == TemporalMode.TEMPORAL:
  340. tempManager = TemporalManager()
  341. # these raise GException:
  342. for anim in animationData:
  343. if anim.inputMapType not in ('strds', 'stvds'):
  344. continue
  345. tempManager.AddTimeSeries(anim.inputData, anim.inputMapType)
  346. message = tempManager.EvaluateInputData()
  347. if message:
  348. GMessage(parent = self.frame, message = message)
  349. return temporalMode, tempManager
  350. def Reload(self):
  351. self.EndAnimation()
  352. activeIndices = [anim.windowIndex for anim in self.animationData]
  353. for index in activeIndices:
  354. self.bitmapProviders[index].Load(force = True)
  355. self.EndAnimation()
  356. def Export(self):
  357. if not self.animationData:
  358. GMessage(parent = self.frame, message = _("No animation to export."))
  359. return
  360. dlg = ExportDialog(self.frame, temporal = self.temporalMode,
  361. timeTick = self.timeTick, visvis = hasVisvis)
  362. if dlg.ShowModal() == wx.ID_OK:
  363. decorations = dlg.GetDecorations()
  364. exportInfo = dlg.GetExportInformation()
  365. dlg.Destroy()
  366. else:
  367. dlg.Destroy()
  368. return
  369. self._export(exportInfo, decorations)
  370. def _export(self, exportInfo, decorations):
  371. size = self.frame.animationPanel.GetSize()
  372. if self.temporalMode == TemporalMode.TEMPORAL:
  373. timeLabels, mapNamesDict = self.temporalManager.GetLabelsAndMaps()
  374. frameCount = len(timeLabels)
  375. else:
  376. frameCount = len(self.animationData[0].mapData) # should be the same for all
  377. animWinSize = []
  378. animWinPos = []
  379. animWinIndex = []
  380. # determine position and sizes of bitmaps
  381. for i, (win, anim) in enumerate(zip(self.mapwindows, self.animations)):
  382. if anim.IsActive():
  383. pos = tuple([pos1 + pos2 for pos1, pos2 in zip(win.GetPosition(), win.GetAdjustedPosition())])
  384. animWinPos.append(pos)
  385. animWinSize.append(win.GetAdjustedSize())
  386. animWinIndex.append(i)
  387. images = []
  388. for frameIndex in range(frameCount):
  389. image = wx.EmptyImage(*size)
  390. image.Replace(0, 0, 0, 255, 255, 255)
  391. # collect bitmaps of all windows and paste them into the one
  392. for i in range(len(animWinSize)):
  393. frameId = self.animations[animWinIndex[i]].GetFrame(frameIndex)
  394. bitmap = self.bitmapProviders[animWinIndex[i]].GetBitmap(frameId)
  395. im = wx.ImageFromBitmap(bitmap)
  396. if im.GetSize() != animWinSize[i]:
  397. im.Rescale(*animWinSize[i])
  398. image.Paste(im, *animWinPos[i])
  399. # paste decorations
  400. for decoration in decorations:
  401. # add image
  402. x = decoration['pos'][0] / 100. * size[0]
  403. y = decoration['pos'][1] / 100. * size[1]
  404. if decoration['name'] == 'image':
  405. decImage = wx.Image(decoration['file'])
  406. elif decoration['name'] == 'time':
  407. timeLabel = timeLabels[frameIndex]
  408. if timeLabel[1]:
  409. text = _("%(from)s %(dash)s %(to)s") % \
  410. {'from': timeLabel[0], 'dash': u"\u2013", 'to': timeLabel[1]}
  411. else:
  412. text = _("%(start)s %(unit)s") % \
  413. {'start': timeLabel[0], 'unit': timeLabel[2]}
  414. decImage = RenderText(text, decoration['font']).ConvertToImage()
  415. elif decoration['name'] == 'text':
  416. text = decoration['text']
  417. decImage = RenderText(text, decoration['font']).ConvertToImage()
  418. image.Paste(decImage, x, y)
  419. images.append(image)
  420. # export
  421. if exportInfo['method'] == 'sequence':
  422. busy = wx.BusyInfo(message = _("Exporting images, please wait..."), parent = self.frame)
  423. wx.Yield()
  424. zeroPadding = len(str(len(images)))
  425. for i, image in enumerate(images):
  426. filename = "%s_%s.%s" % (exportInfo['prefix'], str(i + 1).zfill(zeroPadding),
  427. exportInfo['format']['ext'])
  428. image.SaveFile(os.path.join(exportInfo['directory'], filename), exportInfo['format']['type'])
  429. busy.Destroy()
  430. elif exportInfo['method'] in ('gif', 'swf', 'avi'):
  431. pilImages = [WxImageToPil(image) for image in images]
  432. busy = wx.BusyInfo(message = _("Exporting animation, please wait..."), parent = self.frame)
  433. wx.Yield()
  434. try:
  435. if exportInfo['method'] == 'gif':
  436. vv.writeGif(filename = exportInfo['file'], images = pilImages,
  437. duration = self.timeTick / float(1000), repeat = True)
  438. elif exportInfo['method'] == 'swf':
  439. vv.writeSwf(filename = exportInfo['file'], images = pilImages,
  440. duration = self.timeTick / float(1000), repeat = True)
  441. elif exportInfo['method'] == 'avi':
  442. vv.writeAvi(filename = exportInfo['file'], images = pilImages,
  443. duration = self.timeTick / float(1000),
  444. encoding = exportInfo['encoding'],
  445. inputOptions = '-sameq')
  446. except Exception, e:
  447. del busy
  448. GError(parent = self.frame, message = str(e))
  449. return
  450. del busy
  451. # image.SaveFile('/home/anna/testy/grass/export/export_%s.png' % frameIndex, wx.BITMAP_TYPE_PNG)
  452. # for anim in self.animationData
  453. #def test():
  454. # import gettext
  455. # gettext.install('grasswxpy', os.path.join(os.getenv("GISBASE"), 'locale'), unicode = True)
  456. #
  457. # import grass.script as grass
  458. # import wx
  459. # app = wx.PySimpleApp()
  460. # wx.InitAllImageHandlers()
  461. # # app.MainLoop()
  462. #
  463. # bitmaps = {}
  464. # rasters = ['elevation.dem']
  465. # # rasters = ['streams']
  466. # # rasters = grass.read_command("g.mlist", type = 'rast', fs = ',', quiet = True).strip().split(',')
  467. #
  468. # # print nrows, ncols
  469. # size = (300,100)
  470. # newSize, scale = ComputeScale(size)
  471. # # print scale
  472. # LoadRasters(rasters = rasters, bitmaps = bitmaps, scale = scale, size = newSize)
  473. #
  474. # for b in bitmaps.keys():
  475. # bitmaps[b].SaveFile('/home/anna/testy/ctypes/' + b + '.png', wx.BITMAP_TYPE_PNG)
  476. #
  477. #if __name__ == '__main__':
  478. #
  479. # test()