asset_library.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. """Background asset decoding; all Pygame surfaces stay on the UI thread."""
  2. import json
  3. import re
  4. from pathlib import Path
  5. from runtime_paths import PROJECT_ROOT
  6. from concurrent.futures import ThreadPoolExecutor
  7. from PIL import Image
  8. import pygame
  9. from const.window import WINDOW_W, WINDOW_H, TOOL_PANEL_WIDTH
  10. from game.frame import floor, obstacle
  11. from game.frame.frame import Frame
  12. def scan(root, library):
  13. directory = root / 'res/img/mapElem' / library
  14. entries = []
  15. for path in directory.iterdir():
  16. match = re.fullmatch(r'(elem\d+)(\.png|_stand_0_0\.png)', path.name, re.I)
  17. if not match:
  18. continue
  19. name, suffix = match.groups()
  20. kind = 'floor' if suffix.lower() == '.png' else 'obstacle'
  21. registration = None
  22. if kind == 'obstacle':
  23. registration = next((root / 'game/frame' / folder / library / (name+'.json')
  24. for folder in ('obstacle', 'obstacles')
  25. if (root / 'game/frame' / folder / library / (name+'.json')).is_file()), None)
  26. if registration is None:
  27. continue
  28. entries.append(dict(type=library, name=name, elem_type=kind, path=path, registration=registration))
  29. return sorted(entries, key=lambda n: (int(n['name'][4:]), n['elem_type']))
  30. def decode(root, entry, full=False):
  31. entry = dict(entry)
  32. path = entry['path']
  33. width = height = 1
  34. cx = cy = 0
  35. if entry['registration']:
  36. config = json.loads(entry['registration'].read_text(encoding='utf-8-sig'))
  37. width, height = config['WIDTH'], config['HEIGHT']
  38. if not isinstance(width, int) or not isinstance(height, int) or width < 1 or height < 1:
  39. raise ValueError('无效占地尺寸')
  40. stand = config['STAND']
  41. path = root / 'res/img/mapElem' / config['TYPE'] / stand['IMG'][0]
  42. cx, cy = stand['CX'][0], stand['CY'][0]
  43. with Image.open(path) as source:
  44. img = source.convert('RGBA')
  45. entry.update(width=width, height=height, cx=cx, cy=cy)
  46. if full:
  47. return entry, img.size, img.tobytes()
  48. # Fit the sprite and its offset relative to the occupied cells together.
  49. left, top = min(0, cx), min(0, cy)
  50. right, bottom = max(width*40, cx+img.width), max(height*40, cy+img.height)
  51. scale = min(1, 112/(right-left), 88/(bottom-top))
  52. size = (max(1, round(img.width*scale)), max(1, round(img.height*scale)))
  53. img = img.resize(size, Image.Resampling.LANCZOS if hasattr(Image, 'Resampling') else Image.LANCZOS)
  54. thumb = Image.new('RGBA', (112, 88))
  55. thumb.alpha_composite(img, (round((112-(right-left)*scale)/2+(cx-left)*scale),
  56. round((88-(bottom-top)*scale)/2+(cy-top)*scale)))
  57. return entry, thumb.size, thumb.tobytes()
  58. class AssetLibrary:
  59. def __init__(self, app):
  60. self.app = app
  61. self.root = PROJECT_ROOT
  62. self.pool = ThreadPoolExecutor(max_workers=4, thread_name_prefix='map-assets')
  63. self.visible = False
  64. self.libraries = []
  65. self.directory_job = self.pool.submit(lambda: sorted(p.name for p in (self.root/'res/img/mapElem').iterdir() if p.is_dir()))
  66. self.scan_job = None
  67. self.jobs = {}
  68. self.pending = []
  69. self.entries = []
  70. self.selected_job = None
  71. self.library = None
  72. self.dropdown = False
  73. self.folder_offset = self.offset = self.failed = 0
  74. self.header = pygame.Rect(WINDOW_W+12, 44, TOOL_PANEL_WIDTH-24, 32)
  75. self.button = pygame.Rect(616, 2, 86, 28)
  76. def toggle(self):
  77. self.visible = not self.visible
  78. if not self.visible and self.selected_job:
  79. self.selected_job.cancel()
  80. self.selected_job = None
  81. self.app.menu.active = None
  82. self.app.menu.block_pointer = True
  83. self.app.settings.focus = None
  84. pygame.key.stop_text_input()
  85. if self.visible:
  86. self.app.tools.visible = True
  87. self.app.tools.regions.finish_drag()
  88. self.app.tools.choose('paint')
  89. self.app.tools.regions.enabled = False
  90. def choose_library(self, name):
  91. for job in self.jobs:
  92. job.cancel()
  93. if self.selected_job:
  94. self.selected_job.cancel()
  95. self.selected_job = None
  96. self.jobs.clear()
  97. self.pending = []
  98. self.entries = []
  99. self.offset = self.failed = 0
  100. self.library = name
  101. self.dropdown = False
  102. self.scan_job = self.pool.submit(scan, self.root, name)
  103. def update(self):
  104. if self.directory_job and self.directory_job.done():
  105. try:
  106. self.libraries = self.directory_job.result()
  107. except Exception as error:
  108. self.app.menu.notify('素材目录读取失败:'+str(error))
  109. self.directory_job = None
  110. if self.visible and self.library is None and self.libraries:
  111. self.choose_library(self.libraries[0])
  112. if self.scan_job and self.scan_job.done():
  113. try:
  114. self.pending = self.scan_job.result()
  115. except Exception as error:
  116. self.app.menu.notify('素材扫描失败:'+str(error))
  117. self.scan_job = None
  118. for job in list(self.jobs):
  119. if job.done():
  120. del self.jobs[job]
  121. try:
  122. entry, size, pixels = job.result()
  123. entry['thumbnail'] = pygame.image.fromstring(pixels, size, 'RGBA').convert_alpha()
  124. self.entries.append(entry)
  125. except Exception:
  126. self.failed += 1
  127. self.entries.sort(key=lambda n: (int(n['name'][4:]), n['elem_type']))
  128. while self.pending and len(self.jobs) < 8:
  129. entry = self.pending.pop(0)
  130. self.jobs[self.pool.submit(decode, self.root, entry)] = True
  131. if self.selected_job and self.selected_job.done() and not self.app.placement.active:
  132. job, self.selected_job = self.selected_job, None
  133. try:
  134. entry, size, pixels = job.result()
  135. img = pygame.image.fromstring(pixels, size, 'RGBA').convert_alpha()
  136. kind, library, name = entry['elem_type'], entry['type'], entry['name']
  137. if kind == 'floor':
  138. floor.floors.setdefault(library, {})[name] = img
  139. else:
  140. obstacle.obstacles.setdefault(library, {})[name] = dict(TYPE=library, NAME=name,
  141. WIDTH=entry['width'], HEIGHT=entry['height'], STAND=[Frame(img, entry['cx'], entry['cy'])])
  142. self.app.show_obstacle = True
  143. self.app.tools.choose('paint')
  144. self.app.current_elem = dict(elem_type=kind, type=library, name=name)
  145. selection = self.app.selection
  146. selection.group = [dict(layer=kind, type=library, name=name, x=0, y=0)]
  147. selection.clipboard_text = selection.read_clipboard()
  148. self.app.redraw_floor_obstacle_trigger = True
  149. self.app.menu.notify('已选择 '+library+'/'+name+';左键放置')
  150. except Exception as error:
  151. self.app.menu.notify('素材读取失败:'+str(error))
  152. def handle_event(self, event):
  153. if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1 and self.button.collidepoint(event.pos):
  154. self.toggle()
  155. return True
  156. if not self.visible:
  157. return False
  158. pos = getattr(event, 'pos', pygame.mouse.get_pos())
  159. if pos[0] < WINDOW_W:
  160. if event.type == pygame.MOUSEBUTTONDOWN:
  161. self.dropdown = False
  162. return False
  163. if event.type == pygame.MOUSEBUTTONDOWN:
  164. self.app.menu.block_pointer = True
  165. if event.button in (4, 5):
  166. self.scroll(-1 if event.button == 4 else 1)
  167. elif event.button == 1:
  168. if self.header.collidepoint(pos):
  169. self.dropdown = not self.dropdown
  170. elif self.dropdown:
  171. index = (pos[1]-80)//30 + self.folder_offset
  172. if 80 <= pos[1] < 80+min(18, len(self.libraries)-self.folder_offset)*30 and 0 <= index < len(self.libraries):
  173. self.choose_library(self.libraries[index])
  174. else:
  175. self.dropdown = False
  176. elif 112 <= pos[1] < WINDOW_H:
  177. col, row = (pos[0]-WINDOW_W-12)//154, (pos[1]-112)//144
  178. index = (self.offset+row)*3+col
  179. if 0 <= col < 3 and 0 <= row < 5 and 0 <= index < len(self.entries):
  180. if self.selected_job:
  181. self.selected_job.cancel()
  182. self.selected_job = self.pool.submit(decode, self.root, self.entries[index], True)
  183. return True
  184. if event.type == pygame.MOUSEWHEEL:
  185. self.scroll(-event.y)
  186. return event.type in (pygame.MOUSEWHEEL, pygame.MOUSEMOTION, pygame.MOUSEBUTTONUP)
  187. def scroll(self, delta):
  188. if self.dropdown:
  189. self.folder_offset = max(0, min(max(0, len(self.libraries)-18), self.folder_offset+delta))
  190. else:
  191. self.offset = max(0, min(max(0, (len(self.entries)+2)//3-5), self.offset+delta))
  192. def draw_button(self):
  193. screen, font = self.app.screen, self.app.text_font
  194. pygame.draw.rect(screen, (22, 26, 33) if self.visible else (53, 61, 74), self.button)
  195. pygame.draw.rect(screen, (144, 155, 173), self.button, 1)
  196. text = font.render('素材库', True, (237, 240, 245))
  197. screen.blit(text, text.get_rect(center=self.button.center))
  198. def draw(self):
  199. screen, font = self.app.screen, self.app.text_font
  200. pygame.draw.rect(screen, (35, 39, 46), (WINDOW_W, 32, TOOL_PANEL_WIDTH, WINDOW_H-32))
  201. pygame.draw.rect(screen, (144, 155, 173), self.header, 1)
  202. screen.blit(font.render((self.library or '选择素材子库')+' ▼', True, (235, 235, 240)), (self.header.x+8, self.header.y+6))
  203. loading = self.scan_job or self.jobs or self.pending
  204. status = '%d 个素材%s%s' % (len(self.entries), ' · 加载中…' if loading else '', ' · 跳过 %d 个无效素材' % self.failed if self.failed else '')
  205. screen.blit(font.render(status, True, (170, 185, 200)), (WINDOW_W+12, 86))
  206. for i, entry in enumerate(self.entries[self.offset*3:self.offset*3+15]):
  207. rect = pygame.Rect(WINDOW_W+12+(i%3)*154, 112+(i//3)*144, 146, 136)
  208. selected = self.app.current_elem == {k: entry[k] for k in ('elem_type', 'type', 'name')}
  209. pygame.draw.rect(screen, (22, 26, 33) if selected else (52, 59, 70), rect)
  210. pygame.draw.rect(screen, (245, 195, 80) if selected else (120, 135, 150), rect, 2 if selected else 1)
  211. screen.blit(entry['thumbnail'], (rect.x+17, rect.y+4))
  212. label = font.render(entry['name'], True, (235, 238, 245))
  213. screen.blit(label, label.get_rect(center=(rect.centerx, rect.y+104)))
  214. label = font.render('%s %d×%d' % ('地板' if entry['elem_type']=='floor' else '障碍', entry['width'], entry['height']), True, (175, 190, 205))
  215. screen.blit(label, label.get_rect(center=(rect.centerx, rect.y+124)))
  216. rows = (len(self.entries)+2)//3
  217. if rows > 5:
  218. track = pygame.Rect(WINDOW_W+TOOL_PANEL_WIDTH-12, 112, 6, 712)
  219. pygame.draw.rect(screen, (22, 26, 33), track)
  220. height = max(24, round(track.height*5/rows))
  221. pygame.draw.rect(screen, (145, 160, 180), (track.x, track.y+round((track.height-height)*self.offset/(rows-5)), track.width, height))
  222. screen.blit(font.render('滚轮浏览素材 · 再点“素材库”返回工具栏', True, (170, 185, 200)), (WINDOW_W+12, 845))
  223. if self.dropdown:
  224. for i, name in enumerate(self.libraries[self.folder_offset:self.folder_offset+18]):
  225. rect = pygame.Rect(WINDOW_W+12, 80+i*30, TOOL_PANEL_WIDTH-24, 30)
  226. pygame.draw.rect(screen, (65, 77, 93) if name == self.library else (28, 33, 40), rect)
  227. pygame.draw.rect(screen, (110, 125, 140), rect, 1)
  228. screen.blit(font.render(name, True, (235, 235, 240)), (rect.x+8, rect.y+5))
  229. def close(self):
  230. for job in self.jobs:
  231. job.cancel()
  232. self.pool.shutdown(wait=False)