provider.py 31 KB

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