provider.py 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816
  1. # -*- coding: utf-8 -*-
  2. """!
  3. @package animation.provider
  4. @brief Animation files and bitmaps management
  5. Classes:
  6. - mapwindow::BitmapProvider
  7. - mapwindow::BitmapRenderer
  8. - mapwindow::BitmapComposer
  9. - mapwindow::DictRefCounter
  10. - mapwindow::MapFilesPool
  11. - mapwindow::BitmapPool
  12. - mapwindow::CleanUp
  13. (C) 2013 by the GRASS Development Team
  14. This program is free software under the GNU General Public License
  15. (>=v2). Read the file COPYING that comes with GRASS for details.
  16. @author Anna Petrasova <kratochanna gmail.com>
  17. """
  18. import os
  19. import sys
  20. import wx
  21. import tempfile
  22. from multiprocessing import Process, Queue
  23. if __name__ == '__main__':
  24. sys.path.append(os.path.join(os.environ['GISBASE'], "etc", "gui", "wxpython"))
  25. from core.gcmd import RunCommand, GException
  26. from core.settings import UserSettings
  27. from core.debug import Debug
  28. from core.utils import _, CmdToTuple, autoCropImageFromFile
  29. from animation.utils import HashCmd, HashCmds, GetFileFromCmd, GetFileFromCmds
  30. import grass.script.core as gcore
  31. from grass.pydispatch.signal import Signal
  32. class BitmapProvider:
  33. """!Class for management of image files and bitmaps.
  34. There is one instance of this class in the application.
  35. It handles both 2D and 3D animations.
  36. """
  37. def __init__(self, bitmapPool, mapFilesPool, tempDir,
  38. imageWidth=640, imageHeight=480):
  39. self._bitmapPool = bitmapPool
  40. self._mapFilesPool = mapFilesPool
  41. self.imageWidth = imageWidth # width of the image to render with d.rast or d.vect
  42. self.imageHeight = imageHeight # height of the image to render with d.rast or d.vect
  43. self._tempDir = tempDir
  44. self._uniqueCmds = []
  45. self._cmdsForComposition = []
  46. self._opacities = []
  47. self._cmds3D = []
  48. self._regionFor3D = None
  49. self._regions = []
  50. self._regionsForUniqueCmds = []
  51. self._renderer = BitmapRenderer(self._mapFilesPool, self._tempDir,
  52. self.imageWidth, self.imageHeight)
  53. self._composer = BitmapComposer(self._tempDir, self._mapFilesPool,
  54. self._bitmapPool, self.imageWidth,
  55. self.imageHeight)
  56. self.renderingStarted = Signal('BitmapProvider.renderingStarted')
  57. self.compositionStarted = Signal('BitmapProvider.compositionStarted')
  58. self.renderingContinues = Signal('BitmapProvider.renderingContinues')
  59. self.compositionContinues = Signal('BitmapProvider.compositionContinues')
  60. self.renderingFinished = Signal('BitmapProvider.renderingFinished')
  61. self.compositionFinished = Signal('BitmapProvider.compositionFinished')
  62. self.mapsLoaded = Signal('BitmapProvider.mapsLoaded')
  63. self._renderer.renderingContinues.connect(self.renderingContinues)
  64. self._composer.compositionContinues.connect(self.compositionContinues)
  65. def SetCmds(self, cmdsForComposition, opacities, regions=None):
  66. """!Sets commands to be rendered with opacity levels.
  67. Applies to 2D mode.
  68. @param cmdsForComposition list of lists of command lists
  69. [[['d.rast', 'map=elev_2001'], ['d.vect', 'map=points']], # g.pnmcomp
  70. [['d.rast', 'map=elev_2002'], ['d.vect', 'map=points']],
  71. ...]
  72. @param opacities list of opacity values
  73. @param regions list of regions
  74. """
  75. Debug.msg(2, "BitmapProvider.SetCmds: {n} lists".format(n=len(cmdsForComposition)))
  76. self._cmdsForComposition.extend(cmdsForComposition)
  77. self._opacities.extend(opacities)
  78. self._regions.extend(regions)
  79. self._getUniqueCmds()
  80. def SetCmds3D(self, cmds, region):
  81. """!Sets commands for 3D rendering.
  82. @param cmds list of commands m.nviz.image (cmd as a list)
  83. @param region for 3D rendering
  84. """
  85. Debug.msg(2, "BitmapProvider.SetCmds3D: {c} commands".format(c=len(cmds)))
  86. self._cmds3D = cmds
  87. self._regionFor3D = region
  88. def _getUniqueCmds(self):
  89. """!Returns list of unique commands.
  90. Takes into account the region assigned."""
  91. unique = list()
  92. for cmdList, region in zip(self._cmdsForComposition, self._regions):
  93. for cmd in cmdList:
  94. if region:
  95. unique.append((tuple(cmd), tuple(sorted(region.items()))))
  96. else:
  97. unique.append((tuple(cmd), None))
  98. unique = list(set(unique))
  99. self._uniqueCmds = [cmdAndRegion[0] for cmdAndRegion in unique]
  100. self._regionsForUniqueCmds.extend([dict(cmdAndRegion[1]) if cmdAndRegion[1] else None
  101. for cmdAndRegion in unique])
  102. def Unload(self):
  103. """!Unloads currently loaded data.
  104. Needs to be called before setting new data.
  105. """
  106. Debug.msg(2, "BitmapProvider.Unload")
  107. if self._cmdsForComposition:
  108. for cmd, region in zip(self._uniqueCmds, self._regionsForUniqueCmds):
  109. del self._mapFilesPool[HashCmd(cmd, region)]
  110. for cmdList, region in zip(self._cmdsForComposition, self._regions):
  111. del self._bitmapPool[HashCmds(cmdList, region)]
  112. self._uniqueCmds = []
  113. self._cmdsForComposition = []
  114. self._opacities = []
  115. self._regions = []
  116. self._regionsForUniqueCmds = []
  117. if self._cmds3D:
  118. self._cmds3D = []
  119. self._regionFor3D = None
  120. def _dryRender(self, uniqueCmds, regions, force):
  121. """!Determines how many files will be rendered.
  122. @param uniqueCmds list of commands which are to be rendered
  123. @param force if forced rerendering
  124. @param regions list of regions assigned to the commands
  125. """
  126. count = 0
  127. for cmd, region in zip(uniqueCmds, regions):
  128. filename = GetFileFromCmd(self._tempDir, cmd, region)
  129. if not force and os.path.exists(filename) and \
  130. self._mapFilesPool.GetSize(HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
  131. continue
  132. count += 1
  133. Debug.msg(3, "BitmapProvider._dryRender: {c} files to be rendered".format(c=count))
  134. return count
  135. def _dryCompose(self, cmdLists, regions, force):
  136. """!Determines how many lists of (commands) files
  137. will be composed (with g.pnmcomp).
  138. @param cmdLists list of commands lists which are to be composed
  139. @param regions list of regions assigned to the commands
  140. @param force if forced rerendering
  141. """
  142. count = 0
  143. for cmdList, region in zip(cmdLists, regions):
  144. if not force and HashCmds(cmdList, region) in self._bitmapPool and \
  145. self._bitmapPool[HashCmds(cmdList, region)].GetSize() == (self.imageWidth,
  146. self.imageHeight):
  147. continue
  148. count += 1
  149. Debug.msg(2, "BitmapProvider._dryCompose: {c} files to be composed".format(c=count))
  150. return count
  151. def Load(self, force=False, bgcolor=(255, 255, 255), nprocs=4):
  152. """!Loads data, both 2D and 3D. In case of 2D, it creates composites,
  153. even when there is only 1 layer to compose (to be changed for speedup)
  154. @param force if True reload all data, otherwise only missing data
  155. @param bgcolor background color as a tuple of 3 values 0 to 255
  156. @param nprocs number of procs to be used for rendering
  157. """
  158. Debug.msg(2, "BitmapProvider.Load: "
  159. "force={f}, bgcolor={b}, nprocs={n}".format(f=force,
  160. b=bgcolor,
  161. n=nprocs))
  162. cmds = []
  163. regions = []
  164. if self._uniqueCmds:
  165. cmds.extend(self._uniqueCmds)
  166. regions.extend(self._regionsForUniqueCmds)
  167. if self._cmds3D:
  168. cmds.extend(self._cmds3D)
  169. regions.extend([None] * len(self._cmds3D))
  170. count = self._dryRender(cmds, regions, force=force)
  171. self.renderingStarted.emit(count=count)
  172. # create no data bitmap
  173. if None not in self._bitmapPool or force:
  174. self._bitmapPool[None] = createNoDataBitmap(self.imageWidth, self.imageHeight)
  175. ok = self._renderer.Render(cmds, regions, regionFor3D=self._regionFor3D,
  176. bgcolor=bgcolor, force=force, nprocs=nprocs)
  177. self.renderingFinished.emit()
  178. if not ok:
  179. self.mapsLoaded.emit() # what to do here?
  180. return
  181. if self._cmdsForComposition:
  182. count = self._dryCompose(self._cmdsForComposition, self._regions, force=force)
  183. self.compositionStarted.emit(count=count)
  184. self._composer.Compose(self._cmdsForComposition, self._regions, self._opacities,
  185. bgcolor=bgcolor, force=force, nprocs=nprocs)
  186. self.compositionFinished.emit()
  187. if self._cmds3D:
  188. for cmd in self._cmds3D:
  189. self._bitmapPool[HashCmds([cmd], None)] = \
  190. wx.Bitmap(GetFileFromCmd(self._tempDir, cmd, None))
  191. self.mapsLoaded.emit()
  192. def RequestStopRendering(self):
  193. """!Requests to stop rendering/composition"""
  194. Debug.msg(2, "BitmapProvider.RequestStopRendering")
  195. self._renderer.RequestStopRendering()
  196. self._composer.RequestStopComposing()
  197. def GetBitmap(self, dataId):
  198. """!Returns bitmap with given key
  199. or 'no data' bitmap if no such key exists.
  200. @param dataId name of bitmap
  201. """
  202. try:
  203. bitmap = self._bitmapPool[dataId]
  204. except KeyError:
  205. bitmap = self._bitmapPool[None]
  206. return bitmap
  207. def WindowSizeChanged(self, width, height):
  208. """!Sets size when size of related window changes."""
  209. Debug.msg(5, "BitmapProvider.WindowSizeChanged: w={w}, h={h}".format(w=width, h=height))
  210. self.imageWidth, self.imageHeight = width, height
  211. self._composer.imageWidth = self._renderer.imageWidth = width
  212. self._composer.imageHeight = self._renderer.imageHeight = height
  213. def LoadOverlay(self, cmd):
  214. """!Creates raster legend with d.legend
  215. @param cmd d.legend command as a list
  216. @return bitmap with legend
  217. """
  218. Debug.msg(5, "BitmapProvider.LoadOverlay: cmd={c}".format(c=cmd))
  219. fileHandler, filename = tempfile.mkstemp(suffix=".png")
  220. os.close(fileHandler)
  221. # Set the environment variables for this process
  222. _setEnvironment(self.imageWidth, self.imageHeight, filename,
  223. transparent=True, bgcolor=(0, 0, 0))
  224. Debug.msg(1, "Render raster legend " + str(filename))
  225. cmdTuple = CmdToTuple(cmd)
  226. returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
  227. if returncode == 0:
  228. return wx.BitmapFromImage(autoCropImageFromFile(filename))
  229. else:
  230. os.remove(filename)
  231. raise GException(messages)
  232. class BitmapRenderer:
  233. """!Class which renderes 2D and 3D images to files."""
  234. def __init__(self, mapFilesPool, tempDir,
  235. imageWidth, imageHeight):
  236. self._mapFilesPool = mapFilesPool
  237. self._tempDir = tempDir
  238. self.imageWidth = imageWidth
  239. self.imageHeight = imageHeight
  240. self.renderingContinues = Signal('BitmapRenderer.renderingContinues')
  241. self._stopRendering = False
  242. self._isRendering = False
  243. def Render(self, cmdList, regions, regionFor3D, bgcolor, force, nprocs):
  244. """!Renders all maps and stores files.
  245. @param cmdList list of rendering commands to run
  246. @param regions regions for 2D rendering assigned to commands
  247. @param regionFor3D region for setting 3D view
  248. @param bgcolor background color as a tuple of 3 values 0 to 255
  249. @param force if True reload all data, otherwise only missing data
  250. @param nprocs number of procs to be used for rendering
  251. """
  252. Debug.msg(3, "BitmapRenderer.Render")
  253. count = 0
  254. # Variables for parallel rendering
  255. proc_count = 0
  256. proc_list = []
  257. queue_list = []
  258. cmd_list = []
  259. filteredCmdList = []
  260. for cmd, region in zip(cmdList, regions):
  261. filename = GetFileFromCmd(self._tempDir, cmd, region)
  262. if not force and os.path.exists(filename) and \
  263. self._mapFilesPool.GetSize(HashCmd(cmd, region)) == (self.imageWidth, self.imageHeight):
  264. # for reference counting
  265. self._mapFilesPool[HashCmd(cmd, region)] = filename
  266. continue
  267. filteredCmdList.append((cmd, region))
  268. mapNum = len(filteredCmdList)
  269. stopped = False
  270. self._isRendering = True
  271. for cmd, region in filteredCmdList:
  272. count += 1
  273. # Queue object for interprocess communication
  274. q = Queue()
  275. # The separate render process
  276. if cmd[0] == 'm.nviz.image':
  277. p = Process(target=RenderProcess3D,
  278. args=(self.imageWidth, self.imageHeight, self._tempDir,
  279. cmd, regionFor3D, bgcolor, q))
  280. else:
  281. p = Process(target=RenderProcess2D,
  282. args=(self.imageWidth, self.imageHeight, self._tempDir,
  283. cmd, region, bgcolor, q))
  284. p.start()
  285. queue_list.append(q)
  286. proc_list.append(p)
  287. cmd_list.append((cmd, region))
  288. proc_count += 1
  289. # Wait for all running processes and read/store the created images
  290. if proc_count == nprocs or count == mapNum:
  291. for i in range(len(cmd_list)):
  292. proc_list[i].join()
  293. filename = queue_list[i].get()
  294. self._mapFilesPool[HashCmd(cmd_list[i][0], cmd_list[i][1])] = filename
  295. self._mapFilesPool.SetSize(HashCmd(cmd_list[i][0], cmd_list[i][1]),
  296. (self.imageWidth, self.imageHeight))
  297. proc_count = 0
  298. proc_list = []
  299. queue_list = []
  300. cmd_list = []
  301. self.renderingContinues.emit(current=count, text=_("Rendering map layers"))
  302. if self._stopRendering:
  303. self._stopRendering = False
  304. stopped = True
  305. break
  306. self._isRendering = False
  307. return not stopped
  308. def RequestStopRendering(self):
  309. """!Requests to stop rendering."""
  310. if self._isRendering:
  311. self._stopRendering = True
  312. class BitmapComposer:
  313. """!Class which handles the composition of image files with g.pnmcomp."""
  314. def __init__(self, tempDir, mapFilesPool, bitmapPool,
  315. imageWidth, imageHeight):
  316. self._mapFilesPool = mapFilesPool
  317. self._bitmapPool = bitmapPool
  318. self._tempDir = tempDir
  319. self.imageWidth = imageWidth
  320. self.imageHeight = imageHeight
  321. self.compositionContinues = Signal('BitmapComposer.composingContinues')
  322. self._stopComposing = False
  323. self._isComposing = False
  324. def Compose(self, cmdLists, regions, opacityList, bgcolor, force, nprocs):
  325. """!Performs the composition of ppm/pgm files.
  326. @param cmdLisst lists of rendering commands lists to compose
  327. @param regions regions for 2D rendering assigned to commands
  328. @param opacityList list of lists of opacity values
  329. @param bgcolor background color as a tuple of 3 values 0 to 255
  330. @param force if True reload all data, otherwise only missing data
  331. @param nprocs number of procs to be used for rendering
  332. """
  333. Debug.msg(3, "BitmapComposer.Compose")
  334. count = 0
  335. # Variables for parallel rendering
  336. proc_count = 0
  337. proc_list = []
  338. queue_list = []
  339. cmd_lists = []
  340. filteredCmdLists = []
  341. for cmdList, region in zip(cmdLists, regions):
  342. if not force and HashCmds(cmdList, region) in self._bitmapPool and \
  343. self._bitmapPool[HashCmds(cmdList, region)].GetSize() == (self.imageWidth,
  344. self.imageHeight):
  345. # TODO: find a better way than to assign the same to increase the reference
  346. self._bitmapPool[HashCmds(cmdList, region)] = self._bitmapPool[HashCmds(cmdList, region)]
  347. continue
  348. filteredCmdLists.append((cmdList, region))
  349. num = len(filteredCmdLists)
  350. self._isComposing = True
  351. for cmdList, region in filteredCmdLists:
  352. count += 1
  353. # Queue object for interprocess communication
  354. q = Queue()
  355. # The separate render process
  356. p = Process(target=CompositeProcess,
  357. args=(self.imageWidth, self.imageHeight, self._tempDir,
  358. cmdList, region, opacityList, bgcolor, q))
  359. p.start()
  360. queue_list.append(q)
  361. proc_list.append(p)
  362. cmd_lists.append((cmdList, region))
  363. proc_count += 1
  364. # Wait for all running processes and read/store the created images
  365. if proc_count == nprocs or count == num:
  366. for i in range(len(cmd_lists)):
  367. proc_list[i].join()
  368. filename = queue_list[i].get()
  369. if filename is None:
  370. self._bitmapPool[HashCmds(cmd_lists[i][0], cmd_lists[i][1])] = \
  371. createNoDataBitmap(self.imageWidth, self.imageHeight,
  372. text="Failed to render")
  373. else:
  374. self._bitmapPool[HashCmds(cmd_lists[i][0], cmd_lists[i][1])] = \
  375. wx.BitmapFromImage(wx.Image(filename))
  376. os.remove(filename)
  377. proc_count = 0
  378. proc_list = []
  379. queue_list = []
  380. cmd_lists = []
  381. self.compositionContinues.emit(current=count, text=_("Overlaying map layers"))
  382. if self._stopComposing:
  383. self._stopComposing = False
  384. break
  385. self._isComposing = False
  386. def RequestStopComposing(self):
  387. """!Requests to stop the composition."""
  388. if self._isComposing:
  389. self._stopComposing = True
  390. def RenderProcess2D(imageWidth, imageHeight, tempDir, cmd, region, bgcolor, fileQueue):
  391. """!Render raster or vector files as ppm image and write the
  392. resulting ppm filename in the provided file queue
  393. @param imageWidth image width
  394. @param imageHeight image height
  395. @param tempDir directory for rendering
  396. @param cmd d.rast/d.vect command as a list
  397. @param region region as a dict or None
  398. @param bgcolor background color as a tuple of 3 values 0 to 255
  399. @param fileQueue the inter process communication queue
  400. storing the file name of the image
  401. """
  402. filename = GetFileFromCmd(tempDir, cmd, region)
  403. transparency = True
  404. # Set the environment variables for this process
  405. _setEnvironment(imageWidth, imageHeight, filename,
  406. transparent=transparency, bgcolor=bgcolor)
  407. if region:
  408. os.environ['GRASS_REGION'] = gcore.region_env(**region)
  409. cmdTuple = CmdToTuple(cmd)
  410. returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
  411. if returncode != 0:
  412. gcore.warning("Rendering failed:\n" + messages)
  413. fileQueue.put(None)
  414. if region:
  415. os.environ.pop('GRASS_REGION')
  416. os.remove(filename)
  417. return
  418. if region:
  419. os.environ.pop('GRASS_REGION')
  420. fileQueue.put(filename)
  421. def RenderProcess3D(imageWidth, imageHeight, tempDir, cmd, region, bgcolor, fileQueue):
  422. """!Renders image with m.nviz.image and writes the
  423. resulting ppm filename in the provided file queue
  424. @param imageWidth image width
  425. @param imageHeight image height
  426. @param tempDir directory for rendering
  427. @param cmd m.nviz.image command as a list
  428. @param region region as a dict
  429. @param bgcolor background color as a tuple of 3 values 0 to 255
  430. @param fileQueue the inter process communication queue
  431. storing the file name of the image
  432. """
  433. filename = GetFileFromCmd(tempDir, cmd, None)
  434. os.environ['GRASS_REGION'] = gcore.region_env(region3d=True, **region)
  435. Debug.msg(1, "Render image to file " + str(filename))
  436. cmdTuple = CmdToTuple(cmd)
  437. cmdTuple[1]['output'] = os.path.splitext(filename)[0]
  438. # set size
  439. cmdTuple[1]['size'] = '%d,%d' % (imageWidth, imageHeight)
  440. # set format
  441. cmdTuple[1]['format'] = 'ppm'
  442. cmdTuple[1]['bgcolor'] = bgcolor = ':'.join([str(part) for part in bgcolor])
  443. returncode, stdout, messages = read2_command(cmdTuple[0], **cmdTuple[1])
  444. if returncode != 0:
  445. gcore.warning("Rendering failed:\n" + messages)
  446. fileQueue.put(None)
  447. os.environ.pop('GRASS_REGION')
  448. return
  449. os.environ.pop('GRASS_REGION')
  450. fileQueue.put(filename)
  451. def CompositeProcess(imageWidth, imageHeight, tempDir, cmdList, region, opacities, bgcolor, fileQueue):
  452. """!Performs the composition of image ppm files and writes the
  453. resulting ppm filename in the provided file queue
  454. @param imageWidth image width
  455. @param imageHeight image height
  456. @param tempDir directory for rendering
  457. @param cmdList list of d.rast/d.vect commands
  458. @param region region as a dict or None
  459. @param opacities list of opacities
  460. @param bgcolor background color as a tuple of 3 values 0 to 255
  461. @param fileQueue the inter process communication queue
  462. storing the file name of the image
  463. """
  464. maps = []
  465. masks = []
  466. for cmd in cmdList:
  467. maps.append(GetFileFromCmd(tempDir, cmd, region))
  468. masks.append(GetFileFromCmd(tempDir, cmd, region, 'pgm'))
  469. filename = GetFileFromCmds(tempDir, cmdList, region)
  470. # Set the environment variables for this process
  471. _setEnvironment(imageWidth, imageHeight, filename,
  472. transparent=False, bgcolor=bgcolor)
  473. opacities = [str(op) for op in opacities]
  474. bgcolor = ':'.join([str(part) for part in bgcolor])
  475. returncode, stdout, messages = read2_command('g.pnmcomp',
  476. overwrite=True,
  477. input='%s' % ",".join(reversed(maps)),
  478. mask='%s' % ",".join(reversed(masks)),
  479. opacity='%s' % ",".join(reversed(opacities)),
  480. bgcolor=bgcolor,
  481. width=imageWidth,
  482. height=imageHeight,
  483. output=filename)
  484. if returncode != 0:
  485. gcore.warning("Rendering composite failed:\n" + messages)
  486. fileQueue.put(None)
  487. os.remove(filename)
  488. return
  489. fileQueue.put(filename)
  490. class DictRefCounter:
  491. """!Base class storing map files/bitmaps (emulates dictionary).
  492. Counts the references to know which files/bitmaps to delete."""
  493. def __init__(self):
  494. self.dictionary = {}
  495. self.referenceCount = {}
  496. def __getitem__(self, key):
  497. return self.dictionary[key]
  498. def __setitem__(self, key, value):
  499. self.dictionary[key] = value
  500. if key not in self.referenceCount:
  501. self.referenceCount[key] = 1
  502. else:
  503. self.referenceCount[key] += 1
  504. Debug.msg(5, 'DictRefCounter.__setitem__: +1 for key {k}'.format(k=key))
  505. def __contains__(self, key):
  506. return key in self.dictionary
  507. def __delitem__(self, key):
  508. self.referenceCount[key] -= 1
  509. Debug.msg(5, 'DictRefCounter.__delitem__: -1 for key {k}'.format(k=key))
  510. def keys(self):
  511. return self.dictionary.keys()
  512. def Clear(self):
  513. """!Clears items which are not needed any more."""
  514. Debug.msg(4, 'DictRefCounter.Clear')
  515. for key in self.dictionary.keys():
  516. if key is not None:
  517. if self.referenceCount[key] <= 0:
  518. del self.dictionary[key]
  519. del self.referenceCount[key]
  520. class MapFilesPool(DictRefCounter):
  521. """!Stores rendered images as files."""
  522. def __init__(self):
  523. DictRefCounter.__init__(self)
  524. self.size = {}
  525. def SetSize(self, key, size):
  526. self.size[key] = size
  527. def GetSize(self, key):
  528. return self.size[key]
  529. def Clear(self):
  530. """!Removes files which are not needed anymore.
  531. Removes both ppm and pgm.
  532. """
  533. Debug.msg(4, 'MapFilesPool.Clear')
  534. for key in self.dictionary.keys():
  535. if self.referenceCount[key] <= 0:
  536. name, ext = os.path.splitext(self.dictionary[key])
  537. os.remove(self.dictionary[key])
  538. if ext == '.ppm':
  539. os.remove(name + '.pgm')
  540. del self.dictionary[key]
  541. del self.referenceCount[key]
  542. del self.size[key]
  543. class BitmapPool(DictRefCounter):
  544. """!Class storing bitmaps (emulates dictionary)"""
  545. def __init__(self):
  546. DictRefCounter.__init__(self)
  547. class CleanUp:
  548. """!Responsible for cleaning up the files."""
  549. def __init__(self, tempDir):
  550. self._tempDir = tempDir
  551. def __call__(self):
  552. import shutil
  553. if os.path.exists(self._tempDir):
  554. try:
  555. shutil.rmtree(self._tempDir)
  556. Debug.msg(5, 'CleanUp: removed directory {t}'.format(t=self._tempDir))
  557. except OSError:
  558. gcore.warning(_("Directory {t} not removed.").format(t=self._tempDir))
  559. def _setEnvironment(width, height, filename, transparent, bgcolor):
  560. """!Sets environmental variables for 2D rendering.
  561. @param width rendering width
  562. @param height rendering height
  563. @param filename file name
  564. @param transparent use transparency
  565. @param bgcolor background color as a tuple of 3 values 0 to 255
  566. """
  567. Debug.msg(5, "_setEnvironment: width={w}, height={h}, "
  568. "filename={f}, transparent={t}, bgcolor={b}".format(w=width,
  569. h=height,
  570. f=filename,
  571. t=transparent,
  572. b=bgcolor))
  573. os.environ['GRASS_WIDTH'] = str(width)
  574. os.environ['GRASS_HEIGHT'] = str(height)
  575. driver = UserSettings.Get(group='display', key='driver', subkey='type')
  576. os.environ['GRASS_RENDER_IMMEDIATE'] = driver
  577. os.environ['GRASS_BACKGROUNDCOLOR'] = '{r}{g}{b}'.format(r=bgcolor[0],
  578. g=bgcolor[1],
  579. b=bgcolor[2])
  580. os.environ['GRASS_TRUECOLOR'] = "TRUE"
  581. if transparent:
  582. os.environ['GRASS_TRANSPARENT'] = "TRUE"
  583. else:
  584. os.environ['GRASS_TRANSPARENT'] = "FALSE"
  585. os.environ['GRASS_PNGFILE'] = str(filename)
  586. def createNoDataBitmap(imageWidth, imageHeight, text="No data"):
  587. """!Creates 'no data' bitmap.
  588. Used when requested bitmap is not available (loading data was not successful) or
  589. we want to show 'no data' bitmap.
  590. @param imageWidth image width
  591. @param imageHeight image height
  592. """
  593. Debug.msg(4, "createNoDataBitmap: w={w}, h={h}, text={t}".format(w=imageWidth,
  594. h=imageHeight,
  595. t=text))
  596. bitmap = wx.EmptyBitmap(imageWidth, imageHeight)
  597. dc = wx.MemoryDC()
  598. dc.SelectObject(bitmap)
  599. dc.Clear()
  600. text = _(text)
  601. dc.SetFont(wx.Font(pointSize=40, family=wx.FONTFAMILY_SCRIPT,
  602. style=wx.FONTSTYLE_NORMAL, weight=wx.FONTWEIGHT_BOLD))
  603. tw, th = dc.GetTextExtent(text)
  604. dc.DrawText(text, (imageWidth - tw) / 2, (imageHeight - th) / 2)
  605. dc.SelectObject(wx.NullBitmap)
  606. return bitmap
  607. def read2_command(*args, **kwargs):
  608. kwargs['stdout'] = gcore.PIPE
  609. kwargs['stderr'] = gcore.PIPE
  610. ps = gcore.start_command(*args, **kwargs)
  611. stdout, stderr = ps.communicate()
  612. return ps.returncode, stdout, stderr
  613. def test():
  614. import shutil
  615. from core.layerlist import LayerList, Layer
  616. from animation.data import AnimLayer
  617. from animation.utils import layerListToCmdsMatrix
  618. import grass.temporal as tgis
  619. tgis.init()
  620. layerList = LayerList()
  621. layer = AnimLayer()
  622. layer.mapType = 'strds'
  623. layer.name = 'JR'
  624. layer.cmd = ['d.rast', 'map=elev_2007_1m']
  625. layerList.AddLayer(layer)
  626. layer = Layer()
  627. layer.mapType = 'vect'
  628. layer.name = 'buildings_2009_approx'
  629. layer.cmd = ['d.vect', 'map=buildings_2009_approx',
  630. 'color=grey']
  631. layer.opacity = 50
  632. layerList.AddLayer(layer)
  633. bPool = BitmapPool()
  634. mapFilesPool = MapFilesPool()
  635. tempDir = '/tmp/test'
  636. if os.path.exists(tempDir):
  637. shutil.rmtree(tempDir)
  638. os.mkdir(tempDir)
  639. # comment this line to keep the directory after prgm ends
  640. # cleanUp = CleanUp(tempDir)
  641. # import atexit
  642. # atexit.register(cleanUp)
  643. prov = BitmapProvider(bPool, mapFilesPool, tempDir,
  644. imageWidth=640, imageHeight=480)
  645. prov.renderingStarted.connect(
  646. lambda count: sys.stdout.write("Total number of maps: {c}\n".format(c=count)))
  647. prov.renderingContinues.connect(
  648. lambda current, text: sys.stdout.write("Current number: {c}\n".format(c=current)))
  649. prov.compositionStarted.connect(
  650. lambda count: sys.stdout.write("Composition: total number of maps: {c}\n".format(c=count)))
  651. prov.compositionContinues.connect(
  652. lambda current, text: sys.stdout.write("Composition: Current number: {c}\n".format(c=current)))
  653. prov.mapsLoaded.connect(
  654. lambda: sys.stdout.write("Maps loading finished\n"))
  655. cmdMatrix = layerListToCmdsMatrix(layerList)
  656. prov.SetCmds(cmdMatrix, [l.opacity for l in layerList])
  657. app = wx.App()
  658. prov.Load(bgcolor=(13, 156, 230), nprocs=4)
  659. for key in bPool.keys():
  660. if key is not None:
  661. bPool[key].SaveFile(os.path.join(tempDir, key + '.png'), wx.BITMAP_TYPE_PNG)
  662. # prov.Unload()
  663. # prov.SetCmds(cmdMatrix, [l.opacity for l in layerList])
  664. # prov.Load(bgcolor=(13, 156, 230))
  665. # prov.Unload()
  666. # newList = LayerList()
  667. # prov.SetCmds(layerListToCmdsMatrix(newList), [l.opacity for l in newList])
  668. # prov.Load()
  669. # prov.Unload()
  670. # mapFilesPool.Clear()
  671. # bPool.Clear()
  672. # print bPool.keys(), mapFilesPool.keys()
  673. if __name__ == '__main__':
  674. test()