build_assets.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. """Slice the generated sheet and register the independent DeepSeek character.
  2. Only packaging operations (crop, uniform resize and PNG encoding) are performed;
  3. the poses and animation artwork come from the image generation tool.
  4. """
  5. import hashlib
  6. from copy import deepcopy
  7. import json
  8. from pathlib import Path
  9. import numpy as np
  10. from PIL import Image, ImageDraw
  11. ROOT = Path(__file__).resolve().parents[2]
  12. HERE = Path(__file__).resolve().parent
  13. PREFIX = 'deepseek_bluewhale'
  14. CHARACTER = 'CharacterDeepseekBlueWhale'
  15. HERO = 'DeepseekBlueWhale'
  16. DIRECTIONS = ('R', 'U', 'L', 'D')
  17. def write_json(path, value):
  18. path.parent.mkdir(parents=True, exist_ok=True)
  19. path.write_text(json.dumps(value, ensure_ascii=False, indent=4) + '\n', encoding='utf-8')
  20. def main():
  21. sheet = Image.open(HERE / 'source_sheet.png').convert('RGBA')
  22. alpha = np.asarray(sheet)[:, :, 3]
  23. width, height = sheet.size
  24. row_edges = [0]
  25. for row in range(1, 4):
  26. expected = round(height * row / 4)
  27. low, high = max(0, expected - 18), min(height, expected + 18)
  28. row_edges.append(low + int(np.argmin((alpha[low:high] > 64).sum(axis=1))))
  29. row_edges.append(height)
  30. cells = []
  31. for row in range(4):
  32. y0, y1 = row_edges[row:row + 2]
  33. column_edges = [0]
  34. for column in range(1, 7):
  35. expected = round(width * column / 7)
  36. low, high = max(0, expected - 18), min(width, expected + 18)
  37. projection = (alpha[y0:y1, low:high] > 64).sum(axis=0)
  38. column_edges.append(low + int(np.argmin(projection)))
  39. column_edges.append(width)
  40. poses = []
  41. for col in range(7):
  42. cell = sheet.crop((column_edges[col], y0, column_edges[col + 1], y1))
  43. bounds = cell.getchannel('A').point(lambda value: 255 if value > 64 else 0).getbbox()
  44. if bounds is None:
  45. raise ValueError(f'Empty sprite at {row}, {col}')
  46. poses.append(cell.crop(bounds))
  47. cells.append(poses)
  48. # One uniform scale for all 28 poses; do not independently stretch each pose.
  49. scale = min(58 / max(im.height for row in cells for im in row),
  50. 60 / max(im.width for row in cells for im in row))
  51. output = ROOT / 'res/img/cloth'
  52. character_path = ROOT / f'game/frame/character/{CHARACTER}.json'
  53. hero_path = ROOT / f'game/hero/{HERO}.json'
  54. if character_path.exists() or hero_path.exists() or list(output.glob(PREFIX + '_*.png')):
  55. raise FileExistsError('Character already exists; do not overwrite edited game assets.')
  56. assets, textures = [], []
  57. for row, direction in enumerate(DIRECTIONS):
  58. poses = []
  59. for col, image in enumerate(cells[row]):
  60. resized = image.resize((round(image.width * scale), round(image.height * scale)), Image.Resampling.LANCZOS)
  61. canvas = Image.new('RGBA', (64, 64))
  62. canvas.alpha_composite(resized, ((64 - resized.width) // 2, 60 - resized.height))
  63. motion, frame = ('stand', 0) if col == 0 else ('walk', col - 1)
  64. filename = f'{PREFIX}_{motion}_{row}_{frame}.png'
  65. canvas.save(output / filename)
  66. assets.append({'path': str((output / filename).relative_to(ROOT)),
  67. 'direction': direction, 'motion': motion, 'frame': frame,
  68. 'size': [64, 64], 'visible_bounds': canvas.getbbox(),
  69. 'sha256': hashlib.sha256((output / filename).read_bytes()).hexdigest()})
  70. poses.append(canvas)
  71. textures.append(poses)
  72. data = {'NAME': CHARACTER, 'HEAD_POS': [-17, -1]}
  73. for index, direction in enumerate(DIRECTIONS):
  74. for standing in (True, False):
  75. motion, count = ('stand', 1) if standing else ('walk', 6)
  76. data[('STAND_' if standing else '') + direction] = {
  77. 'Len': count, 'Cx': -32, 'Cy': -53,
  78. 'Cloth': {'IMG': [f'{PREFIX}_{motion}_{index}_{frame}.png' for frame in range(count)],
  79. 'CX': [0] * count, 'CY': [0] * count}}
  80. # Reuse the front standing image as a safe defeat-state fallback.
  81. data['LOSE'] = deepcopy(data['STAND_D'])
  82. data['INTERVAL'] = 100
  83. write_json(character_path, data)
  84. hero = json.loads((ROOT / 'game/hero/Cola.json').read_text(encoding='utf-8-sig'))
  85. hero.update(name=HERO, character=CHARACTER, icon_img='icon_deepseek_bluewhale')
  86. hero['decorations']['bomb_skin'] = 'bomb1'
  87. write_json(hero_path, hero)
  88. icon = textures[3][0].crop(textures[3][0].getbbox())
  89. icon.thumbnail((53, 53), Image.Resampling.LANCZOS)
  90. icon_canvas = Image.new('RGBA', (55, 55))
  91. icon_canvas.alpha_composite(icon, ((55 - icon.width) // 2, 55 - icon.height))
  92. icon_canvas.save(ROOT / 'res/img/ui/game/icon_deepseek_bluewhale.png')
  93. # Enlarged contact sheet and a 40 px grid animation for reviewing the result.
  94. contact = Image.new('RGB', (7 * 168, 4 * 216), '#edf3f8')
  95. draw = ImageDraw.Draw(contact)
  96. for row in range(4):
  97. for col in range(7):
  98. x, y = col * 168, row * 216
  99. contact.paste(textures[row][col].resize((160, 160), Image.Resampling.NEAREST),
  100. (x + 4, y + 24), textures[row][col].resize((160, 160), Image.Resampling.NEAREST))
  101. draw.text((x + 8, y + 190), DIRECTIONS[row] + (' stand' if col == 0 else f' walk {col - 1}'), fill='#203349')
  102. contact.save(HERE / 'contact_sheet.png')
  103. sequence = []
  104. for frame in range(6):
  105. scene = Image.new('RGB', (400, 180), '#263447')
  106. draw = ImageDraw.Draw(scene)
  107. for gx in range(0, 401, 40):
  108. draw.line((gx, 0, gx, 180), fill='#526174')
  109. for gy in range(0, 181, 40):
  110. draw.line((0, gy, 400, gy), fill='#526174')
  111. for row in range(4):
  112. sprite = textures[row][frame + 1]
  113. scene.paste(sprite, (28 + row * 96, 47), sprite)
  114. draw.text((44 + row * 96, 130), DIRECTIONS[row], fill='white')
  115. sequence.append(scene.resize((800, 360), Image.Resampling.NEAREST))
  116. sequence[0].save(HERE / 'walk_preview.gif', save_all=True, append_images=sequence[1:], duration=100, loop=0)
  117. write_json(HERE / 'asset_manifest.json', {'hero': HERO, 'character': CHARACTER,
  118. 'source_sheet': 'source_sheet.png', 'source_size': list(sheet.size), 'row_edges': row_edges,
  119. 'uniform_scale': scale, 'canvas': [64, 64], 'foot_baseline': 60,
  120. 'character_offset': [-32, -53], 'assets': assets})
  121. print(f'Created {len(assets)} frames, character JSON, hero JSON, icon and previews.')
  122. if __name__ == '__main__':
  123. main()