File size: 11,468 Bytes
764e34c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
"""
Module for camera-related functionality in the ARCEngine.
"""

from typing import List, Tuple

import numpy as np

from .interfaces import RenderableUserDisplay
from .sprites import Sprite


class Camera:
    """A camera that defines the viewport into the game world."""

    # Maximum allowed dimensions
    MAX_DIMENSION = 64

    _x: int
    _y: int
    _width: int
    _height: int
    _background: int
    _letter_box: int
    _interfaces: list[RenderableUserDisplay]

    def __init__(
        self,
        x: int = 0,
        y: int = 0,
        width: int = 64,
        height: int = 64,
        background: int = 5,
        letter_box: int = 5,
        interfaces: list[RenderableUserDisplay] = [],
    ):
        """Initialize a new Camera.

        Args:
            x: X coordinate in pixels (default: 0)
            y: Y coordinate in pixels (default: 0)
            width: Viewport width in pixels (default: 64, max: 64)
            height: Viewport height in pixels (default: 64, max: 64)
            background: Background color index (default: 5 - Black)
            letter_box: Letter box color index (default: 5 - Black)
            interfaces: Optional list of renderable interfaces to initialize with

        Raises:
            ValueError: If width or height exceed 64 pixels
        """
        if width > 64 or height > 64 or width < 0 or height < 0:
            raise ValueError("Camera dimensions cannot exceed 64x64 pixels and must be positive")

        self._x = x
        self._y = y
        self.width = width
        self.height = height
        self._background = background
        self._letter_box = letter_box
        self._interfaces: List[RenderableUserDisplay] = []

        if interfaces:
            for interface in interfaces:
                self._interfaces.append(interface)

    @property
    def x(self) -> int:
        """Get the camera's x position.

        Returns:
            int: The camera's x position
        """
        return self._x

    @x.setter
    def x(self, value: int) -> None:
        """Set the camera's x position.

        Args:
            value: The new x position
        """
        self._x = int(value)

    @property
    def y(self) -> int:
        """Get the camera's y position.

        Returns:
            int: The camera's y position
        """
        return self._y

    @y.setter
    def y(self, value: int) -> None:
        """Set the camera's y position.

        Args:
            value: The new y position
        """
        self._y = int(value)

    @property
    def width(self) -> int:
        """Get the camera's width.

        Returns:
            int: The camera's width
        """
        return self._width

    @width.setter
    def width(self, value: int) -> None:
        """Set the camera's width.

        Args:
            value: The new width

        Raises:
            ValueError: If width exceeds MAX_DIMENSION
        """
        width_int = int(value)
        if width_int > self.MAX_DIMENSION:
            raise ValueError(f"Width cannot exceed {self.MAX_DIMENSION} pixels")
        self._width = width_int

    @property
    def height(self) -> int:
        """Get the camera's height.

        Returns:
            int: The camera's height
        """
        return self._height

    @height.setter
    def height(self, value: int) -> None:
        """Set the camera's height.

        Args:
            value: The new height

        Raises:
            ValueError: If height exceeds MAX_DIMENSION
        """
        height_int = int(value)
        if height_int > self.MAX_DIMENSION:
            raise ValueError(f"Height cannot exceed {self.MAX_DIMENSION} pixels")
        self._height = height_int

    @property
    def background(self) -> int:
        """Get the camera's background color."""
        return self._background

    @background.setter
    def background(self, value: int) -> None:
        """Set the camera's background color."""
        self._background = value

    @property
    def letter_box(self) -> int:
        """Get the camera's letter box color."""
        return self._letter_box

    @letter_box.setter
    def letter_box(self, value: int) -> None:
        """Set the camera's letter box color."""
        self._letter_box = value

    def resize(self, width: int, height: int) -> None:
        """Resize the camera.

        Args:
            width: The new width
            height: The new height
        """
        self.width = width
        self.height = height

    def move(self, dx: int, dy: int) -> None:
        """Move the camera by the specified delta.

        Args:
            dx: The change in x position
            dy: The change in y position
        """
        self._x += int(dx)
        self._y += int(dy)

    def _calculate_scale_and_offset(self) -> Tuple[int, int, int]:
        """Calculate the scale factor and offsets for letterboxing.

        Returns:
            Tuple[int, int, int]: (scale, x_offset, y_offset)
            - scale: The uniform scale factor to fit viewport in 64x64
            - x_offset: Horizontal offset for centering
            - y_offset: Vertical offset for centering
        """
        # Calculate maximum possible scale that fits in MAX_DIMENSION
        scale_x = self.MAX_DIMENSION // self._width
        scale_y = self.MAX_DIMENSION // self._height
        scale = min(scale_x, scale_y)

        # Calculate scaled dimensions
        scaled_width = self._width * scale
        scaled_height = self._height * scale

        # Only use offsets if we can't scale up to fill the screen
        x_offset = (self.MAX_DIMENSION - scaled_width) // 2
        y_offset = (self.MAX_DIMENSION - scaled_height) // 2

        return scale, x_offset, y_offset

    def _raw_render(self, sprites: List[Sprite]) -> np.ndarray:
        """Internal method to render the camera view.

        Args:
            sprites: List of sprites to render. Sprites are rendered in order of their layer
                    value (lower layers first). Negative pixel values are treated as transparent.
                    Only visible sprites (based on their interaction mode) will be rendered.

        Returns:
            np.ndarray: The rendered view as a 2D numpy array
        """
        # Create background array filled with background color
        output = np.full((self._height, self._width), self._background, dtype=np.int8)

        if not sprites:
            return output

        # Sort sprites by layer (lower layers first) and filter out non-visible sprites
        sorted_sprites = sorted((s for s in sprites if s.is_visible), key=lambda s: s.layer)

        for sprite in sorted_sprites:
            # Get the sprite's rendered pixels (handles rotation and scaling)
            sprite_pixels = sprite.render()
            sprite_height, sprite_width = sprite_pixels.shape

            # Calculate sprite position relative to camera
            rel_x = sprite.x - self._x
            rel_y = sprite.y - self._y

            # Calculate the intersection with viewport
            dest_x_start = max(0, rel_x)
            dest_x_end = min(self._width, rel_x + sprite_width)
            dest_y_start = max(0, rel_y)
            dest_y_end = min(self._height, rel_y + sprite_height)

            # Skip if sprite is completely outside viewport
            if dest_x_end <= dest_x_start or dest_y_end <= dest_y_start:
                continue

            # Calculate source region from sprite
            sprite_x_start = max(0, -rel_x)
            sprite_x_end = sprite_width - max(0, (rel_x + sprite_width) - self._width)
            sprite_y_start = max(0, -rel_y)
            sprite_y_end = sprite_height - max(0, (rel_y + sprite_height) - self._height)

            # Get the sprite region we're going to copy
            sprite_region = sprite_pixels[sprite_y_start:sprite_y_end, sprite_x_start:sprite_x_end]

            # Create a mask for non-negative (visible) pixels
            visible_mask = sprite_region >= 0

            # Update only the non-transparent pixels
            output[dest_y_start:dest_y_end, dest_x_start:dest_x_end][visible_mask] = sprite_region[visible_mask]

        return output

    def render(self, sprites: List[Sprite]) -> np.ndarray:
        """Render the camera view.

        The rendered output is always 64x64 pixels. If the camera's viewport is smaller,
        the view will be scaled up uniformly (maintaining aspect ratio) to fit within
        64x64, and the remaining space will be filled with the letter_box color.

        Args:
            sprites: List of sprites to render (currently unused)

        Returns:
            np.ndarray: The rendered view as a 64x64 numpy array
        """
        # Start with a letter-boxed canvas
        output = np.full((self.MAX_DIMENSION, self.MAX_DIMENSION), self._letter_box, dtype=np.int8)

        # Get the raw camera view
        view = self._raw_render(sprites)

        # Calculate scaling and offsets
        scale, x_offset, y_offset = self._calculate_scale_and_offset()

        # Scale up the view using numpy's repeat
        if scale > 1:
            view = np.repeat(np.repeat(view, scale, axis=0), scale, axis=1)

        # Insert the scaled view into the letter-boxed output
        output[y_offset : y_offset + view.shape[0], x_offset : x_offset + view.shape[1]] = view

        for interface in self._interfaces:
            output = interface.render_interface(output)

        return output

    def replace_interface(self, new_interfaces: list[RenderableUserDisplay]) -> None:
        """Replace the current interfaces with new ones.

        This method replaces all current interfaces with the provided ones. Each interface
        in the new list will be cloned to prevent external modification.

        Args:
            new_interfaces: List of new interfaces to use.  These should be cloned before passing them in.
        """
        self._interfaces = []
        if new_interfaces:
            for interface in new_interfaces:
                self._interfaces.append(interface)

    def display_to_grid(self, display_x: int, display_y: int) -> tuple[int, int] | None:
        """Convert display coordinates (64x64) to camera grid coordinates.

        This takes into account:
        - Camera scaling max(64/camera_width, 64/camera_height)
        - Letterbox padding
        - Grid boundaries

        Args:
            display_x: X coordinate in display space (0-63)
            display_y: Y coordinate in display space (0-63)

        Returns:
            tuple[int, int] | None: The corresponding grid coordinates (x, y) or None if the display coordinates are within the letterbox
        """
        # Calculate scaling factor
        scale_x = int(64 / self.width)
        scale_y = int(64 / self.height)
        scale = min(scale_x, scale_y)

        # Calculate letterbox padding
        x_padding = int((64 - (self.width * scale)) / 2)
        y_padding = int((64 - (self.height * scale)) / 2)

        # Remove padding and scale down
        grid_x = int((display_x - x_padding) / scale) if display_x - x_padding >= 0 else -1
        grid_y = int((display_y - y_padding) / scale) if display_y - y_padding >= 0 else -1

        if grid_x < 0 or grid_y < 0 or grid_x >= self.width or grid_y >= self.height:
            # Given X, Y is off the camera screen
            return None

        return grid_x + self.x, grid_y + self.y