provider.py 31 KB

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