painter.py
1.9 kB · python · 44 lines
1import numpy as np2from typing import Dict, List, Optional, TYPE_CHECKING3from mrlypy.core.colors import alpha, black, blue, green, red, white4from mrlypy.core.enums import Mode5from mrlypy.core.state import state67if TYPE_CHECKING:8 from mrlypy.core.colors import Color9 from .models import Cell2d1011def get_mapping():12 return {0: [white], 1: [black], 2: [alpha], 3: [red], 4: [green], 5: [blue]}1314def paint_2d(cell: "Cell2d", mapping: Optional[Dict[int, List["Color"]]] = None, mode: Optional[Mode] = None) -> "Cell2d":15 mapping = mapping or get_mapping()16 mode = mode or Mode.TYPE17 for key, colors in mapping.items():18 mask = cell.types == key19 if not np.any(mask):20 continue21 match mode:22 case Mode.TYPE:23 cell.colors[mask] = colors[0].to_rgba()24 case Mode.RANDOM:25 palette = np.array([c.to_rgba() for c in colors], dtype=np.uint8)26 indices = state.rng.randint(0, len(palette), size=np.sum(mask))27 cell.colors[mask] = palette[indices]28 case Mode.ENUMERATE:29 palette = np.array([c.to_rgba() for c in colors], dtype=np.uint8)30 indices = np.arange(np.sum(mask)) % len(palette)31 cell.colors[mask] = palette[indices]32 case _:33 source_array = {34 Mode.INDEX: np.arange(cell.width * cell.height).reshape(cell.height, cell.width),35 Mode.TAG: cell.tags,36 Mode.ROW: np.indices((cell.height, cell.width))[0],37 Mode.COLUMN: np.indices((cell.height, cell.width))[1],38 }.get(mode)39 if source_array is not None:40 palette = np.array([c.to_rgba() for c in colors], dtype=np.uint8)41 masked_values = source_array[mask]42 indices = masked_values % len(palette)43 cell.colors[mask] = palette[indices]44 return cell