feat: add snapshot recording
This commit is contained in:
		| @@ -2,12 +2,15 @@ from __future__ import annotations | ||||
|  | ||||
| import struct | ||||
| from dataclasses import dataclass, field | ||||
| from typing import Optional | ||||
| from typing import TYPE_CHECKING, Optional | ||||
|  | ||||
| import numpy as np | ||||
|  | ||||
| from src.vec import Vec | ||||
|  | ||||
| if TYPE_CHECKING: | ||||
|     from src.car import Car | ||||
|  | ||||
|  | ||||
| def iter_unpack(format, data): | ||||
|     nbr_bytes = struct.calcsize(format) | ||||
| @@ -20,7 +23,8 @@ class Snapshot: | ||||
|     position: Vec = field(default_factory=Vec) | ||||
|     direction: Vec = field(default_factory=Vec) | ||||
|     speed: float = 0 | ||||
|     raycast_distances: list[float] | tuple[float, ...] = field(default_factory=list) | ||||
|     raycast_distances: list[float] | tuple[float, ...] = field( | ||||
|         default_factory=list) | ||||
|     image: Optional[np.ndarray] = None | ||||
|  | ||||
|     def pack(self): | ||||
| @@ -36,10 +40,12 @@ class Snapshot: | ||||
|         ) | ||||
|  | ||||
|         nbr_raycasts: int = len(self.raycast_distances) | ||||
|         data += struct.pack(f">B{nbr_raycasts}f", nbr_raycasts, *self.raycast_distances) | ||||
|         data += struct.pack(f">B{nbr_raycasts}f", | ||||
|                             nbr_raycasts, *self.raycast_distances) | ||||
|  | ||||
|         if self.image is not None: | ||||
|             data += struct.pack(">II", self.image.shape[0], self.image.shape[1]) | ||||
|             data += struct.pack(">II", | ||||
|                                 self.image.shape[0], self.image.shape[1]) | ||||
|             data += self.image.tobytes() | ||||
|         else: | ||||
|             data += struct.pack(">II", 0, 0) | ||||
| @@ -72,3 +78,19 @@ class Snapshot: | ||||
|             raycast_distances=raycast_distances, | ||||
|             image=image, | ||||
|         ) | ||||
|  | ||||
|     @staticmethod | ||||
|     def from_car(car: Car) -> Snapshot: | ||||
|         return Snapshot( | ||||
|             controls=( | ||||
|                 car.forward, | ||||
|                 car.backward, | ||||
|                 car.left, | ||||
|                 car.right | ||||
|             ), | ||||
|             position=car.pos.copy(), | ||||
|             direction=car.direction.copy(), | ||||
|             speed=car.speed, | ||||
|             raycast_distances=car.rays.copy(), | ||||
|             image=None | ||||
|         ) | ||||
|   | ||||
		Reference in New Issue
	
	Block a user