diff --git a/ssatk/plots/_sphere_raster.py b/ssatk/plots/_sphere_raster.py index 723955c..1556db4 100644 --- a/ssatk/plots/_sphere_raster.py +++ b/ssatk/plots/_sphere_raster.py @@ -44,6 +44,8 @@ def __init__(self, ax, texture, *, zorder=10): self.set_zorder(zorder) ax.add_artist(self) self.set_clip_path(ax.patch) + self._view_geometry_key = None + self._view_geometry = None def set_surface(self, center, radius, rotation, sun_hat, ambient, diffuse): self.center = np.asarray(center, dtype=float) @@ -60,28 +62,53 @@ def draw(self, renderer): ax = self.axes matrix = ax.get_proj() - corners = np.array(np.meshgrid(*[[-1., 1.]]*3)).reshape(3, -1).T - corners = self.center+self.radius*corners - projected = np.column_stack((corners, np.ones(8))) @ matrix.T bounds = np.array([[ax.bbox.x0, ax.bbox.y0], [ax.bbox.x1, ax.bbox.y1]]) - # A box entirely in front of the camera bounds the projected sphere. - if np.all(projected[:, 3] > 0): - pixels = ax.transData.transform(projected[:, :2]/projected[:, 3, None]) - bounds[0] = np.maximum(bounds[0], pixels.min(axis=0)-1) - bounds[1] = np.minimum(bounds[1], pixels.max(axis=0)+1) - lower = np.floor(bounds[0]).astype(int) - upper = np.ceil(bounds[1]).astype(int) scale = renderer.get_image_magnification() - width, height = np.ceil((upper-lower)*scale).astype(int) - if width < 2 or height < 2: + data_transform = ax.transData + cacheable_transform = data_transform.is_affine + data_transform_key = ( + data_transform.get_affine().get_matrix().tobytes() + if cacheable_transform else None + ) + key = ( + matrix.shape, matrix.tobytes(), tuple(bounds.ravel()), float(scale), + data_transform_key, tuple(self.center), float(self.radius), + ) + # A nonlinear transform has no compact, exact fingerprint here. Never + # reuse geometry for it rather than approximating its state by probes. + if not cacheable_transform or key != self._view_geometry_key: + corners = np.array(np.meshgrid(*[[-1., 1.]]*3)).reshape(3, -1).T + corners = self.center+self.radius*corners + projected = np.column_stack((corners, np.ones(8))) @ matrix.T + # A box entirely in front of the camera bounds the projected sphere. + if np.all(projected[:, 3] > 0): + pixels = data_transform.transform(projected[:, :2]/projected[:, 3, None]) + bounds[0] = np.maximum(bounds[0], pixels.min(axis=0)-1) + bounds[1] = np.minimum(bounds[1], pixels.max(axis=0)+1) + lower = np.floor(bounds[0]).astype(int) + upper = np.ceil(bounds[1]).astype(int) + width, height = np.ceil((upper-lower)*scale).astype(int) + if width < 2 or height < 2: + self._view_geometry = None + else: + x, y = np.meshgrid(lower[0]+(np.arange(width)+.5)/scale, + lower[1]+(np.arange(height)+.5)/scale) + xy = data_transform.inverted().transform( + np.column_stack((x.ravel(), y.ravel())) + ) + clip = np.column_stack((xy, -np.ones(len(xy)), np.ones(len(xy)))) + world = clip @ np.linalg.inv(matrix).T + points = (world[:, :3]/world[:, 3, None]).reshape(height, width, 3) + camera = _camera(ax, None) + hits, clearance = sphere_intersections( + points, self.center, self.radius, **camera + ) + self._view_geometry = (lower, points, hits, clearance, camera) + self._view_geometry_key = key if cacheable_transform else None + if self._view_geometry is None: return - x, y = np.meshgrid(lower[0]+(np.arange(width)+.5)/scale, - lower[1]+(np.arange(height)+.5)/scale) - xy = ax.transData.inverted().transform(np.column_stack((x.ravel(), y.ravel()))) - clip = np.column_stack((xy, -np.ones(len(xy)), np.ones(len(xy)))) - world = clip @ np.linalg.inv(matrix).T - points = (world[:, :3]/world[:, 3, None]).reshape(height, width, 3) - hits, clearance = sphere_intersections(points, self.center, self.radius, **_camera(ax, None)) + lower, points, hits, clearance, camera = self._view_geometry + height, width = clearance.shape # Linear coverage over the boundary pixel avoids a jagged silhouette. dy, dx = np.gradient(clearance) footprint = np.maximum(np.hypot(dx, dy), np.finfo(float).eps*self.radius) diff --git a/ssatk/plots/coverage_analysis.py b/ssatk/plots/coverage_analysis.py index 594b100..199c06e 100644 --- a/ssatk/plots/coverage_analysis.py +++ b/ssatk/plots/coverage_analysis.py @@ -1460,8 +1460,9 @@ def compute_eclipse(r, r_sun): def compute_sun_positions(t): + """Return SunPosition samples as an ``(N, 3)`` array, including empty input.""" sun = SunPosition() - return np.array([sun(ti) for ti in t]) + return np.asarray(sun(t)).T # ═════════════════════════════════════════════════════════════════════════════ diff --git a/ssatk/plots/eclipse_cinematic_light_3d.py b/ssatk/plots/eclipse_cinematic_light_3d.py index 2b1e086..9a63777 100644 --- a/ssatk/plots/eclipse_cinematic_light_3d.py +++ b/ssatk/plots/eclipse_cinematic_light_3d.py @@ -152,8 +152,10 @@ def _definition(kind: str | ReferenceDefinition | ReferenceEvent) -> ReferenceDe return SOLAR_2024 if str(kind).lower().startswith("solar") else LUNAR_2025 -def _texture_uri(path: Path, *, max_width: int, quality: int = 90) -> tuple[str, dict[str, object]]: - """Embed a texture as an in-memory WebP derivative of the installed PNG/JPEG.""" +@lru_cache(maxsize=8) +def _texture_uri_cached(path: str, modified_ns: int, size: int, max_width: int, + quality: int) -> tuple[str, dict[str, object]]: + """Build one immutable cache entry for a source texture revision.""" from PIL import Image with Image.open(path) as image: @@ -168,6 +170,18 @@ def _texture_uri(path: Path, *, max_width: int, quality: int = 90) -> tuple[str, return uri, {"source_name": Path(path).name, "embedded_bytes": len(buffer.getvalue())} +def _texture_uri(path: Path, *, max_width: int, quality: int = 90) -> tuple[str, dict[str, object]]: + """Embed a texture, reusing only an unchanged source/option combination.""" + path = Path(path).expanduser().resolve() + stat = path.stat() + uri, metadata = _texture_uri_cached( + str(path), int(stat.st_mtime_ns), int(stat.st_size), + int(max_width), int(quality), + ) + # Callers may annotate their copy without corrupting future cache hits. + return uri, dict(metadata) + + def _rotation_rows_itrf_to_scene(state: PublicPeakState) -> np.ndarray: """Column-vector rotation matrix from the event-owned ITRF to scene.""" gcrf_rows = np.asarray( diff --git a/ssatk/plots/eclipse_space_view_plotly.py b/ssatk/plots/eclipse_space_view_plotly.py index bbe6dfb..88458ec 100644 --- a/ssatk/plots/eclipse_space_view_plotly.py +++ b/ssatk/plots/eclipse_space_view_plotly.py @@ -2055,6 +2055,8 @@ def plot_space_view_animated(mode="lunar", search_days=None, n_frames=26, since this rebuilds full Earth+Moon meshes per frame — n_frames=28 at full 180x360 resolution would be quite slow to generate. """ + if n_frames < 1: + raise ValueError("n_frames must be at least 1") assert mode in ("lunar", "solar") window = _eclipse_window(mode, search_days=search_days, event=event, n_steps=4000, verbose=verbose) t_fine = window["t_s"] diff --git a/ssatk/plots/layers.py b/ssatk/plots/layers.py index 53ae7f1..76ef316 100644 --- a/ssatk/plots/layers.py +++ b/ssatk/plots/layers.py @@ -525,7 +525,8 @@ def add_to_plotly(self, fig, orbit_state, traj=None, satellite=None, **kw): verts_x = X.ravel(); verts_y = Y.ravel(); verts_z = Z.ravel() H, W = self.n_lat, self.n_lon i_idx, j_idx, k_idx = [], [], [] - cols = [] + cols = np.empty(2 * (H - 1) * (W - 1), dtype=object) + face = 0 for r in range(H - 1): for c in range(W - 1): v0 = r*W + c; v1 = v0+1; v2 = (r+1)*W + c; v3 = v2+1 @@ -536,11 +537,12 @@ def add_to_plotly(self, fig, orbit_state, traj=None, satellite=None, **kw): col = f"rgb({pixel[0]},{pixel[1]},{pixel[2]})" for tri in [(v0,v1,v2),(v1,v3,v2)]: i_idx.append(tri[0]); j_idx.append(tri[1]); k_idx.append(tri[2]) - cols.append(col) + cols[face] = col + face += 1 fig.add_trace(go.Mesh3d( x=verts_x, y=verts_y, z=verts_z, i=i_idx, j=j_idx, k=k_idx, - facecolor=cols, + facecolor=np.asarray(cols), name="Earth", hoverinfo="skip", showlegend=False, )) else: