Compare commits

...
2 Commits
Author SHA1 Message Date
rayd1o 4b8feeb87e release: bump version to 0.75.3 2026-09-27 09:30:06 +08:00
rayd1o a2025dbfe0 release: bump version to 0.75.2 2026-09-25 02:03:53 +08:00
68 changed files with 1725 additions and 849 deletions

No files matched your search

+1 -1
View File
@@ -1 +1 @@
0.75.1
0.75.3
+35 -28
View File
@@ -18,7 +18,6 @@ from app.services.business_logs import emit_business_log, exception_context
from app.services.collectors.base import BaseCollector
from app.services.collectors.downloads import DownloadHTTPStatusError, ResumableFileDownloader
logger = get_logger(__name__, service="collector")
ACTIVE_GROUP = "active"
FALLBACK_GROUPS = (
@@ -39,6 +38,7 @@ FALLBACK_GROUPS = (
)
FETCH_RETRY_ATTEMPTS = 3
FETCH_RETRY_BASE_DELAY_SECONDS = 0.8
CELESTRAK_CACHE_TTL_SECONDS = 2 * 60 * 60
CELESTRAK_NOT_UPDATED_MARKER = "GP data has not updated since your last successful"
@@ -51,6 +51,8 @@ class CelesTrakTLECollector(BaseCollector):
_downloader = ResumableFileDownloader(
cache_namespace="celestrak",
default_accept="application/json",
preflight_head=False,
cache_ttl_seconds=CELESTRAK_CACHE_TTL_SECONDS,
)
@property
@@ -195,7 +197,9 @@ class CelesTrakTLECollector(BaseCollector):
if not is_final_attempt:
await asyncio.sleep(FETCH_RETRY_BASE_DELAY_SECONDS * attempt)
raise RuntimeError(f"CelesTrak active satellite download failed after retries: {last_error}")
raise RuntimeError(
f"CelesTrak active satellite download failed after retries: {last_error}"
)
async def _fetch_fallback_groups(
self,
@@ -226,25 +230,25 @@ class CelesTrakTLECollector(BaseCollector):
try:
for group in FALLBACK_GROUPS:
group_url = self._group_url(group)
cached_path = self._downloader.get_cached_file(
group_url,
".json",
validate_existing=self._validate_json_file,
)
if cached_path is not None:
body_path = cached_path
else:
try:
body_path = await self._downloader.download_file(
client,
group_url,
extension=".json",
accept="application/json",
validate_existing=self._validate_json_file,
)
except DownloadHTTPStatusError as exc:
if not self._is_not_updated_response(exc):
raise RuntimeError(f"CelesTrak fallback group '{group}' download failed: {exc}") from exc
try:
body_path = await self._downloader.download_file(
client,
group_url,
extension=".json",
accept="application/json",
validate_existing=self._validate_json_file,
)
except DownloadHTTPStatusError as exc:
if not self._is_not_updated_response(exc):
raise RuntimeError(
f"CelesTrak fallback group '{group}' download failed: {exc}"
) from exc
body_path = self._downloader.get_cached_file(
group_url,
".json",
validate_existing=self._validate_json_file,
)
if body_path is None:
raise RuntimeError(
f"CelesTrak fallback group '{group}' has not updated and no local cached copy is available"
) from exc
@@ -348,13 +352,13 @@ class CelesTrakTLECollector(BaseCollector):
commit=True,
)
@staticmethod
def _validate_json_file(path: Path) -> bool:
@classmethod
def _validate_json_file(cls, path: Path) -> bool:
try:
data = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, UnicodeDecodeError):
cls._load_active_payload(path)
except RuntimeError:
return False
return isinstance(data, list)
return True
async def _log_parse_failure(self, exc: Exception) -> None:
await emit_business_log(
@@ -375,7 +379,8 @@ class CelesTrakTLECollector(BaseCollector):
),
)
def _load_active_payload(self, path: Path) -> List[Dict[str, Any]]:
@staticmethod
def _load_active_payload(path: Path) -> List[Dict[str, Any]]:
try:
raw = json.loads(path.read_text(encoding="utf-8"))
except (OSError, json.JSONDecodeError, UnicodeDecodeError) as exc:
@@ -391,7 +396,9 @@ class CelesTrakTLECollector(BaseCollector):
else:
invalid_count += 1
if invalid_count:
raise RuntimeError(f"CelesTrak active payload contains {invalid_count} invalid record(s)")
raise RuntimeError(
f"CelesTrak active payload contains {invalid_count} invalid record(s)"
)
if not records:
raise RuntimeError("CelesTrak active payload contains no satellite records")
return records
+49 -21
View File
@@ -12,7 +12,6 @@ from typing import Any, Awaitable, Callable
import httpx
ProgressCallback = Callable[[int, int | None], Awaitable[None]]
ValidateCallback = Callable[[Path], bool]
@@ -52,10 +51,14 @@ class ResumableFileDownloader:
user_agent: str = "Planet-Intelligence-System/1.0 (Python/collector)",
default_accept: str = "*/*",
cache_root: Path | None = None,
preflight_head: bool = True,
cache_ttl_seconds: float = 0,
) -> None:
self._cache_dir = (cache_root or default_download_cache_root()) / cache_namespace
self._user_agent = user_agent
self._default_accept = default_accept
self._preflight_head = preflight_head
self._cache_ttl_seconds = cache_ttl_seconds
@staticmethod
def _cache_key(url: str) -> str:
@@ -93,8 +96,9 @@ class ResumableFileDownloader:
if not meta_path.exists():
return {}
try:
return json.loads(meta_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError):
data = json.loads(meta_path.read_text(encoding="utf-8"))
return data if isinstance(data, dict) else {}
except json.JSONDecodeError, OSError:
return {}
@staticmethod
@@ -111,20 +115,25 @@ class ResumableFileDownloader:
return last_modified == str(meta.get("last_modified") or "").strip()
return True
@staticmethod
def _response_info(response: httpx.Response) -> dict[str, Any]:
# httpx yields decoded bytes; encoded Content-Length cannot validate them.
raw_length = response.headers.get("content-length")
encoded = response.headers.get("content-encoding", "identity") != "identity"
return {
"etag": response.headers.get("etag"),
"last_modified": response.headers.get("last-modified"),
"content_length": int(raw_length) if raw_length and not encoded else None,
"accept_ranges": (response.headers.get("accept-ranges") or "").lower(),
}
async def fetch_remote_info(self, client: httpx.AsyncClient, url: str) -> dict[str, Any]:
try:
response = await client.head(url)
if response.status_code >= 400:
return {}
content_length_raw = response.headers.get("content-length")
content_length = int(content_length_raw) if content_length_raw else None
return {
"etag": response.headers.get("etag"),
"last_modified": response.headers.get("last-modified"),
"content_length": content_length,
"accept_ranges": (response.headers.get("accept-ranges") or "").lower(),
}
except (httpx.HTTPError, ValueError):
return self._response_info(response)
except httpx.HTTPError, ValueError:
return {}
async def download_file(
@@ -139,14 +148,24 @@ class ResumableFileDownloader:
) -> Path:
self._cache_dir.mkdir(parents=True, exist_ok=True)
final_path, part_path, meta_path = self._cache_paths(url, extension)
cached_path = self.get_cached_file(url, extension, validate_existing=validate_existing)
if cached_path and 0 <= time.time() - cached_path.stat().st_mtime < self._cache_ttl_seconds:
size = cached_path.stat().st_size
if progress_callback:
await progress_callback(size, size)
return cached_path
meta = self._load_meta(meta_path)
remote = await self.fetch_remote_info(client, url)
remote = await self.fetch_remote_info(client, url) if self._preflight_head else {}
expected_size = remote.get("content_length")
if final_path.exists():
local_size = final_path.stat().st_size
size_match = expected_size is None or local_size == expected_size
if self._validators_match(meta, remote) and size_match:
if (
(remote.get("etag") or remote.get("last_modified"))
and self._validators_match(meta, remote)
and size_match
):
if validate_existing and not validate_existing(final_path):
final_path.unlink(missing_ok=True)
else:
@@ -181,9 +200,13 @@ class ResumableFileDownloader:
headers["If-Range"] = str(remote.get("last_modified"))
async with client.stream("GET", url, headers=headers) as response:
if response.status_code == 304 and final_path.exists():
if progress_callback and expected_size and expected_size > 0:
await progress_callback(expected_size, expected_size)
if response.status_code == 304:
if cached_path is None:
raise RuntimeError(f"Server returned 304 without a valid local cache for {url}")
final_path.touch()
size = final_path.stat().st_size
if progress_callback:
await progress_callback(size, size)
return final_path
if response.status_code >= 400:
body = (await response.aread()).decode("utf-8", errors="replace")
@@ -194,12 +217,16 @@ class ResumableFileDownloader:
else:
mode = "wb"
resume_from = 0
remote = self._response_info(response)
expected_size = remote.get("content_length")
downloaded = resume_from
last_emit_bytes = 0
last_emit_time = time.monotonic()
min_emit_bytes = (
max(expected_size // 150, 512 * 1024) if expected_size and expected_size > 0 else 1024 * 1024
max(expected_size // 150, 512 * 1024)
if expected_size and expected_size > 0
else 1024 * 1024
)
with part_path.open(mode) as f:
@@ -230,6 +257,10 @@ class ResumableFileDownloader:
f"Resumable download incomplete for {url}: expected={expected_size}, got={final_size}"
)
# Never replace the last good payload with an HTML error or invalid JSON.
if validate_existing and not validate_existing(part_path):
part_path.unlink(missing_ok=True)
raise RuntimeError(f"Downloaded file validation failed for {url}")
part_path.replace(final_path)
self._save_meta(
meta_path,
@@ -242,9 +273,6 @@ class ResumableFileDownloader:
},
)
if validate_existing and not validate_existing(final_path):
raise RuntimeError(f"Downloaded file validation failed for {url}")
if progress_callback and expected_size and expected_size > 0:
await progress_callback(expected_size, expected_size)
+218
View File
@@ -0,0 +1,218 @@
"""Request-level regressions for quota-limited satellite downloads."""
import gzip
import json
import os
import time
from unittest.mock import AsyncMock
import httpx
import pytest
from app.services.collectors.celestrak import CelesTrakTLECollector, CELESTRAK_CACHE_TTL_SECONDS
from app.services.collectors.downloads import ResumableFileDownloader
URL = "https://celestrak.example/gp.php?GROUP=active&FORMAT=json"
def setup_collector(monkeypatch, tmp_path, handler):
collector = CelesTrakTLECollector()
collector._resolved_url = "https://celestrak.example/gp.php"
monkeypatch.setattr(collector._downloader, "_cache_dir", tmp_path)
monkeypatch.setattr(collector, "update_phase_progress", AsyncMock())
monkeypatch.setattr("app.services.collectors.celestrak.emit_business_log", AsyncMock())
monkeypatch.setattr("app.services.collectors.celestrak.asyncio.sleep", AsyncMock())
original_client = httpx.AsyncClient
monkeypatch.setattr(
"app.services.collectors.celestrak.httpx.AsyncClient",
lambda **kwargs: original_client(transport=httpx.MockTransport(handler), **kwargs),
)
return collector
def expire(path):
old = time.time() - CELESTRAK_CACHE_TTL_SECONDS - 1
os.utime(path, (old, old))
@pytest.mark.asyncio
async def test_celestrak_uses_one_get_and_revalidates_after_cache_expiry(monkeypatch, tmp_path):
requests = []
def handler(request):
requests.append(request)
assert request.method == "GET", "HEAD consumes this upstream's download allowance"
return httpx.Response(
200, json=[{"NORAD_CAT_ID": len(requests)}], headers={"etag": f'"v{len(requests)}"'}
)
collector = setup_collector(monkeypatch, tmp_path, handler)
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 1
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 1
assert len(requests) == 1
path = collector._downloader.cached_file_path(URL, ".json")
expire(path)
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 2
assert requests[1].headers["if-none-match"] == '"v1"'
@pytest.mark.asyncio
async def test_not_updated_reuses_valid_cache_without_retry_storm(monkeypatch, tmp_path):
requests = []
def handler(request):
requests.append(request.method)
return httpx.Response(
403, text="GP data has not updated since your last successful download"
)
collector = setup_collector(monkeypatch, tmp_path, handler)
path = collector._downloader.cached_file_path(URL, ".json")
path.write_text('[{"NORAD_CAT_ID":42}]')
expire(path)
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 42
assert requests == ["GET"]
@pytest.mark.asyncio
async def test_bad_download_does_not_replace_last_good_cache(monkeypatch, tmp_path):
collector = setup_collector(monkeypatch, tmp_path, lambda request: httpx.Response(200, json=[]))
path = collector._downloader.cached_file_path(URL, ".json")
path.write_text('[{"NORAD_CAT_ID":42}]')
expire(path)
with pytest.raises(RuntimeError, match="validation failed"):
await collector.fetch()
assert json.loads(path.read_text()) == [{"NORAD_CAT_ID": 42}]
@pytest.mark.asyncio
async def test_corrupt_cache_is_not_reused_or_conditionally_requested(monkeypatch, tmp_path):
requests = []
def handler(request):
requests.append(request)
return httpx.Response(200, json=[{"NORAD_CAT_ID": 7}])
collector = setup_collector(monkeypatch, tmp_path, handler)
path, _, meta = collector._downloader._cache_paths(URL, ".json")
path.write_text("[]")
meta.write_text('{"etag":"old"}')
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 7
assert "if-none-match" not in requests[0].headers
@pytest.mark.asyncio
async def test_conditional_304_keeps_payload_and_refreshes_cache_window(tmp_path):
downloader = ResumableFileDownloader(
cache_namespace="test", cache_root=tmp_path, preflight_head=False, cache_ttl_seconds=7200
)
path, _, meta = downloader._cache_paths(URL, ".json")
path.parent.mkdir(parents=True)
path.write_text('[{"NORAD_CAT_ID":42}]')
meta.write_text('{"etag":"v1"}')
expire(path)
requests = []
def handler(request):
requests.append(request)
return httpx.Response(304)
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
for _ in range(2):
await downloader.download_file(
client,
URL,
extension=".json",
validate_existing=CelesTrakTLECollector._validate_json_file,
)
assert len(requests) == 1
assert requests[0].headers["if-none-match"] == "v1"
assert json.loads(path.read_text())[0]["NORAD_CAT_ID"] == 42
@pytest.mark.asyncio
async def test_compressed_get_length_uses_decoded_payload(tmp_path):
raw = json.dumps([{"NORAD_CAT_ID": 42}]).encode()
body = gzip.compress(raw)
downloader = ResumableFileDownloader(
cache_namespace="test", cache_root=tmp_path, preflight_head=False
)
async with httpx.AsyncClient(
transport=httpx.MockTransport(
lambda request: httpx.Response(
200,
content=body,
headers={"content-encoding": "gzip", "content-length": str(len(body))},
)
)
) as client:
path = await downloader.download_file(
client,
URL,
extension=".json",
validate_existing=CelesTrakTLECollector._validate_json_file,
)
assert path.read_bytes() == raw
@pytest.mark.asyncio
async def test_other_collectors_keep_head_and_range_resume(tmp_path):
downloader = ResumableFileDownloader(cache_namespace="test", cache_root=tmp_path)
final, part, meta = downloader._cache_paths(URL, ".bin")
part.parent.mkdir(parents=True)
part.write_bytes(b"abc")
meta.write_text('{"etag":"v1"}')
requests = []
def handler(request):
requests.append(request)
if request.method == "HEAD":
return httpx.Response(
200, headers={"etag": "v1", "accept-ranges": "bytes", "content-length": "6"}
)
assert request.headers["range"] == "bytes=3-"
return httpx.Response(206, content=b"def", headers={"content-range": "bytes 3-5/6"})
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
await downloader.download_file(client, URL, extension=".bin")
assert [r.method for r in requests] == ["HEAD", "GET"]
assert final.read_bytes() == b"abcdef"
@pytest.mark.asyncio
async def test_fallback_group_refreshes_expired_cache(monkeypatch, tmp_path):
requests = []
def handler(request):
requests.append(request)
if request.url.params["GROUP"] == "active":
return httpx.Response(
403, text="GP data has not updated since your last successful download"
)
return httpx.Response(200, json=[{"NORAD_CAT_ID": 99}])
collector = setup_collector(monkeypatch, tmp_path, handler)
monkeypatch.setattr("app.services.collectors.celestrak.FALLBACK_GROUPS", ("starlink",))
path = collector._downloader.cached_file_path(collector._group_url("starlink"), ".json")
path.write_text('[{"NORAD_CAT_ID":42}]')
expire(path)
assert (await collector.fetch())[0]["NORAD_CAT_ID"] == 99
assert [r.method for r in requests] == ["GET", "GET"]
@pytest.mark.asyncio
async def test_generic_cache_without_validators_must_refresh(tmp_path):
downloader = ResumableFileDownloader(cache_namespace="test", cache_root=tmp_path)
path = downloader.cached_file_path(URL, ".json")
path.parent.mkdir(parents=True)
path.write_text("[]")
requests = []
def handler(request):
requests.append(request.method)
return httpx.Response(200, content=b"[1]" if request.method == "GET" else b"")
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as client:
await downloader.download_file(client, URL, extension=".json")
assert requests == ["HEAD", "GET"]
assert path.read_text() == "[1]"
+30
View File
@@ -8,6 +8,36 @@ This project follows the repository versioning rule:
- `improvement` -> `+0.0.1`(bugfix + 小功能混合)
- `bugfix` -> `+0.0.1`
## [0.75.3] — 2026-09-27
Released: 2026-09-27
### Highlights
- 升级地球材质、地图标记与卫星展示,修复拖拽、采集缓存和任务队列,清理废弃渲染路径。
### Improved / Fixed
- 高清地表采用海陆分离 Shader、可读夜侧与单层柔和大气;保留四张底图及真实昼夜,移除旧厚光壳和无用高光配置。
- 卫星在真实轨道采样之间平滑移动,类别色在昼夜保持一致,蓝色覆盖与拾取位置同步;预测轨道开放并加入方向流光,消除强制闭合尖角。
- 地表设施统一渐变徽标,BGP 保留不规则扁平例外;修复低缩放圆点开关,电视面板与播放器恢复方角。
- 鼠标与单指拖出球体仍持续旋转,保留惯性并在极大倍率下限制灵敏度;修复欧拉角换支导致的反向和普通横拖侧歪。
- CelesTrak 改为直接 GET、限时有效缓存和校验后原子替换;采集队列按 task ID 保留独立历史,防止失败任务被新任务或迟到消息重新激活。
---
## [0.75.2] — 2026-09-25
Released: 2026-09-25
### Highlights
- 修复 Windows 启动器固定使用旧版 PowerShell 的问题,优先在 Windows Terminal 新窗口中运行 PowerShell 7。
### Fixed
- 仓库与桌面 CMD 引导优先使用 `pwsh.exe`,缺少新版 PowerShell 或 Terminal 时保留可用环境回退。
- 已以管理员运行的入口同样进入首选终端,子窗口校验权限后直接衔接 WSL,避免重复提权和递归开窗。
- 补齐终端选择、含空格路径、提权分支回归和中英文说明,保持 WSL 重启参数及默认端口不变。
---
## [0.75.1] — 2026-09-25
Released: 2026-09-25
+2
View File
@@ -1,5 +1,7 @@
# Earth Predicted Orbit Plan
> 2026-09-27 状态更新:选中轨道现为 96% 周期的开放弧线,已移除强制闭合,使用同一 Line Shader 绘制沿预测方向前进的流光;传播器、轨道平面与高度策略保留。以下早期设计以当前实现和技术文档为准。
> Source note: this plan absorbs useful ideas from a sisyphus-created draft formerly stored at `.sisyphus/plans/predicted-orbit.md`.
## Goal
+7
View File
@@ -472,3 +472,10 @@ Neither collector returns sample data on failure. Empty fetches or transformed r
Under the same prefix, `GET/PUT /configuration` and `POST /configuration/reset` require admin/super_admin. Writes accept `{revision, config}` and reset accepts `revision`. Pydantic validates canonical countries, finite values, share totals, duplicate metric/year pairs and report references; each metric/year has one report basis. PostgreSQL category uniqueness and row locking serialize first writes and updates; stale revisions return 409. Configuration and before/after audit records commit in one transaction. Reset removes the override so subsequent reads use the current bundled defaults. `version` is a configuration revision, while `reviewed_at` is the supplied review date. Admin-curated data is not automatically labeled official. Source URLs are references, not scrape instructions.
`/api/v1/data-products/compute/facilities` reads successful snapshots with `compute_contract=v1`, applying country filters and per-source counts in SQL. Epoch excludes planned, decommissioned, superseded, and suspected duplicate records; TOP500 means list observations. Cross-source deduplication remains pending. Historical cutoffs use collection time, never pretending a recently fetched old source was available earlier. Geographic results are bounded and report truncation; total record counts are independent of this limit. Official site helpers are keyed by exact `source` + `source_id`; their access-map centers are site-level references only and retain their official URL in `source_note`.
### CelesTrak download windows and caching
Both active and fallback-group downloads skip HEAD preflight and send GET directly: a preflight may consume the upstream download allowance before the body request. Valid complete cache entries are reused for two hours, then refreshed with conditional GET when validators exist, or ordinary GET otherwise. A 304 reuses validated cache; only the explicit “GP data has not updated” 403 permits a valid-cache fallback. Other 403 errors remain failures. Fallback groups also respect cache age rather than reusing old files indefinitely.
A nonempty GP record list is validated in `.part` before atomically replacing the cache; failed downloads preserve the previous valid payload. Length comes from the GET response, and compressed wire length is not compared with decoded bytes. Other collectors retain HEAD metadata and Range resume support. Restoring a raw cache does not populate the database: trigger a new collection task afterward.
+13 -4
View File
@@ -1,5 +1,12 @@
# Earth Frontend Context
## HD surface and atmosphere materials
The visible HD surface uses a single-draw ShaderMaterial in `earth-surface-material.js`, retaining the R+0.48 mesh, depth policy and surface pick target. The existing controller still switches all four 8K maps, updates the sampler and disposes the previous texture only after success. Normals, view direction and astronomical sunlight share world coordinates. Land is matte; water has grazing-angle cool reflection without a white specular lobe. The existing geographic land/ocean texture owns the optical mask independently of border visibility, with a conservative chroma fallback until loaded and reflection suppression over ice. Original JPEGs are neither repainted nor downsampled.
Color textures are tagged sRGB with mipmaps. The r128 surface shader decodes sRGB; r160 uses hardware texture decoding. Both combine light in linear space and encode once. A local filmic curve affects only the surface instead of enabling global ACES exposure on the sky and data layers. The terminator spans normal dot products [-0.075, 0.16]; night shading has its own geographic texture ghosting and cool ambient branch. A 0.55 power of the locally tone-mapped texture retains shadow variation, followed by separate muted land and deep-indigo ocean tints and low ambient floors. Day/night mixing remains linear with one final sRGB output. Day exposure and reflections are unchanged; no synthetic city lights are added. One R×1.025 BackSide/Additive shell replaces the three rim shells, with depthWrite=false and depthTest=true; inner scattering is part of the surface pass. Independently switchable clouds use matte day/night shading at renderOrder 1.1. The sky uses the existing `starmap_deep_8k.jpg` without a tint overlay.
## Configurable compute observations
Compute cards read annual observations from `/api/v1/data-products/compute/series`; the admin Compute comparison section is the maintenance entry point. `compute-topic.js` fetches with no-store, listens for same-origin `planet-compute-configuration` notifications, and checks every 60 seconds while visible and enabled, plus when the page becomes visible. Observation refresh does not reload facility layers. `destroy()` releases the timer, channel and visibility listener. Country membership, full regional coverage and missing-value semantics remain backend-owned.
@@ -8,10 +15,8 @@ Compute cards read annual observations from `/api/v1/data-products/compute/serie
On 2026-09-21, `assets/8k_earth_daymap.jpg` was replaced with an 8192×4096 Web derivative of the paired Natural Earth I raster. Its loading path and rendering code remain unchanged. The source is a 16200×8100 EPSG:4326 image; the previous JPEG is preserved byte-for-byte under `resources/earth/archive/2026-09-21/`. Source/license records, the catalogue versus embedded-version discrepancy, SHA256 hashes, JPEG parameters, and recalculated world-file metadata live in `resources/earth/natural-earth-1/`. Large originals remain in Git-ignored `downloads/earth/`, outside the frontend release bundle.
The base-map selector defaults to Original basemap, listed first and saves the source chosen in the display menu. Natural Earth I remains available alongside “Original basemap”, a byte-identical copy of the September 21, 2026 archive; NASA 21K is source archive material only, while runtime delivery stays at one 8K texture. A new source replaces the old GPU texture only after successful loading and releases the old one then; failures retain the old texture and stale responses cannot overwrite the current source. This is a source switch, not an additional rendering layer. The physical texture is JPEG sRGB, does not bake political borders, and detailed boundary alignment is not yet validated. The starfield is restored byte-for-byte to commit `83a10a6c`: `celestial.js` matches that commit, `skyTint` and `skyBrightness` are removed, and `brightStarOpacity` is back to `0.88`; star density and color are no longer calibrated. The HD overlay uses a white `MeshBasicMaterial` with opacity `1` and `toneMapped:false`, with `texture-colors.js` centralizing sRGB read/write. The 0.128 path uses `encoding` plus `LinearTosRGB`; the 0.160.1 path uses `colorSpace` plus the normal colorspace fragment. There is no Phong white-light or colored twilight overlay, blue night tint, `cameraBoost`, or shoulder curve; daylight neutral scaling keeps brightness at or below the source maximum, and dark mode only applies neutral scaling. The original texture asset is unchanged. Natural Earth is intrinsically pale; this does not claim missing detail was restored. Earth still supports the Three 0.128 import-map runtime and frontend package Three 0.160.1 runtime, and WebGL1 derivatives remain enabled for `fwidth`.
Day/night shading uses a narrow smooth transition centered on the solar horizon (normal dot product ±0.12). The day side is capped at the source brightness; night-side linear illumination is 0.24, rising smoothly to at most 0.60 in source shadows to retain dark ocean and forest detail. Shading uses a neutral scalar without added exposure, colored veils, rendering passes, or textures.
Basemaps and TV channels share `hud-select-menu.js` for the HUD popover, list, selection mark, keyboard navigation, and positioning; `tv-source-menu.js` only adapts channel copy. Basemaps disable search, pagination, and counts. The trigger owner identifies popover clicks as internal to the mobile drawer.
This document describes the current real structure of the Earth display frontend. The focus is on helping future changes to the HUD, layers, media panel, real terrain, and BGP visualization avoid repeating past structural and state-sync pitfalls.
@@ -288,7 +293,7 @@ The surface hover tooltip preference is persisted by `controls.js` as `shared.su
The real satellite altitude preference is persisted by `controls.js`, while the rendering state lives in `satellites.js`. When enabled, the real radius from SGP4 is compressed logarithmically into the current Earth visual radius range. When disabled, satellite dots, trails, and predicted orbits all return to the legacy same-sphere display. Toggling this setting must refresh satellite positions and clear trail buffers so a trail never mixes both height models. `maxRealAltitudeOffset = 25` is a visual cap tuned for the current camera and `earthRadius = 100`: GEO / MEO remain clearly higher than LEO, but the highest orbits stay within about 25% beyond the globe radius so selection targets, red trails, and the globe do not feel disconnected.
SGP4 propagation returns an inertial-frame position, so it must not be drawn directly as Earth-fixed longitude / latitude. `satellites.js` uses `gstime` to convert ECI/TEME positions to ECF, then maps that result into the same Three.js axes as `latLonToVector3()`. Satellite dots and short trails use Earth-fixed coordinates for each sample time, representing the object's current position relative to the globe surface. The locked predicted orbit uses the `gstime` from the lock moment for the whole future orbit, projecting the inertial orbit plane onto the current globe pose; that keeps the line closed and keeps the visual orbit inclination aligned with the details card. Fallback predicted orbits must also use a real RAAN + inclination orbital-plane formula, not treat inclination as a constant latitude.
SGP4 propagation returns an inertial-frame position, so it must not be drawn directly as Earth-fixed longitude / latitude. `satellites.js` uses `gstime` to convert ECI/TEME positions to ECF, then maps that result into the same Three.js axes as `latLonToVector3()`. Satellite dots and short trails use Earth-fixed coordinates for each sample time, representing the object's current position relative to the globe surface. The locked predicted orbit uses the `gstime` from the lock moment for an open 96%-period prediction arc, projecting the inertial orbit plane onto the current globe pose. No first vertex or closing chord is appended; arc-length highlights travel toward increasing prediction time, and visual inclination stays aligned with the details card. Fallback predicted orbits must also use a real RAAN + inclination orbital-plane formula, not treat inclination as a constant latitude.
Boundary precision is stored separately by `country-boundaries.js` under `planet.earth.boundaries.highPrecisionEnabled`. When high precision is off, Earth keeps using the bundled low-precision `countries-admin0.min.geojson` fallback even if high-precision manifest/PMTiles files exist locally. When high precision is on but the artifact is missing, the Earth toolbar settings call `/api/v1/earth/boundaries/build` and poll progress. After success, `reloadCountryBoundaries()` hot-swaps the boundary layer without refreshing the page. Boundary hover is independent from interactable hover: a country polygon remains highlighted whenever the surface coordinate is inside it, while the tooltip can still prioritize a satellite, vessel, BGP marker, or other interactable.
@@ -369,7 +374,7 @@ If future cable, satellite, or news cruise is added, do not copy a new set of `m
[controls.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/controls.js) owns the Earth zoom state, and every zoom entry point must ultimately call `setZoomLevel()` to write the camera distance. Do not write `camera.position.z` from other modules, or the zoom percentage, drag sensitivity, and Interactable clustering thresholds will diverge again.
`globe-navigation.js` maps zoom to `sqrt(R² + (D₀² - R²) / zoom²)` with minimum surface clearance and the matching inverse. The 100% camera pose remains unchanged; 500% stays outside the globe. Mouse and single-touch drags choose a mode on pointer-down from the actual camera frustum. A fully visible globe retains legacy screen-delta sensitivity, 0.18 smoothing and release inertia, including movement outside its silhouette. A viewport-clipped globe uses pixel-aligned ray/sphere grabbing only when the initial pointer hits its surface. Subsequent missed intersections pause surface updates and clear fling speed instead of using a closest-point substitute that can reverse rotation. Grabs starting in space use screen deltas. The mode stays fixed throughout the drag; auto-rotation is suspended during dragging and pinching. Returning from a pinch to one finger reselects the mode and rebases the anchor. Click suppression uses displacement from pointer-down, and cancellation clears inertia.
`globe-navigation.js` retains the safe zoom-distance mapping. Mouse and single-touch drags uniformly use legacy screen deltas, 0.18 smoothing and release inertia, including movement outside the globe silhouette; ray/sphere intersection no longer gates dragging. Normal zoom retains legacy sensitivity. Once the globe exceeds the viewport, a smooth surface-distance/viewport cap limits excessive rotation at extreme zoom. Horizontal motion uses geographic yaw, vertical input changes tilt, and quaternion math prevents multi-revolution reversal. Pinch transitions and pointer capture remain intact.
Interactable clustering is selected per layer through `cluster.strategy`. `stable-spherical` uses discrete zoom bands and local 3D bucket clustering, so BGP, compute centers, and Earth interactables do not regroup while the globe rotates inside the same band. `dynamic-screen` keeps projection-based clustering, and `none` disables it. Vessels explicitly disable clustering and avoidance so incremental updates do not rebuild cluster topology. Stable cluster dots stay rigidly aligned to their 3D centroid projection and do not participate in 2D avoidance. See [Earth Interactable Clustering](/home/ray/dev/linkong/planet/docs/technical/en/earth-interactable-clustering.md) for strategy configuration and tuning.
@@ -451,3 +456,7 @@ The root attributes `data-earth-first-frame-ms` and `data-earth-surface-ready-ms
Positioned cards stay hidden while the shared connector draws for 420 ms, then fade in using the HUD 180 ms opacity timing. Targets remain fixed during drawing; subsequent motion does not replay entrance. Reduced-motion preferences skip this animation.
Object clicks, search focus and gesture confirmation share `PresentationController`. Cable selection updates selection/legend state without independently opening the card. InfoCard reveal callbacks are versioned so staging or hiding invalidates older callbacks. Connector completion gates card reveal; cancelled cruises no longer hide a newer selection. Object details reuse the regional-card edge candidates and collision scoring, with dimensions measured while staged. Selecting a mobile search result collapses the search drawer so the focused object, connector and compact card remain visible.
### Satellite particles and smooth rendering
Real GP/TLE propagation remains in the Worker at 250ms sampling intervals. `satellite-motion.js` interpolates radius-preserving rendered positions each frame without changing orbits, sample-time offsets or altitude policy. Rendering, picking current positions, trail tips, hover/locked rings and footprints share these positions. Data/count/altitude resets clear interpolation to prevent unrelated transitions. Batched Points shade analytic discs for the reference small-sphere appearance, with restrained size scaling instead of individual sphere meshes. Starlink and Iridium footprints share `SATELLITE_CONFIG.footprintColor` (`#3399ff`). The old yellow-day/blue-night shader mix is removed; sunlight only adjusts opacity. Satellite particles and predicted orbits share their category color, with a thin dark particle outline for bright terrain. Coverage geometry and capability policy remain unchanged.
@@ -1,5 +1,17 @@
# Earth Layer Style Property Index
`EARTH_MATERIAL_CONFIG.surface.night` centralizes night texture contrast (detailGamma=0.55) and separate land/ocean tint and ambient values. It only contributes to the night branch, keeps day exposure unchanged, and reuses the geographic mask without another texture or draw call.
## Modern object presentation
- Surface: `EARTH_MATERIAL_CONFIG.surface` owns exposure=0.9, landSaturation=0.9, oceanAbsorption=0.36, oceanDeepColor=[0.004,0.012,0.032], night retention and Fresnel parameters. `atmosphere` owns the single shell's radius, color and strength. Base and terrain specular highlights are disabled.
- Cables blend a cool normal tint with their category color, consistently with the legend. Selected pulses follow cumulative route length with 6 repetitions and speed 4.5 in the existing batch draw. Drawing no longer writes depth; original Line pick objects, cable IDs and state logic remain intact.
- Landing points use the 128×128 monochrome `marker-landing-point.svg` micro-core instead of a glossy procedural ball; Sprite picking and billboard size logic remain intact.
- Compute markers use canonical SVG inner glyphs over shared gradient plates, pale rims, top highlights and shadows. GPU/AI uses purple stacked layers, supercomputers purple chips, and infrastructure teal server racks. Estimated badges, optional compact dots and picking remain intact.
- Satellite inclination categories remain distinct using muted cool colors. Propagation, trail caches, selection, footprint geometry and display modes are unchanged. BGP severity, vessel heading and related-object emphasis remain intact; shared HUD surfaces and short tooltip reveals use the same dark visual family.
This document records the material, color, opacity, line width, radius offset, and `renderOrder` style properties of all Earth frontend layers. For layer ordering relationships, see [Earth Render Layer Order](/home/ray/dev/linkong/planet/docs/technical/en/earth-render-layer-order.md).
## Naming Conventions
@@ -20,15 +32,11 @@ This document records the material, color, opacity, line width, radius offset, a
| Earth base radius | `CONFIG.earthRadius` | `100` | `earth.js:createEarth()` |
| Earth base color | `EARTH_MATERIAL_CONFIG.color` | `0x010609` | `MeshPhongMaterial.color` |
| Earth base emissive | `EARTH_MATERIAL_CONFIG.emissive` | `0x010609` | `MeshPhongMaterial.emissive` |
| Earth base specular | `EARTH_MATERIAL_CONFIG.specular` | `0x1a2d45` | `MeshPhongMaterial.specular` |
| Earth base shininess | `EARTH_MATERIAL_CONFIG.shininess` | `12` | `MeshPhongMaterial.shininess` |
| Earth base specular | `EARTH_MATERIAL_CONFIG.specular` | `0x000000` | `MeshPhongMaterial.specular` |
| Earth base shininess | `EARTH_MATERIAL_CONFIG.shininess` | `0` | `MeshPhongMaterial.shininess` |
| Earth base opacity | `EARTH_MATERIAL_CONFIG.opacity` | `1` | `MeshPhongMaterial.opacity` |
| HD texture radius offset | `EARTH_MATERIAL_CONFIG.textureOverlayAltitudeOffset` | `0.48` | Standalone HD texture sphere radius; must keep enough depth separation from the land/ocean base and Earth base sphere to avoid far-zoom z-fighting |
| HD texture opacity | `EARTH_MATERIAL_CONFIG.textureOverlayOpacity` | `0.88` | HD texture `MeshPhongMaterial.opacity` |
| HD texture renderOrder | `EARTH_MATERIAL_CONFIG.textureOverlayRenderOrder` | `0.96` | `_earthTextureOverlay.renderOrder` |
| HD texture specular | `EARTH_MATERIAL_CONFIG.textureOverlaySpecular` | `0x05080d` | Reduces specular highlight in direct-light areas to avoid blown-out texture |
| HD texture shininess | `EARTH_MATERIAL_CONFIG.textureOverlayShininess` | `4` | Reduces specular concentration |
| HD texture color multiplier | inline | `0xffffff` | `_earthTextureOverlayMaterial.color` |
## Earth Occluder and Day/Night
@@ -36,7 +44,7 @@ This document records the material, color, opacity, line width, radius offset, a
| --- | --- | --- | --- |
| Occluder radius factor | `EARTH_MATERIAL_CONFIG.occluderRadiusFactor` | `0.999` | Depth occluder sphere radius |
| Occluder segments | `EARTH_MATERIAL_CONFIG.occluderSegments` | `48` | Occluder geometry segments |
| Occluder renderOrder | inline | `-1` | `occluder.renderOrder` |
| Occluder renderOrder | inline | `0.5` | `occluder.renderOrder` |
| Day/night sun direction | `EARTH_MATERIAL_CONFIG.dayNight.sunDirection` | `{ x: 1, y: 0.2, z: 0.4 }` | Custom day/night shader |
| Night-side minimum brightness | `EARTH_MATERIAL_CONFIG.dayNight.nightFloor` | `0.24` | Shader uniform |
| Day-side boost | `EARTH_MATERIAL_CONFIG.dayNight.dayBoost` | `1.12` | Shader uniform |
@@ -50,27 +58,12 @@ This document records the material, color, opacity, line width, radius offset, a
| Name | Variable | Current Value | Location / Notes |
| --- | --- | --- | --- |
| Inner atmosphere radius factor | `EARTH_MATERIAL_CONFIG.atmosInnerRadiusFactor` | `1.01` | `atmosInnerGeo` |
| Inner atmosphere segments | `EARTH_MATERIAL_CONFIG.atmosInnerSegments` | `64` | `atmosInnerGeo` |
| Inner atmosphere color | `EARTH_MATERIAL_CONFIG.atmosInnerColor` | `[0.25, 0.62, 1.0]` | Shader RGB |
| Inner atmosphere rim power | `EARTH_MATERIAL_CONFIG.atmosInnerRimPower` | `3.2` | Shader rim falloff |
| Inner atmosphere intensity | `EARTH_MATERIAL_CONFIG.atmosInnerIntensity` | `0.18` | Shader alpha multiplier |
| Outer atmosphere radius factor | `EARTH_MATERIAL_CONFIG.atmosOuterRadiusFactor` | `1.016` | `atmosOuterGeo` |
| Outer atmosphere segments | `EARTH_MATERIAL_CONFIG.atmosOuterSegments` | `48` | `atmosOuterGeo` |
| Outer atmosphere color | `EARTH_MATERIAL_CONFIG.atmosOuterColor` | `[0.18, 0.45, 0.9]` | Shader RGB |
| Outer atmosphere rim power | `EARTH_MATERIAL_CONFIG.atmosOuterRimPower` | `5.0` | Shader rim falloff |
| Outer atmosphere intensity | `EARTH_MATERIAL_CONFIG.atmosOuterIntensity` | `0.02` | Shader alpha multiplier |
| Atmosphere blending | inline | `THREE.AdditiveBlending` | `ShaderMaterial.blending` |
| Atmosphere renderOrder | inline | `1` | `atmosInner/Outer.renderOrder` |
| No-HD-texture rim glow color | `EARTH_MATERIAL_CONFIG.rimGlowColor` | `[0.35, 0.65, 1.0]` | Fresnel shell RGB when HD texture is hidden or unavailable |
| No-HD-texture rim glow power | `EARTH_MATERIAL_CONFIG.rimGlowPower` | `3.8` | Shader rim falloff; higher = narrower edge |
| No-HD-texture rim glow intensity | `EARTH_MATERIAL_CONFIG.rimGlowIntensity` | `0.28` | Shader alpha multiplier |
| No-HD-texture rim glow segments | `EARTH_MATERIAL_CONFIG.rimGlowSegments` | `64` | `earth-rim-glow` geometry segments |
| Cloud layer radius offset | `CLOUD_LAYER_CONFIG.radiusOffset` | `3` | Cloud sphere radius |
| Cloud layer segments | `CLOUD_LAYER_CONFIG.widthSegments / heightSegments` | `64 / 64` | Cloud sphere geometry |
| Cloud layer opacity | `CLOUD_LAYER_CONFIG.opacity` | `0.15` | `MeshPhongMaterial.opacity` |
| Cloud layer opacity | `CLOUD_LAYER_CONFIG.opacity` | `0.15` | `MeshBasicMaterial.opacity` |
| Cloud texture | `CLOUD_LAYER_CONFIG.textureUrl` | `"./assets/earth_clouds_1024.png"` | Cloud texture map |
| Cloud blending | inline | `THREE.AdditiveBlending` | `MeshPhongMaterial.blending` |
| Cloud blending | inline | `THREE.AdditiveBlending` | `MeshBasicMaterial.blending` |
## Land/Ocean Base and Country Borders
@@ -123,8 +116,8 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor
| Terrain opacity | `TERRAIN_CONFIG.opacity` | `0.68` | `MeshPhongMaterial.opacity` |
| Terrain color | `TERRAIN_CONFIG.color` | `0x8aa884` | `MeshPhongMaterial.color` |
| Terrain emissive | `TERRAIN_CONFIG.emissive` | `0x030704` | Reduces self-emission to preserve terrain shading |
| Terrain specular | `TERRAIN_CONFIG.specular` | `0x344438` | Gives terrain local sheen without boosting HD texture brightness |
| Terrain shininess | `TERRAIN_CONFIG.shininess` | `16` | Tightens terrain highlight |
| Terrain specular | `TERRAIN_CONFIG.specular` | `0x000000` | Matte terrain; no white specular lobe |
| Terrain shininess | `TERRAIN_CONFIG.shininess` | `0` | Specular disabled |
| Terrain renderOrder | inline | `1.2` | `terrain.renderOrder` |
| Terrain polygonOffset | inline | `factor -1`, `units -1` | Reduces z-fighting near sphere surface |
@@ -174,8 +167,8 @@ The land/ocean base is an Earth base-map asset and preloads at startup; the "Bor
| Satellite altitude compression scale | `SATELLITE_CONFIG.altitudeCompressionKm` | `1200` | TLE/SGP4 altitude compression; larger values soften high-orbit separation |
| Satellite real-altitude cap | `SATELLITE_CONFIG.maxDisplayAltitudeKm` | `40000` | Altitude clamp for the compressed display mapping, covering GEO-range altitude |
| Satellite real-altitude display offset range | `minRealAltitudeOffset / maxRealAltitudeOffset` | `4 / 25` | Compressed offset added to `CONFIG.earthRadius`; `25` is about one quarter of the current globe radius `100`, keeping high-orbit separation visible without pushing GEO/MEO trails too far away |
| Satellite dot base pixel size | `SATELLITE_CONFIG.dotBaseSize` | `2.8` | Point shader size |
| Satellite backdrop dot scale | `SATELLITE_CONFIG.dotBackdropScale` | `1.28` | Backdrop dot size |
| Satellite dot base pixel size | `SATELLITE_CONFIG.dotBaseSize` | `2.2` | Point shader size |
| Satellite backdrop dot scale | `SATELLITE_CONFIG.dotBackdropScale` | `1.4` | Backdrop dot size |
| Satellite dot opacity range | `dotOpacityMin / dotOpacityMax` | `0.42 / 1.0` | Breathing animation |
| Satellite dot breathing speed | `SATELLITE_CONFIG.dotBreathingSpeed` | `0.12` | Dot opacity animation |
| Satellite backdrop renderOrder | inline | `5` | `satelliteBackdropPoints.renderOrder` |
@@ -216,8 +209,8 @@ AIS vessel markers use batched `THREE.Points`, not one `THREE.Sprite` per vessel
| Hover scale | `COMPUTE_CENTER_CONFIG.marker.hoverScale` | `1.16` | Hover overlay size multiplier |
| Locked scale | `COMPUTE_CENTER_CONFIG.marker.lockedScale` | `1.22` | Locked overlay size multiplier, with pulse |
| Dimmed scale / opacity | `dimmedScale / dimmedOpacity` | `0.82 / 0.34` | Dim state |
| Supercomputer color | `COMPUTE_CENTER_CONFIG.colors.supercomputer` | `"#38bdf8"` | Marker texture |
| GPU cluster color | `COMPUTE_CENTER_CONFIG.colors.gpu_cluster` | `"#2dd4bf"` | Marker texture |
| Supercomputer color | `COMPUTE_CENTER_CONFIG.colors.supercomputer` | `"#a855f7"` | Marker texture |
| GPU cluster color | `COMPUTE_CENTER_CONFIG.colors.gpu_cluster` | `"#a855f7"` | Marker texture |
| Linked color | `COMPUTE_CENTER_CONFIG.colors.linked` | `"#f8fafc"` | Linked state |
| Compute center renderOrder | local `COMPUTE_CENTER_RENDER_ORDER` | `4.5` | Surface facility below satellites |
@@ -263,3 +256,30 @@ AIS vessel markers use batched `THREE.Points`, not one `THREE.Sprite` per vessel
| Star radius range | `minRadius + radiusJitter` | `800 + 200` | Random distribution |
| Star color | `STARFIELD_CONFIG.color` | `0xffffff` | `PointsMaterial.color` |
| Star size | `STARFIELD_CONFIG.size` | `0.5` | `PointsMaterial.size` |
## Badge taxonomy and palette
| Type | Primary color | Inner glyph |
| --- | --- | --- |
| Datacenter/infrastructure | Teal `#14b8a6` → `#0d9488`, rim `#5eead4` | Server rack |
| GPU/AI | Purple `#a855f7` → `#7e22ce`, rim `#d8b4fe` | Stacked compute layers |
| Supercomputer | Same purple family | Chip |
| Cable landing point | Amber `#f59e0b`, pale-gold `#fef3c7` rim | Glowing circular core |
| BGP collector | Blue and existing activity heat colors | Flat broadcast tower, no badge plate |
| BGP event | Low/medium/high/critical: blue/amber/orange/red | Irregular flat event symbols, no badge plate |
| Vessel | Cargo blue, tanker orange, passenger teal, fishing amber, military indigo, other silver | Heading arrow; anchored state retained |
| Custom marker | Place green, note yellow, alert red, default blue | Pin, note sheet, warning triangle |
BGP retains irregular flat symbols as the exception; other finite surface objects share cached badge textures without a new DOM node or draw object per marker. Vessels retain heading buckets and vertex colors rather than multiplying buckets by vessel type. Satellites use distinct category colors with a thin dark outline; orbit and footprint calculations stay intact. Optional low-zoom dots remain available, default off; both rendering and pick sizing honor the switch.
### Stable satellite palette
Category colors follow [satellitemap.space](https://satellitemap.space/) while retaining this project's real inclination classes: 0–30° blue `#3399ff`, 30–60° orange `#ff801a`, 60–90° green `#00e680`, 90–120° purple `#cc33ff`, 120–180° rose `#ff3366`, unknown gray `#94a3b8`. A satellite keeps its hue across day/night; predicted orbits no longer use an unrelated yellow-purple gradient.
All coverage uses `#3399ff`, opacity 0.34, with a day-side opacity multiplier of 1.65 rather than switching to yellow. Particle dark-outline scale is 1.4 and opacity 0.46, reusing the existing backdrop point batch without additional draw batches.
### Selected orbit and panel outlines
Prediction draws an open 96%-period arc with faded endpoints and no appended closing vertex. Highlights travel forward along cumulative arc length in the same Line draw. TV and shared HUD shells use square corners, including the player clip, without changing panel size or dragging. Temporary frame-statistics instrumentation and its QA-only DOM attributes are removed from release code.
@@ -1,6 +1,6 @@
# Earth Render Layer Order
The compute topic reuses the compute-center Interactable icons, depth behavior, and layer order. Country/year changes replace that layer's data and clear prior selection. Its HUD is screen UI excluded from Earth picking in `main.js`. Regional cards are tethered in screen space; rear anchors do not draw connectors through the globe. Facility details reuse the existing card and mobile details drawer. The existing outer atmosphere shell remains, while the starfield is restored to commit `83a10a6c` (`brightStarOpacity:0.88`; no tint/brightness calibration). The HD overlay is a white `MeshBasicMaterial` with opacity 1 and `toneMapped:false`; `texture-colors.js` selects the r128 `encoding`/`LinearTosRGB` path or r160 `colorSpace`/colorspace fragment. No Phong white light, colored twilight, blue night tint, camera boost, or shoulder curve is added. No new post-processing, GPU draw pass, or high-resolution texture was added; the compute topic adds 45 local SVG flag assets.
The compute topic reuses the compute-center Interactable icons, depth behavior, and layer order. Country/year changes replace that layer's data and clear prior selection. Its HUD is screen UI excluded from Earth picking in `main.js`. Regional cards are tethered in screen space; rear anchors do not draw connectors through the globe. Facility details reuse the existing card and mobile details drawer. The visible HD surface uses a single-draw ShaderMaterial in `earth-surface-material.js`, retaining the R+0.48 mesh, depth policy and surface pick target. The existing controller still switches all four 8K maps, updates the sampler and disposes the previous texture only after success. Normals, view direction and astronomical sunlight share world coordinates. Land is matte; water has grazing-angle cool reflection without a white specular lobe. The existing geographic land/ocean texture owns the optical mask independently of border visibility, with a conservative chroma fallback until loaded and reflection suppression over ice. Original JPEGs are neither repainted nor downsampled. Color textures are tagged sRGB with mipmaps. The r128 surface shader decodes sRGB; r160 uses hardware texture decoding. Both combine light in linear space and encode once. A local filmic curve affects only the surface instead of enabling global ACES exposure on the sky and data layers. The terminator spans normal dot products [-0.12, 0.28]; night attenuation retains 0.12–0.32 linear illumination after tone mapping to avoid crushing source shadows twice. One R×1.025 BackSide/Additive shell replaces the three rim shells, with depthWrite=false and depthTest=true; inner scattering is part of the surface pass. Independently switchable clouds use matte day/night shading at renderOrder 1.1. The sky uses the existing `starmap_deep_8k.jpg` without a tint overlay.
This document records the current Earth renderer's layer order and the intent of each layer. When adjusting `renderOrder`, radius offsets, depth strategy, or pointer interaction, update this document accordingly.
@@ -16,12 +16,12 @@ Note: the layer control panel order and the registration / startup load order ar
| Order | Layer | Source | Render / Radius Strategy | Depth / Interaction Strategy | Notes |
| --- | --- | --- | --- | --- | --- |
| -1000 | Celestial background mesh | `celestial.js` | Background sphere | Not part of surface picking | Behind all Earth content. |
| -1 | Earth occluder sphere | `earth.js` | Invisible inner sphere | Writes depth buffer | Occludes objects behind the Earth. |
| 0.5 | Earth occluder sphere | `earth.js` | Invisible inner sphere | Writes depth buffer | Occludes objects behind the Earth. |
| 0 | Earth base sphere | `earth.js` | `CONFIG.earthRadius` | Surface picking fallback target | Dark base; still visible when all optional map layers are off. |
| 0.2 | Country dark tint | `country-boundaries.js` | `tintAltitudeOffset` | Raycast disabled | Used when HD texture is off. |
| 0.86 | Land/ocean base fill | `country-boundaries.js` | `landAltitudeOffset = 0.32`; ocean `#010609`, land `#080f1b` | Raycast disabled | Base map remains usable even when country borders are off; radius is separated from the base sphere to avoid far-zoom z-fighting. |
| 0.96 | HD Earth texture | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | Surface picking target when visible | HD texture always overlays the land/ocean base fill; radius must stay above the land/ocean base and far enough from the base sphere. |
| 1 | Atmospheric glow and clouds | `earth.js` | Atmosphere / cloud spheres | Not in normal object selection path | Cloud layer controlled by the "Cloud Layer" toggle. |
| 1 / 1.1 | Atmosphere / clouds | `earth.js` | One atmosphere shell at R×1.025; clouds at R+3 | Atmosphere uses BackSide, depthWrite=false, depthTest=true; cloud toggle retained | Inner scattering shares the surface pass; no fullscreen post-processing. |
| 1 | Submarine cables / landing points | `cables.js`, `cable-batches.js` | All cable segments share one `LineSegments`; all landing points use instanced billboards; render order remains `1`; cable altitude offset stays `0.2`, while landing-point anchors use the HD surface offset `0.48` | Original `Line` / `Sprite` objects retain per-item picking and selection state but no longer draw individually; landing-point sphere occlusion remains, with `depthTest: false` on the batch | Style textures and instance attributes preserve color, pulse, size, visibility, and click behavior. |
| 1.2 | Real terrain | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` plus terrain displacement | Raycast disabled | Terrain overlays HD texture; temporarily hidden when HD texture is off, restores to prior state when re-enabled. |
| 2.05 | Grid lines | `earth.js` | `CONFIG.earthRadius + 0.14` | Raycast disabled | Low-opacity lines over HD texture. |
@@ -35,7 +35,7 @@ Note: the layer control panel order and the registration / startup load order ar
| 4.5 | Compute centers | `compute-centers.js`, `interactable.js` | `COMPUTE_CENTER_RENDER_ORDER` | Screen-space Interactable picking, with surface-icon collision handling | Surface facilities, below satellites. |
| 5 | Satellite background dot | `satellites.js` | Fixed renderOrder; by default TLE/SGP4 altitude is compressed to `CONFIG.earthRadius + 4..25`; with real altitude disabled or propagation failed, uses `fallbackAltitudeOffset = 8` | Screen-space satellite picking | Below satellite dots. |
| 6 | Satellite dots | `satellites.js` | Same compressed / fallback height as satellite backdrop dots | Screen-space satellite picking | Satellite dots above footprints and compute centers. |
| 12+ | Satellite locked ring, halo, predicted orbit | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` and offsets; predicted orbit follows the same real-altitude toggle and fixes the lock-time globe pose to draw a closed inertial orbit; returns to same-sphere mode when real altitude is disabled | Satellite overlay path | Used for selected/locked satellite emphasis. |
| 12+ | Satellite locked ring, halo, predicted orbit | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` and offsets; predicted orbit follows the same real-altitude toggle and fixes the lock-time globe pose to draw an open 96%-period inertial arc with forward-flow highlights; returns to same-sphere mode when real altitude is disabled | Satellite overlay path | Used for selected/locked satellite emphasis. |
| 98-100 | Sun / moon halo and sprite | `celestial.js` | Fixed renderOrder | Celestial picking disabled | Foreground celestial sprites. |
## Full-set rendering and updates
@@ -75,6 +75,8 @@ This keeps Earth, AI, collection management, and other multi-section pages from
## Datasource Collection Queue
`datasource-task-queue.ts` reconciles attempts by task ID. Retrying a source adds a new attempt and preserves failed/completed/cancelled history; source matching is allowed only for active placeholders without an ID. Late events cannot reactivate terminal attempts, and older task polls cannot overwrite the latest datasource task. Task status uses `ListChecks`; refresh retains `RefreshCw`.
The Admin datasource page routes single-source trigger, table-selected trigger, and trigger-all into a browser-download-list style collection queue:
- Queue state is managed by [PlainResourcePages.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx). It is a current-session visibility layer and does not fake task history in `localStorage`.
+10
View File
@@ -425,3 +425,13 @@ The default national metric is global compute-device scale, covering basic, inte
This prototype shows up to six content cards. The main card centers on the selected compute metric: a large share percentage or absolute value with its unit, observation year, historical context, and source entry. Missing comparable data is shown as “No comparable data yet”; a trend is omitted when there are no observations rather than rendered as an empty chart. Facility records and coverage metadata remain complete but move to the expanded auxiliary area; sample counts are evidence context, never a compute value or global coverage rate. Region previews may show member counts, and long lists open only when needed. Desktop compact cards are about 268px wide with content-driven height; expanded cards support user resizing up to 480px. Mobile keeps the same single metric meaning in the one-card accordion rather than promoting facility counts. Local card position and size are saved, with a reset-to-auto action. The content layout leaves room for later image and video integration, but those media data are not connected yet. When outside space is insufficient, cards can travel through the globe's foreground instead of teleporting or shrinking to labels.
When the map cards switch is off, the overview summary still loads. Turning it on shares the map loading event; a newer request cancels the previous one. Drawer event handling follows `composedPath()` so replacing inner HTML cannot accidentally collapse the active row. The shared HUD collapsible panel animation is reused and respects reduced-motion preferences. Facility names remain in a scroll region capped at 240px; rows are left-aligned, wrap long names, and retain at least 42px of touch height.
## Surface and object appearance
The real surface retains all four map choices. Day/night shading follows the sun, with uniform illumination when disabled. Selected cables show traveling pulses and landing points use amber micro-markers. Facilities show chip symbols up close while the compact-dot preference remains available. Satellites retain self-glow/ground-coverage modes, trails and their existing orbital motion. BGP severity, vessel heading, related highlights, detail cards and mobile drawers retain their established interactions.
### Satellite orbits and collection attempts
Selecting a satellite shows an open predicted arc with highlights moving in the travel direction. Satellites, trails and footprints remain synchronized. Coverage stays blue across day/night; particle and orbit category colors match the legend. Dragging continues outside the globe silhouette, with reduced sensitivity at extreme zoom. The TV panel has square corners like other cards.
Retriggering a datasource creates a new task while older failures remain in the failed group. Task Status uses a checklist icon, distinct from Refresh. CelesTrak can reuse valid recent download cache; each new collection attempt still gets its own task and updates collected data.
@@ -2,6 +2,8 @@
## Windows desktop launcher
The launcher prefers a new Windows Terminal window and explicitly runs PowerShell 7 (`pwsh.exe`), independently of the default Terminal profile. Without PowerShell 7 it falls back to Windows PowerShell; without Terminal it starts the available PowerShell directly. The CMD bootstrap also prefers PowerShell 7. Ordinary entries request elevation; entries already running as administrator still dispatch to the preferred terminal without another elevation request. The child validates its privileges and enters WSL directly, preventing recursive windows. The existing post-restart WSL shell is retained.
On first use, open the actual project folder in Windows Explorer and double-click the repository's `planet.cmd`. It derives the WSL distribution and Linux project directory from its own location, creates `Planet.cmd` on the current user's actual Windows desktop, then follows the normal restart flow. Both `\\wsl$\distribution\...` and `\\wsl.localhost\distribution\...` work. Local Windows-drive checkouts use the default WSL distribution and `wslpath`. Windows resolves the desktop location, including redirected desktops such as OneDrive; WSL, zsh and project dependencies must already be installed.
Subsequent desktop launches use the bound target, request the existing administrator elevation and call `planet.sh restart --allow-lan`. No test ports are embedded: defaults remain frontend 3000, backend 8000 and AI Provider 8010, subject to explicit `DEFAULT_*_PORT` environment overrides. Successful restarts open Earth using the actual `ports.env` values and retain the WSL shell; failures display their error without opening a success page. `scripts/windows/planet-launcher.ps1` owns path resolution, desktop installation and elevation; `scripts/windows/restart.zsh` only bridges to the existing lifecycle script.
+1
View File
@@ -311,6 +311,7 @@ For each newly confirmed cause, update both language tables with a stable code,
<!-- planet-error-catalog:start -->
| Error code | Matching fragments (semicolon-separated) | Cause / established failure | Remedy |
| --- | --- | --- | --- |
| P_CELESTRAK_NOT_UPDATED | GP data has not updated since your last successful | CelesTrak rejected a repeated download within an update window. HEAD 200 followed by GET 403 can mean preflight consumed the allowance, not an unreachable egress route. | Use the collector without HEAD preflight and preserve validated raw cache. Without valid cache, wait for the next GP update or configure Space-Track instead of retrying repeatedly. |
| P_WINDOWS_LAUNCHER_TARGET_MISSING | P_WINDOWS_LAUNCHER_TARGET_MISSING | The bound WSL project is unavailable or lacks launcher scripts, commonly after moving a checkout, losing access to a distribution or copying another machine's desktop launcher. | Run the repository planet.cmd from the current checkout to regenerate this machine's desktop launcher and verify the WSL distribution; do not hardcode another machine's path. |
| P_PROXY_EXTERNAL | PLANET_PROXY_EXTERNAL | Docker proxy settings belong to another configuration source or have been edited manually. | Inspect daemon.json, systemd proxy settings and the Planet ownership record before changing ownership; existing settings are preserved. |
| P_AUTH_BOOTSTRAP_MISSING | DEFAULT_LOGIN_USER_MISSING | The active backend database is confirmed to lack default accounts, often in an isolated preview that skipped initialization. | Verify database ownership and run the existing account initializer without resetting existing passwords or clearing data. |
+4
View File
@@ -77,3 +77,7 @@ Open `/forgot-password`, enter your email, receive a code, then enter the code p
To maintain card values, an administrator opens **Earth content → Compute comparison**, adds report sources, enters comparable annual country observations, then chooses **Save and publish**. Omit missing countries; facility counts never replace compute shares. Bundled defaults can be restored and Earth cards automatically check published configuration.
Open the analysis icon beside Compute Centers and enable Show region cards. Closing configuration keeps the cards active; the switch controls their visibility. Resize or collapse desktop cards and inspect observed history, sources, and facility details. On mobile, use the Compute drawer tab. National indicators and facility samples are separate. “—” means missing evidence, not zero capacity.
### Inspect satellites and retry collection
Enable satellites in Earth and select a particle to inspect its open predicted orbit, travel-direction highlights and supported footprint. Dragging continues beyond the globe silhouette. A failed datasource can be triggered again: the new task is separate, and older failures remain in the current queue’s failed group.
+7
View File
@@ -503,3 +503,10 @@ Epoch 改用官方公开 CSV,保留 FP16 理论性能、原始日期、状态
同前缀的 `GET/PUT /configuration` 和 `POST /configuration/reset` 仅允许 admin/super_admin。写入体为 `{revision, config}`,重置只需要 `revision`。Pydantic 校验国家目录、有限数值、比例总和、重复指标年份和报告引用;每个指标年份只允许一个报告口径。PostgreSQL 唯一分类与行锁串行化首次写入和更新,旧版本返回 409。审计记录和配置在同一事务提交;重置移除覆盖,下次读取随版本默认值。`version` 为配置修订标识,`reviewed_at` 为录入的核验日期,不能将管理员配置一概称为官方报告。来源链接只作引用,不触发抓取。
`/api/v1/data-products/compute/facilities` 仅读取 `compute_contract=v1` 的成功快照,数据库执行国家过滤和按来源计数。Epoch 默认排除规划、退役、已被替代和疑似重复记录;TOP500 表示榜单观测,跨源仍未合并。历史选择按采集时间截止,不将最近抓到的旧资料冒充过去已知的快照。地理结果有返回上限与截断标记,记录统计不受该上限影响。官方 site helper 按精确 `source` + `source_id` 匹配;access map 中心只表示 site 级参考点,并在 `source_note` 保留官方 URL。
### CelesTrak 下载窗口与缓存
CelesTrak active 和 fallback group 均禁用 HEAD 预检,直接 GET,避免预检被上游记为下载后使正文请求收到 403。完整有效缓存两小时内复用;到期后进行条件 GET(有 ETag/Last-Modified 时)或普通 GET。304 复用已校验缓存;仅明确的“GP data has not updated”403 可以回退到有效缓存,其他 403 不伪装成功。fallback group 同样检查缓存时效,不永久使用旧文件。
下载在 `.part` 上校验非空 GP 记录列表后原子替换缓存,失败保留上一份有效文件。内容长度以 GET 响应为准;压缩响应不拿压缩长度校验解压后的字节数。其他采集器继续支持 HEAD 元数据和 Range 断点续传。原始缓存不等于已入库数据,恢复缓存后仍须触发新采集任务。
+14 -3
View File
@@ -1,13 +1,18 @@
# 智能星球前端结构
## 高清地表与大气材质
高清地表由 `earth-surface-material.js` 的单次绘制 `ShaderMaterial` 负责,保持原有 R+0.48 网格、深度策略和地表拾取对象。四张 8K 底图仍由原控制器切换,成功后更新采样 uniform 并释放旧纹理,失败保留原图。法线、视线和真实太阳方向统一到世界坐标;土地哑光,海洋只有掠射角冷色反射,没有白色镜面高光。海洋区分优先复用现有海陆地理纹理,未加载时使用保守色差估计,冰雪抑制反射;关闭国界线不移除光学遮罩。原始 JPEG 不重绘、不降采样。
颜色纹理标记 sRGB 并启用 mipmaps。r128 在地表 Shader 中解码 sRGB,r160 由纹理硬件格式解码;二者在线性空间合成光照后只编码一次。局部 filmic 曲线只作用于地表,不打开全局 ACES 曝光,避免改变星空和业务图层。晨昏范围为法线点积 [-0.075, 0.16],夜侧单独计算地理纹理透光与冷色环境漫射:对局部色调映射后的纹理用 0.55 次幂保留暗部层次,再分别应用陆地冷灰绿、海洋深靛蓝的纹理系数和极弱环境底色;最后在线性空间按晨昏系数混合昼夜并统一输出 sRGB。日面曝光和反射不变,不添加虚构城市灯光。大气收敛为 R×1.025 的一个 BackSide/Additive 壳,depthWrite=false、depthTest=true,内沿散射并入地表;云图独立开关,使用哑光昼夜材质并在 1.1 顺序绘制。星图使用已有 `starmap_deep_8k.jpg`,不加染色遮罩。
## 地表贴图资源记录
2026-09-21,`assets/8k_earth_daymap.jpg` 替换为 Natural Earth I 配套栅格的 8192×4096 Web 派生图,加载路径和渲染代码未变。源图为 EPSG:4326、16200×8100;旧 JPG 在仓库 `resources/earth/archive/2026-09-21/` 逐字节保留。来源、许可、源包/目录版本差异、SHA256、JPEG 参数及按导出尺寸重算的定位文件见 `resources/earth/natural-earth-1/`。原始大文件位于 Git 忽略的 `downloads/earth/`,不进入前端发布包。
底图选择器默认使用“原始底图”,并将该选项放在首位,显示菜单可切换并在本地保存选择。已有 Natural Earth I 保留可用,并增加“原始底图”选项,使用 2026-09-21 归档原图的逐字节副本;NASA 21K 只作为源归档,运行时统一使用一张 8K 贴图。新贴图成功加载后才替换并释放旧 GPU 纹理,失败时保留旧纹理,过期响应不会覆盖当前结果;这是源切换,不新增渲染层。物理贴图为 JPEG sRGB,未烘焙政治边界,也未完成逐段边界对齐验收。星空逐字节恢复到上次提交前的 commit `83a10a6c`:`celestial.js` 与该提交一致,删除 `skyTint`、`skyBrightness`,`brightStarOpacity` 恢复为 `.88`,不再校准星空密度和颜色。高清 overlay 使用白色 `MeshBasicMaterial`、opacity 1、`toneMapped:false`,由 `texture-colors.js` 统一 sRGB 读写;r128 使用 `encoding`/`LinearTosRGB`,r160 使用 `colorSpace`/colorspace fragment。不叠加 Phong 白光、彩色暮光、蓝色夜染、`cameraBoost` 或 shoulder 曲线;daylight 中性亮度不超过原图最大值,dark 仅做 neutral 缩放,原图资源不变。Natural Earth 原图本身偏浅,不声称恢复不存在的细节。为 WebGL1 的 `fwidth` 开启 derivatives。
昼夜明暗使用以太阳地平线为中心的窄平滑过渡(法线点积 ±0.12)。日面保持原图亮度上限;夜面线性光照系数为 0.24,原图暗部最高保留 0.60,按源亮度连续过渡,以保持暗色海洋和森林细节。只使用中性标量,不增加曝光、彩色罩层、额外渲染通道或纹理。
地表底图与新闻频道复用 `hud-select-menu.js` 的 HUD 浮层、列表、选中标记、键盘导航和定位;`tv-source-menu.js` 仅保留频道文案适配。底图关闭搜索、分页和计数,菜单通过触发按钮归属参与移动抽屉的内部点击判断。
本文件描述当前智能星球前端的真实结构,重点是帮助后续继续改 HUD、图层、媒体面板、真实地形、BGP 可视化时,不再重复踩结构和状态同步上的坑。
@@ -439,6 +444,8 @@ asset 图标大小由 `Interactable` 的 `icon.fitSize` 控制。SVG / 图片文
[controls.js](/home/ray/dev/linkong/planet/frontend/public/earth/js/controls.js) 统一维护智能星球缩放状态,所有入口最终都必须调用 `setZoomLevel()` 写相机距离。不要在其他模块直接写 `camera.position.z`,否则缩放百分比、拖拽灵敏度和 Interactable 聚合阈值会再次分叉。
鼠标与单指统一使用原有屏幕位移驱动、0.18 平滑和松手惯性。按下后拖出球体轮廓仍连续旋转,不再调用射线/球面命中作为拖动前提。常规缩放保留原灵敏度;球体超出视口后平滑加入按相机距地表距离和视口尺寸计算的旋转上限,修正极大倍率的放大效应。左右绕地理轴、上下改倾角,四元数保持多圈不反向;双指缩放切换与 pointer capture 保留。
滚轮输入分两类处理:传统鼠标滚轮保留 10% 档位和短动画,并用 `wheelZoomTarget` 作为连续滚动的逻辑基准;触控板 / 高精度滚轮按 pixel delta 连续缩放,直接调用 `setZoomLevel()`,不走 10% 档位动画。触控板路径还会过滤反向后的短窗口旧方向小 residual delta,避免惯性尾巴把用户刚反向的缩放又拉回旧方向。
该提示每 90ms 最多更新一次,显示 760ms 后淡出。它是视角反馈,不是数据加载进度,也不应该写进图层 loading 状态。
@@ -495,7 +502,7 @@ Earth 设置面板当前由 [controls.js](/home/ray/dev/linkong/planet/frontend/
卫星真实高度开关由 `controls.js` 持久化,实际渲染状态在 `satellites.js`。开启时,SGP4 得到的真实半径会按对数压缩到当前 Earth 视觉半径范围;关闭时,卫星点、轨迹和预测轨道都回到旧版同层球面。切换时必须刷新卫星位置并清理轨迹缓存,避免同一条轨迹混入两个高度模型。`maxRealAltitudeOffset = 25` 是当前相机和 `earthRadius = 100` 下的视觉上限:它让 GEO / MEO 比 LEO 明显更高,但把最高轨道控制在地球半径外约 25%,避免选择点、红色轨迹和主体地球之间出现过大的空场。
SGP4 传播输出是惯性系位置,不能直接当成 Earth 的经纬度固定坐标使用。`satellites.js` 会用当前时间的 `gstime` 把 ECI/TEME 位置转换到 ECF,再映射到 `latLonToVector3()` 使用的 Three.js 坐标轴。卫星点和短尾迹使用随采样时间变化的地固坐标,表示相对当前地球表面的实际位置;锁定后的预测轨道线使用锁定时刻固定的 `gstime`,把未来一圈惯性轨道投到当前地球姿态上显示,因此会闭合,并且轨道面倾角应与详情卡一致。fallback 预测轨道也必须使用真正的 RAAN + inclination 轨道平面公式,不能把 inclination 当成恒定纬度。
SGP4 传播输出是惯性系位置,不能直接当成 Earth 的经纬度固定坐标使用。`satellites.js` 会用当前时间的 `gstime` 把 ECI/TEME 位置转换到 ECF,再映射到 `latLonToVector3()` 使用的 Three.js 坐标轴。卫星点和短尾迹使用随采样时间变化的地固坐标,表示相对当前地球表面的实际位置;锁定后的预测轨道线使用锁定时刻固定的 `gstime`,把未来 96% 周期的惯性轨道投到当前地球姿态上显示为开放弧线;不追加首点或用直线强制封口,轨道面倾角与详情卡一致。流光按累计弧长和未来采样方向移动。fallback 预测轨道也必须使用真正的 RAAN + inclination 轨道平面公式,不能把 inclination 当成恒定纬度。
国界精度偏好独立存储在 `country-boundaries.js` 的 `planet.earth.boundaries.highPrecisionEnabled`。未开启高精时,即使本机已经有高精 manifest/PMTiles,也继续加载低精 `countries-admin0.min.geojson` fallback;开启高精但高精产物缺失时,智能星球工具栏设置会调用 `/api/v1/earth/boundaries/build` 启动后台构建并轮询进度。构建成功后调用 `reloadCountryBoundaries()` 热切换,不再刷新整个页面。国界 hover 与 tooltip 解耦:只要地表坐标落在国界 polygon 内就保持高亮;如果鼠标同时命中卫星、船只、BGP 等 interactable,tooltip 显示 interactable 信息,但国界高亮不应闪烁。
@@ -581,3 +588,7 @@ Earth 由 `earth-runtime-plugin.mjs` 将本地模块合并为带内容哈希的
空间卡片定位后保持隐藏,先复用 `CalloutConnector` 的 420 ms 绘线动画,再按共享 HUD 的 180 ms 淡入时长显示卡片。绘线期间固定目标位置,后续跟随运动不重播入场;系统减少动态效果时直接呈现。
物件点击、搜索定位及手势确认统一通过 `PresentationController`。海缆选择处理器只更新选择与图例,不再绕过控制器提前显示卡片;共享 InfoCard 的显示回调带版本标记,新的隐藏/预布局请求会使旧回调失效。所有连线卡片以绘线完成事件作为显示门槛,取消的旧巡航不能关闭新的选择卡片。物件详情复用算力卡的边缘候选与避让评分,按隐藏状态下测得的真实尺寸定位置;手机搜索结果被选中时收起搜索抽屉,让地图定位、引导线与精简卡片可见。
### 卫星粒子与平滑显示
卫星仍由真实 GP/TLE 传播器和 Worker 每 250ms 计算采样。`satellite-motion.js` 在相邻样本之间逐帧做半径保持插值,不改轨道、采样时刻偏移或真实高度策略。绘制缓冲、拾取使用的 current 位置、尾迹末端、悬停/锁定环和覆盖投影共享平滑位置;数据替换、数量变化或高度重置会清空插值,避免跨对象拖影。粒子用批量 Points 中的解析圆盘明暗表现参考页的小球感,缩放温和变化,避免为每颗卫星增加球网格。Starlink 与 Iridium 覆盖统一使用 `SATELLITE_CONFIG.footprintColor`(`#3399ff`);移除日侧黄/夜侧蓝的 Shader 混色,日照只调节透明度。卫星和预测轨道沿用同一轨道类别色,粒子使用薄深色衬边保证明亮地图上的可读性。范围计算和能力策略不变。
@@ -1,5 +1,17 @@
# 智能星球图层样式属性索引
`EARTH_MATERIAL_CONFIG.surface.night` 集中夜侧纹理对比(detailGamma=0.55)及海陆各自的 tint/ambient 参数。它只参与夜侧混合,不调整日面曝光;沿用现有地理遮罩,无新增贴图或 Draw Call。
## 现代物件视觉
- 地表:`EARTH_MATERIAL_CONFIG.surface` 集中 exposure=0.9、landSaturation=0.9、oceanAbsorption=0.36、oceanDeepColor=[0.004,0.012,0.032]、夜面保留与 Fresnel 参数;`atmosphere` 集中单壳半径、颜色和强度。低清基座及地形关闭镜面高光。
- 海缆:常态冷色与原分类色混合,图例与线路保持一致;选中后参考流光沿真实线路累计长度移动,6 个周期、速度 4.5。复用同一批量 draw,绘制材质不写深度;原 Line 对象、cableId、选中逻辑不变。
- 登陆点:`marker-landing-point.svg` 为 128×128 琥珀微核单色源,取代带高光的程序球;Sprite 拾取和 billboard 批量绘制保持原尺寸逻辑。
- 算力:三个规范 SVG 只负责内置符号;`marker-badges.js` 与 `interactable.js` 共同绘制渐变方块底板、浅色边圈、上沿高光与投影。GPU/AI 使用电紫堆叠层,超算使用电紫芯片,数据中心/基础设施使用青绿机柜。估算标志和原拾取/联动保留。
- 卫星:保留真实倾角分类,用蓝、橙、绿、紫、玫红、灰区分,图例、粒子与预测轨道使用同一类别色。粒子不受日夜染色,薄深衬边提高浅色地表对比;覆盖投影统一蓝色,日照只改变透明度。轨道传播、拾取与覆盖范围保持原逻辑。
本文记录当前 Earth 前端各图层的材质、颜色、透明度、线宽、半径偏移和
`renderOrder` 等样式属性。层级关系请配合
[智能星球渲染图层顺序](/home/ray/dev/linkong/planet/docs/technical/zh/earth-render-layer-order.md)
@@ -23,15 +35,11 @@
| 智能星球基座半径 | `CONFIG.earthRadius` | `100` | `earth.js:createEarth()` |
| 智能星球基座颜色 | `EARTH_MATERIAL_CONFIG.color` | `0x010609` | `MeshPhongMaterial.color` |
| 智能星球基座 emissive | `EARTH_MATERIAL_CONFIG.emissive` | `0x010609` | `MeshPhongMaterial.emissive` |
| 智能星球基座 specular | `EARTH_MATERIAL_CONFIG.specular` | `0x1a2d45` | `MeshPhongMaterial.specular` |
| 智能星球基座 shininess | `EARTH_MATERIAL_CONFIG.shininess` | `12` | `MeshPhongMaterial.shininess` |
| 智能星球基座 specular | `EARTH_MATERIAL_CONFIG.specular` | `0x000000` | `MeshPhongMaterial.specular` |
| 智能星球基座 shininess | `EARTH_MATERIAL_CONFIG.shininess` | `0` | `MeshPhongMaterial.shininess` |
| 智能星球基座 opacity | `EARTH_MATERIAL_CONFIG.opacity` | `1` | `MeshPhongMaterial.opacity` |
| 高清材质半径偏移 | `EARTH_MATERIAL_CONFIG.textureOverlayAltitudeOffset` | `0.48` | 独立高清材质球半径;必须与海陆基座和地球基座保持足够深度间距,避免远距 z-fighting |
| 高清材质透明度 | `EARTH_MATERIAL_CONFIG.textureOverlayOpacity` | `0.88` | 高清材质 `MeshPhongMaterial.opacity` |
| 高清材质 renderOrder | `EARTH_MATERIAL_CONFIG.textureOverlayRenderOrder` | `0.96` | `_earthTextureOverlay.renderOrder` |
| 高清材质 specular | `EARTH_MATERIAL_CONFIG.textureOverlaySpecular` | `0x05080d` | 降低直射区域镜面高光,避免贴图死白 |
| 高清材质 shininess | `EARTH_MATERIAL_CONFIG.textureOverlayShininess` | `4` | 降低高光集中度 |
| 高清材质颜色乘色 | inline | `0xffffff` | `_earthTextureOverlayMaterial.color` |
## Earth 遮挡与昼夜
@@ -39,7 +47,7 @@
| --- | --- | --- | --- |
| 遮挡球半径系数 | `EARTH_MATERIAL_CONFIG.occluderRadiusFactor` | `0.999` | 深度遮挡球半径 |
| 遮挡球分段 | `EARTH_MATERIAL_CONFIG.occluderSegments` | `48` | 遮挡球几何分段 |
| 遮挡球 renderOrder | inline | `-1` | `occluder.renderOrder` |
| 遮挡球 renderOrder | inline | `0.5` | `occluder.renderOrder` |
| 昼夜太阳方向 | `EARTH_MATERIAL_CONFIG.dayNight.sunDirection` | `{ x: 1, y: 0.2, z: 0.4 }` | 自定义 day/night shader |
| 夜侧最低亮度 | `EARTH_MATERIAL_CONFIG.dayNight.nightFloor` | `0.24` | shader uniform |
| 日侧增强 | `EARTH_MATERIAL_CONFIG.dayNight.dayBoost` | `1.12` | shader uniform |
@@ -53,30 +61,13 @@
| 正式名称 | 变量名 | 当前值 | 使用位置 / 说明 |
| --- | --- | --- | --- |
| 内层大气半径系数 | `EARTH_MATERIAL_CONFIG.atmosInnerRadiusFactor` | `1.01` | `atmosInnerGeo` |
| 内层大气分段 | `EARTH_MATERIAL_CONFIG.atmosInnerSegments` | `64` | `atmosInnerGeo` |
| 内层大气颜色 | `EARTH_MATERIAL_CONFIG.atmosInnerColor` | `[0.25, 0.62, 1.0]` | shader RGB |
| 内层大气 rim power | `EARTH_MATERIAL_CONFIG.atmosInnerRimPower` | `3.2` | shader rim |
| 内层大气强度 | `EARTH_MATERIAL_CONFIG.atmosInnerIntensity` | `0.18` | shader alpha multiplier |
| 外层大气半径系数 | `EARTH_MATERIAL_CONFIG.atmosOuterRadiusFactor` | `1.0025` | `atmosOuterGeo` |
| 外层大气分段 | `EARTH_MATERIAL_CONFIG.atmosOuterSegments` | `48` | `atmosOuterGeo` |
| 外层大气颜色 | `EARTH_MATERIAL_CONFIG.atmosOuterColor` | `[0.18, 0.45, 0.9]` | shader RGB |
| 外层大气 rim power | `EARTH_MATERIAL_CONFIG.atmosOuterRimPower` | `9.0` | shader rim |
| 外层大气强度 | `EARTH_MATERIAL_CONFIG.atmosOuterIntensity` | `0.0025` | shader alpha multiplier |
| 大气辉光 blending | inline | `THREE.AdditiveBlending` | `ShaderMaterial.blending` |
| 大气辉光 renderOrder | inline | `1` | `atmosInner/Outer.renderOrder` |
| 无高清材质边缘光颜色 | `EARTH_MATERIAL_CONFIG.rimGlowColor` | `[0.42, 0.72, 1.0]` | 高清材质隐藏或不可用时的 Fresnel shell RGB |
| 无高清材质边缘光半径系数 | `EARTH_MATERIAL_CONFIG.rimGlowRadiusFactor` | `1.0035` | `earth-rim-glow` 外扩球壳半径 |
| 无高清材质边缘光 rim power | `EARTH_MATERIAL_CONFIG.rimGlowPower` | `3.4` | shader rim 衰减;值越大边缘越窄 |
| 无高清材质边缘光强度 | `EARTH_MATERIAL_CONFIG.rimGlowIntensity` | `0.24` | shader alpha multiplier |
| 无高清材质边缘光分段 | `EARTH_MATERIAL_CONFIG.rimGlowSegments` | `96` | `earth-rim-glow` 几何分段 |
| 无高清材质边缘光 renderOrder | `EARTH_MATERIAL_CONFIG.rimGlowRenderOrder` | `1.08` | `_earthRimGlow.renderOrder` |
| 无高清材质边缘光 depthTest | inline | `false` | 避免被海陆基座或地表填充遮住 |
| 云图半径偏移 | `CLOUD_LAYER_CONFIG.radiusOffset` | `3` | 云层球半径 |
| 云图分段 | `CLOUD_LAYER_CONFIG.widthSegments / heightSegments` | `64 / 64` | 云层球几何分段 |
| 云图透明度 | `CLOUD_LAYER_CONFIG.opacity` | `0.15` | `MeshPhongMaterial.opacity` |
| 云图透明度 | `CLOUD_LAYER_CONFIG.opacity` | `0.15` | `MeshBasicMaterial.opacity` |
| 云图贴图 | `CLOUD_LAYER_CONFIG.textureUrl` | `"./assets/earth_clouds_1024.png"` | 云层贴图 |
| 云图 blending | inline | `THREE.AdditiveBlending` | `MeshPhongMaterial.blending` |
| 云图 blending | inline | `THREE.AdditiveBlending` | `MeshBasicMaterial.blending` |
## 海陆基座与国界
@@ -129,8 +120,8 @@
| 地形透明度 | `TERRAIN_CONFIG.opacity` | `0.68` | `MeshPhongMaterial.opacity` |
| 地形颜色 | `TERRAIN_CONFIG.color` | `0x8aa884` | `MeshPhongMaterial.color` |
| 地形 emissive | `TERRAIN_CONFIG.emissive` | `0x030704` | 降低自发光,恢复地形明暗层次 |
| 地形 specular | `TERRAIN_CONFIG.specular` | `0x344438` | 给地形局部光泽,不抬高高清贴图直射亮度 |
| 地形 shininess | `TERRAIN_CONFIG.shininess` | `16` | 收紧地形高光,增强起伏辨识 |
| 地形 specular | `TERRAIN_CONFIG.specular` | `0x000000` | 给地形局部光泽,不抬高高清贴图直射亮度 |
| 地形 shininess | `TERRAIN_CONFIG.shininess` | `0` | 关闭镜面高光 |
| 地形 renderOrder | inline | `1.2` | `terrain.renderOrder` |
| 地形 polygonOffset | inline | `factor -1`, `units -1` | 降低贴近球面时的闪烁 |
@@ -180,8 +171,8 @@
| 卫星真实高度压缩尺度 | `SATELLITE_CONFIG.altitudeCompressionKm` | `1200` | TLE/SGP4 高度压缩映射,数值越大高轨差异越温和 |
| 卫星真实高度上限 | `SATELLITE_CONFIG.maxDisplayAltitudeKm` | `40000` | 压缩映射的高度截断,覆盖 GEO 附近高度 |
| 卫星真实高度显示偏移范围 | `minRealAltitudeOffset / maxRealAltitudeOffset` | `4 / 25` | 压缩后映射到 `CONFIG.earthRadius + offset`;`25` 约为当前地球半径 `100` 的四分之一,用于保留高轨分层同时避免 GEO/MEO 轨迹离主体过远 |
| 卫星点基础像素大小 | `SATELLITE_CONFIG.dotBaseSize` | `2.8` | 点 shader size |
| 卫星背景点缩放 | `SATELLITE_CONFIG.dotBackdropScale` | `1.28` | 背景点大小 |
| 卫星点基础像素大小 | `SATELLITE_CONFIG.dotBaseSize` | `2.2` | 点 shader size |
| 卫星背景点缩放 | `SATELLITE_CONFIG.dotBackdropScale` | `1.4` | 背景点大小 |
| 卫星点透明度范围 | `dotOpacityMin / dotOpacityMax` | `0.42 / 1.0` | 呼吸动画 |
| 卫星点呼吸速度 | `SATELLITE_CONFIG.dotBreathingSpeed` | `0.12` | 点 opacity 动画 |
| 卫星背景点颜色 | inline | `0x0b1626` | backdrop point baseColor |
@@ -235,8 +226,8 @@ AIS 船只普通态使用批量 `THREE.Points`,不是逐船 `THREE.Sprite`。
| hover 缩放 | `COMPUTE_CENTER_CONFIG.marker.hoverScale` | `1.16` | hover overlay 尺寸倍率 |
| locked 缩放 | `COMPUTE_CENTER_CONFIG.marker.lockedScale` | `1.22` | locked overlay 尺寸倍率,并叠加 pulse |
| dimmed 缩放 / 透明度 | `dimmedScale / dimmedOpacity` | `0.82 / 0.34` | dim 状态 |
| 超算颜色 | `COMPUTE_CENTER_CONFIG.colors.supercomputer` | `"#38bdf8"` | marker texture |
| GPU 集群颜色 | `COMPUTE_CENTER_CONFIG.colors.gpu_cluster` | `"#2dd4bf"` | marker texture |
| 超算颜色 | `COMPUTE_CENTER_CONFIG.colors.supercomputer` | `"#a855f7"` | marker texture |
| GPU 集群颜色 | `COMPUTE_CENTER_CONFIG.colors.gpu_cluster` | `"#a855f7"` | marker texture |
| 关联颜色 | `COMPUTE_CENTER_CONFIG.colors.linked` | `"#f8fafc"` | 关联态 |
| 算力中心 renderOrder | local `COMPUTE_CENTER_RENDER_ORDER` | `4.5` | 地表设施低于卫星点 |
@@ -286,3 +277,30 @@ AIS 船只普通态使用批量 `THREE.Points`,不是逐船 `THREE.Sprite`。
| 星空半径范围 | `minRadius + radiusJitter` | `800 + 200` | 随机分布 |
| 星空点颜色 | `STARFIELD_CONFIG.color` | `0xffffff` | `PointsMaterial.color` |
| 星空点大小 | `STARFIELD_CONFIG.size` | `0.5` | `PointsMaterial.size` |
## 方块徽标分类与配色
| 类型 | 主色 | 内置图标 |
| --- | --- | --- |
| 数据中心/基础设施 | 青绿 `#14b8a6` → `#0d9488`,边框 `#5eead4` | 服务器机柜 |
| GPU/AI | 电紫 `#a855f7` → `#7e22ce`,边框 `#d8b4fe` | 堆叠算力层 |
| 超级计算机 | 同一电紫 | 芯片 |
| 海缆登陆点 | 琥珀 `#f59e0b`,浅金 `#fef3c7` 边圈 | 发光圆核 |
| BGP 观测站 | 蓝色及原活动热度色 | 扁平广播塔,不使用方块底板 |
| BGP 事件 | 低/中/高/严重:蓝/琥珀/橙/红 | 不规则扁平符号(三角、感叹号、波动、爆发、泄漏),不使用方块 |
| 船舶 | 货轮蓝、油轮橙、客船青绿、渔船琥珀、军舰靛紫、其他银灰 | 方块内航向箭头,停泊状态独立保留 |
| 自定义标记 | 地点绿、备注黄、告警红、默认蓝 | 地点针、备注页、告警三角 |
BGP 保持不规则扁平符号作为唯一例外;其他有限地表物件使用缓存的徽标纹理,不为每个图标新增 DOM 或独立绘制对象。船舶继续按航向分桶,以顶点色区分船型,不将船型与航向相乘扩张批次数。卫星使用参考的鲜明类别色与薄深色衬边;轨道和覆盖计算不变。“低缩放圆点”开关仍可开启,新默认关闭;渲染与拾取尺寸共同尊重开关,不再关闭后仍强制用圆点。
### 卫星统一色板
参考 [satellitemap.space](https://satellitemap.space/) 的类别色;本地 3d.html 中的模拟壳层与数量不作为项目分类依据。当前项目仍按真实轨道倾角分类:0–30° 蓝 `#3399ff`、30–60° 橙 `#ff801a`、60–90° 绿 `#00e680`、90–120° 紫 `#cc33ff`、120–180° 玫红 `#ff3366`,未知灰 `#94a3b8`。同一颗卫星跨昼夜保持同一颜色,预测轨道不再使用无关的黄紫渐变。
覆盖统一 `#3399ff`,opacity=0.34,日侧透明度增益=1.65;不再以黄色区分日面。粒子深色衬边尺寸系数=1.4、透明度=0.46,复用原有背景点批次,没有新增绘制批次。
### 选中轨道与面板轮廓
预测轨道绘制 96% 周期的开放弧线,不追加首点,端部渐隐;按累计弧长沿未来采样方向推进亮色流光,复用同一 Line 绘制。电视与通用 HUD 外壳恢复方角,播放器裁剪区域同样为方角;不改变窗口尺寸与拖拽。发布代码移除临时逐帧性能统计,不保留只用于验收的 DOM 诊断接口。
@@ -12,17 +12,17 @@
## 地表图层栈
算力专题沿用原算力中心 Interactable 图标、深度与层次顺序;国家/年份切换会替换该层数据并清除旧选中状态。专题 HUD 属于屏幕 UI,在 `main.js` 的指针排除列表中,不参与地球 picking;区域数据卡在屏幕空间由地理锚点牵引,背面不画穿球连线,设施详情复用原详情卡和移动端详情抽屉。外层大气壳保持原有实现;星空逐字节恢复到 commit `83a10a6c`,`brightStarOpacity` 为 `.88`,删除 `skyTint`/`skyBrightness`,不再校准密度和颜色。高清 overlay 使用白色 `MeshBasicMaterial`、opacity 1、`toneMapped:false`;`texture-colors.js` 统一选择 r128 的 `encoding`/`LinearTosRGB` 或 r160 的 `colorSpace`/colorspace fragment。不叠加 Phong 白光、彩色暮光、蓝色夜染、camera boost 或 shoulder 曲线。没有新增后处理、GPU draw pass 或高分辨率纹理;算力专题新增 45 个本地 SVG 旗帜资源。
算力专题沿用原算力中心 Interactable 图标、深度与层次顺序;国家/年份切换会替换该层数据并清除旧选中状态。专题 HUD 属于屏幕 UI,在 `main.js` 的指针排除列表中,不参与地球 picking;区域数据卡在屏幕空间由地理锚点牵引,背面不画穿球连线,设施详情复用原详情卡和移动端详情抽屉。高清地表由 `earth-surface-material.js` 的单次绘制 `ShaderMaterial` 负责,保持原有 R+0.48 网格、深度策略和地表拾取对象。四张 8K 底图仍由原控制器切换,成功后更新采样 uniform 并释放旧纹理,失败保留原图。法线、视线和真实太阳方向统一到世界坐标;土地哑光,海洋只有掠射角冷色反射,没有白色镜面高光。海洋区分优先复用现有海陆地理纹理,未加载时使用保守色差估计,冰雪抑制反射;关闭国界线不移除光学遮罩。原始 JPEG 不重绘、不降采样。 颜色纹理标记 sRGB 并启用 mipmaps。r128 在地表 Shader 中解码 sRGB,r160 由纹理硬件格式解码;二者在线性空间合成光照后只编码一次。局部 filmic 曲线只作用于地表,不打开全局 ACES 曝光,避免改变星空和业务图层。晨昏范围为法线点积 [-0.12, 0.28],夜面在线性色调映射后保留 0.12–0.32 光照,避免暗部被曲线再次压黑。大气收敛为 R×1.025 的一个 BackSide/Additive 壳,depthWrite=false、depthTest=true,内沿散射并入地表;云图独立开关,使用哑光昼夜材质并在 1.1 顺序绘制。星图使用已有 `starmap_deep_8k.jpg`,不加染色遮罩。
| 顺序 | 图层 | 来源 | 渲染 / 半径策略 | 深度 / 交互策略 | 备注 |
| --- | --- | --- | --- | --- | --- |
| -1000 | 天体背景 mesh | `celestial.js` | 背景球 | 不参与地表拾取 | 位于所有智能星球内容之后。 |
| -1 | 智能星球遮挡球 | `earth.js` | 地球内侧不可见球 | 写入深度 | 遮挡地球背面的对象。 |
| 0.5 | 智能星球遮挡球 | `earth.js` | 地球内侧不可见球 | 写入深度 | 遮挡地球背面的对象。 |
| 0 | 智能星球基座球 | `earth.js` | `CONFIG.earthRadius` | 地表拾取兜底目标 | 深色基座,所有可选地图层关闭时仍可见。 |
| 0.2 | 国界暗色 tint | `country-boundaries.js` | `tintAltitudeOffset` | 禁用 raycast | 高清材质关闭时使用。 |
| 0.86 | 海陆基座填充 | `country-boundaries.js` | `landAltitudeOffset = 0.32`; 海洋 `#010609`,陆地 `#080f1b` | 禁用 raycast | 即使国界线关闭,基座地图仍保持可用;半径与基座球拉开以避免远距 z-fighting。 |
| 0.96 | 高清 Earth 材质 | `earth.js` | `textureOverlayAltitudeOffset = EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET = 0.48` | 可见时作为地表拾取目标 | 高清材质始终压过海陆基座填充;半径必须高于海陆基座并与基座球保持足够间距。 |
| 1 | 大气辉光和云图 | `earth.js` | 大气 / 云层球 | 不走普通对象选择路径 | 云图由“大气云图”图层开关控制。 |
| 1 / 1.1 | 大气辉光 / 云图 | `earth.js` | 单层大气 R×1.025;云图 R+3 | 大气 BackSide、depthWrite=false、depthTest=true;保留云图开关 | 内沿光照并入高清地表,不新增全屏后处理。 |
| 1 | 海缆 / 登陆点 | `cables.js`, `cable-batches.js` | 海缆全量线段合并为一个 `LineSegments`;登陆点全量使用实例化 billboard;`renderOrder = 1`、海缆半径偏移仍为 `0.2`;登陆点锚点改为高清地表的 `0.48` | 原始 `Line` / `Sprite` 仅作为逐项拾取和选择状态对象,材质不再单独绘制;登陆点仍按球体遮挡判断背面可见性,批量材质 `depthTest: false` | 样式通过线缆样式纹理和登陆点实例属性同步;保留颜色、脉冲、尺寸、显隐与点击语义。 |
| 1.2 | 真实地形 | `earth.js`, `terrain.js` | `TERRAIN_CONFIG.baseRadiusOffset` 加地形位移 | 禁用 raycast | 地形压过高清材质;高清材质关闭时临时隐藏,重新开启后恢复原状态。 |
| 2.05 | 经纬线 | `earth.js` | `CONFIG.earthRadius + 0.14` | 禁用 raycast | 低透明度显示在高清材质上。 |
@@ -36,7 +36,7 @@
| 4.5 | 算力中心 | `compute-centers.js`, `interactable.js` | 使用 `COMPUTE_CENTER_RENDER_ORDER` 并由 `Interactable` 绘制 | 通过 `Interactable` 屏幕空间 picking,参与同坐标避让 | 地表设施层,保持在卫星下方。登陆点已下沉到海缆层。 |
| 5 | 卫星背景点 | `satellites.js` | 固定 renderOrder;默认按 TLE/SGP4 真实高度压缩到 `CONFIG.earthRadius + 4..25`,关闭真实高度或传播失败时回退到 `fallbackAltitudeOffset = 8` | 屏幕空间卫星拾取 | 位于卫星点下方。 |
| 6 | 卫星点 | `satellites.js` | 与卫星背景点使用同一压缩高度 / fallback 高度 | 屏幕空间卫星拾取 | 卫星点压过 footprint 和算力中心。 |
| 12+ | 卫星锁定 ring、halo、预测轨道 | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` 及偏移;预测轨道使用同一真实高度开关,并固定锁定时刻的地球姿态来绘制闭合惯性轨道;关闭真实高度时回到同层球面 | 卫星覆盖层路径 | 用于选中 / 锁定卫星强调。 |
| 12+ | 卫星锁定 ring、halo、预测轨道 | `satellites.js` | `SATELLITE_CONFIG.overlayRenderOrder` 及偏移;预测轨道使用同一真实高度开关,并固定锁定时刻的地球姿态来绘制 96% 周期开放惯性轨道与方向流光;关闭真实高度时回到同层球面 | 卫星覆盖层路径 | 用于选中 / 锁定卫星强调。 |
| 98-100 | 太阳 / 月亮 halo 和 sprite | `celestial.js` | 固定 renderOrder | 天体拾取禁用 | 前景天体 sprite。 |
## 全量绘制与更新约束
@@ -75,6 +75,8 @@
## 数据源采集队列
队列由 `datasource-task-queue.ts` 按独立 task ID 合并状态。同一数据源再次采集会新增一条任务,旧失败/完成/取消记录保留;仅尚未取得 task ID 的活动占位项允许按数据源绑定。迟到推送不能把终态改回进行中,旧任务轮询也不能覆盖数据源当前的新任务。任务状态按钮使用 `ListChecks`,刷新按钮仍使用 `RefreshCw`。
Admin 的数据源页把单源触发、表格勾选触发和触发全部统一接入浏览器下载列表式采集队列:
- 队列状态由 [PlainResourcePages.tsx](/home/ray/dev/linkong/planet/frontend/src/admin/pages/PlainResourcePages.tsx) 管理,只保存当前会话中的可见任务,不用 `localStorage` 伪造历史。
+10
View File
@@ -424,3 +424,13 @@ AIS 船只图例按船型显示颜色:货轮、油轮、客船、渔船、军
当前原型最多同时显示六张内容卡。主卡围绕当前选择的算力指标:大号百分比或带单位的绝对量、观测年份、历史上下文和来源入口。缺少可比数据时明确显示“暂无可比数据”;没有观测值时不绘制空趋势图。设施记录和覆盖信息仍完整保留,但移到展开后的辅助区;样本数只是证据上下文,不能当作算力值或全球覆盖率。区域预览可以显示成员数,长列表仅在需要时展开。桌面卡片约宽 268 像素,高度随内容自适应;展开卡片支持用户调整至最高 480 像素。手机手风琴单卡也保持同一占比/绝对量语义,不把设施条数提升为主数字。位置和尺寸保存于本地,并可恢复自动布局。拖动或展开后先留出阅读时间;地区随地球明显转到另一侧或上下方后,卡片才会在能减少连线交叉、绕行的情况下成组平滑换位。鼠标正在卡片上操作时不移动,手动位置不会被立即抢回,也不会永久阻止必要调整。图片、视频等内容可以沿用内容区布局,当前尚未接入这些媒体数据。空间不足时卡片可以经过球体前景移动,不再靠瞬移避让或缩成小标签。
地图卡片开关关闭时仍会加载概览摘要,打开后共享地图加载事件;新请求会取消旧请求。抽屉事件使用 `composedPath()`,即使通过 innerHTML 换节点也不会误收起当前卡片。复用共享 HUD 折叠面板动画,并尊重 reduced-motion。设施名单使用最高 240px 的内部滚动区域,名称左对齐并正常换行,每行至少保留 42px 触控高度。
## 地表与物件视觉
真实地表保留原有四种底图选择;日夜模式按太阳方向控制明暗,关闭后均匀照亮。海缆选中时沿线显示流动脉冲,登陆点使用琥珀微标;设施在近距离显示芯片图标,低缩放圆点设置继续有效。卫星仍可切换自身发光/真实地表覆盖,显示轨迹并沿既有轨道运动。BGP 告警、船舶方向、关联高亮、详情卡与移动端抽屉继续使用原有操作。
### 卫星轨道与采集任务
选中卫星后,预测轨道以开放弧线显示,线上流光表示运行方向;卫星、轨迹与覆盖投影继续同步移动。覆盖区昼夜保持蓝色,粒子和轨道按图例保持固定类别色。拖动从地球移到轮廓外仍可继续旋转,大倍率下灵敏度会减小。电视窗口使用与其他卡片一致的方角。
再次触发同一数据源会创建新任务,旧失败项留在失败分组。“任务状态”使用清单图标,与刷新操作区分。CelesTrak 在短时间内可复用有效下载缓存;重新采集仍会生成独立任务并更新采集数据。
@@ -2,6 +2,8 @@
## Windows 桌面启动器
启动窗口优先使用 Windows Terminal,并显式运行 PowerShell 7(`pwsh.exe`),不依赖 Terminal 默认配置文件。未安装 PowerShell 7 时回退到 Windows PowerShell;未安装 Terminal 时直接启动可用的 PowerShell。CMD 初始引导同样优先 PowerShell 7。普通入口请求提权,已经以管理员运行的入口也会进入新 Terminal 窗口,但不会再次请求提权;子窗口校验权限后直接执行 WSL,避免递归打开窗口。重启完成后仍保留原有 WSL shell。
首次在 Windows 文件资源管理器中打开实际项目目录,双击仓库根目录的 `planet.cmd`。它从自身位置识别 WSL 发行版和 Linux 项目目录,在 Windows 当前用户的实际桌面生成 `Planet.cmd`,随后进入正常重启流程。支持 `\\wsl$\发行版\...` 与 `\\wsl.localhost\发行版\...`;仓库位于 Windows 本地磁盘时,使用默认 WSL 发行版及 `wslpath` 映射。系统桌面位置由 Windows 获取,兼容不同用户名和 OneDrive 等桌面重定向;WSL、zsh 及项目依赖仍须先准备好。
后续双击桌面副本,使用已绑定的发行版与目录,申请原有管理员权限,并调用 `planet.sh restart --allow-lan`。不写入测试端口;默认前端 3000、后端 8000、AI Provider 8010,显式 `DEFAULT_*_PORT` 环境配置仍有效。成功后按实际 `ports.env` 端口打开 Earth,终端保留 WSL shell;失败只显示错误,不打开成功页面。源文件负责生成入口,`scripts/windows/planet-launcher.ps1` 负责 Windows 路径、桌面安装与提权,`scripts/windows/restart.zsh` 只衔接现有重启流程。
+1
View File
@@ -311,6 +311,7 @@ OTP 一次性验证码走 Redis,key 格式 `otp:{purpose}:{email}`,TTL 600
<!-- planet-error-catalog:start -->
| 错误编号 | 匹配片段(分号分隔) | 原因/已确认的故障现象 | 处理建议 |
| --- | --- | --- | --- |
| P_CELESTRAK_NOT_UPDATED | GP data has not updated since your last successful | CelesTrak 拒绝同一更新窗口的重复下载;若日志是 HEAD 200 后 GET 403,预检可能已消耗下载额度,这不表示出口不通。 | 使用不发 HEAD 的采集器版本,保留并校验原始下载缓存;无有效缓存时等待下一次 GP 更新或配置 Space-Track,避免连续重试。 |
| P_WINDOWS_LAUNCHER_TARGET_MISSING | P_WINDOWS_LAUNCHER_TARGET_MISSING | 桌面启动器绑定的 WSL 项目目录不可访问或缺少启动脚本,常见于项目移动、发行版不可用或复制旧机器的副本。 | 从当前项目目录运行仓库 planet.cmd 重新生成本机桌面副本,检查 WSL 发行版;不修改成其他电脑的固定路径。 |
| P_PROXY_EXTERNAL | PLANET_PROXY_EXTERNAL | 当前 Docker 代理由其他配置管理,或已被人工修改,不能安全自动覆盖。 | 检查 daemon.json、systemd 代理及 Planet 管理记录,确认归属后再调整;脚本保留现有配置。 |
| P_AUTH_BOOTSTRAP_MISSING | DEFAULT_LOGIN_USER_MISSING | 已确认当前后端数据库缺少默认账户,常见于跳过初始化的隔离预览。 | 核对数据库归属后运行现有默认账户初始化,不重置已有账户或清空数据库。 |
+4
View File
@@ -77,3 +77,7 @@
维护卡片数值:管理员打开“智能星球内容 → 算力对比”,先维护报告来源,再填写年度国家观测并“保存并发布”。只录入同年同口径数据,缺失国家不填,设施数量不会替代算力份额。可恢复内置默认值,地球卡片自动检查已发布配置。
在算力中心旁打开“算力态势分析”,开启“显示区域卡片”,选择地区并旋转地球。关闭配置窗会保留卡片,显示开关才控制启停。桌面卡片可调整大小、收起并查看真实历史图;点击来源或设施进入详情。手机使用底部“算力”页。国家指标与设施样本分开,“—”表示缺数据,不代表算力为零。
### 查看卫星与重试采集
在 Earth 启用卫星并选中一个粒子,可查看开放预测轨道、方向流光及受支持的覆盖投影。拖动移出球体仍会继续旋转。数据源采集失败后可重新触发;新任务独立显示,旧失败记录保留在当前任务队列的失败分组。
+3 -1
View File
@@ -16,12 +16,14 @@
## Current Version
- `main` 当前主线历史推导到:`0.16.5`
- `dev` 当前开发分支历史推导到:`0.75.1`
- `dev` 当前开发分支历史推导到:`0.75.3`
## Timeline
| Version | Type | Branch | Commit | Summary |
| --- | --- | --- | --- | --- |
| `0.75.3` | improvement | `dev` | `v0.75.3` | 地球海陆材质与可读夜侧、连续拖拽、现代徽标、卫星平滑开放轨道及流光,修复 CelesTrak 缓存与任务历史并清理废弃实现 |
| `0.75.2` | bugfix | `dev` | `v0.75.2` | Windows 启动器优先 Terminal 与 PowerShell 7,修复管理员入口分流,补齐兼容回退与提权测试 |
| `0.75.1` | improvement | `dev` | `v0.75.1` | Windows 启动器自动生成本机桌面入口,后台维护算力比较数据,恢复小球惯性与大球跟手分流并更新 agent 策略 |
| `0.75.0` | feature | `dev` | `v0.75.0` | 四图切换默认原始底图,新增算力区域态势卡片,统一空间连线与重排,优化启动和缩放拖动并补齐地理规则交付 |
| `0.74.7` | improvement | `dev` | `v0.74.7` | Docker 镜像网络故障临时回退,精简副行进度与失败显示,修复数据库端口冲突及启动重试并补齐实际验证 |
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planet-frontend",
"version": "0.75.1",
"version": "0.75.3",
"private": true,
"packageManager": "bun@1",
"dependencies": {
@@ -1,6 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#2dd4bf" viewBox="0 0 16 16">
<path fill-rule="evenodd" d="M3.904 1.777C4.978 1.289 6.427 1 8 1s3.022.289 4.096.777C13.125 2.245 14 2.993 14 4s-.875 1.755-1.904 2.223C11.022 6.711 9.573 7 8 7s-3.022-.289-4.096-.777C2.875 5.755 2 5.007 2 4s.875-1.755 1.904-2.223Z"/>
<path d="M2 6.161V7c0 1.007.875 1.755 1.904 2.223C4.978 9.71 6.427 10 8 10s3.022-.289 4.096-.777C13.125 8.755 14 8.007 14 7v-.839c-.457.432-1.004.751-1.49.972C11.278 7.693 9.682 8 8 8s-3.278-.307-4.51-.867c-.486-.22-1.033-.54-1.49-.972Z"/>
<path d="M2 9.161V10c0 1.007.875 1.755 1.904 2.223C4.978 12.711 6.427 13 8 13s3.022-.289 4.096-.777C13.125 11.755 14 11.007 14 10v-.839c-.457.432-1.004.751-1.49.972-1.232.56-2.828.867-4.51.867s-3.278-.307-4.51-.867c-.486-.22-1.033-.54-1.49-.972Z"/>
<path d="M2 12.161V13c0 1.007.875 1.755 1.904 2.223C4.978 15.711 6.427 16 8 16s3.022-.289 4.096-.777C13.125 14.755 14 14.007 14 13v-.839c-.457.432-1.004.751-1.49.972-1.232.56-2.828.867-4.51.867s-3.278-.307-4.51-.867c-.486-.22-1.033-.54-1.49-.972Z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" color="white"><g fill="currentColor"><path d="M64 17L110 40L64 63L18 40Z"/><path d="M18 57L64 80L110 57V72L64 95L18 72Z"/><path d="M18 88L64 111L110 88V101L64 124L18 101Z"/></g></svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

After

Width:  |  Height:  |  Size: 271 B

@@ -1,3 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#f8fafc" viewBox="0 0 16 16">
<path d="M2 2a2 2 0 0 0-2 2v1a2 2 0 0 0 2 2h5.5v3A1.5 1.5 0 0 0 6 11.5H.5a.5.5 0 0 0 0 1H6A1.5 1.5 0 0 0 7.5 14h1a1.5 1.5 0 0 0 1.5-1.5h5.5a.5.5 0 0 0 0-1H10A1.5 1.5 0 0 0 8.5 10V7H14a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H2zm.5 3a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1zm2 0a.5.5 0 1 1 0-1 .5.5 0 0 1 0 1z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" color="white"><g fill="none" stroke="currentColor" stroke-width="7" stroke-linejoin="round"><rect x="27" y="14" width="74" height="100" rx="9"/><path d="M27 47H101M27 80H101M61 31H87M61 64H87M61 97H87"/></g><g fill="currentColor"><circle cx="43" cy="31" r="4"/><circle cx="43" cy="64" r="4"/><circle cx="43" cy="97" r="4"/></g></svg>

Before

Width:  |  Height:  |  Size: 399 B

After

Width:  |  Height:  |  Size: 421 B

@@ -1,3 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="#38bdf8" class="bi bi-buildings-fill" viewBox="0 0 16 16">
<path d="M15 .5a.5.5 0 0 0-.724-.447l-8 4A.5.5 0 0 0 6 4.5v3.14L.342 9.526A.5.5 0 0 0 0 10v5.5a.5.5 0 0 0 .5.5h9a.5.5 0 0 0 .5-.5V14h1v1.5a.5.5 0 0 0 .5.5h3a.5.5 0 0 0 .5-.5V.5ZM2 11h1v1H2v-1Zm2 0h1v1H4v-1Zm-1 2v1H2v-1h1Zm1 0h1v1H4v-1Zm9-10v1h-1V3h1ZM8 5h1v1H8V5Zm1 2v1H8V7h1ZM8 9h1v1H8V9Zm2 0h1v1h-1V9Zm-1 2v1H8v-1h1Zm1 0h1v1h-1v-1Zm3-2v1h-1V9h1Zm-1 2h1v1h-1v-1Zm-2-4h1v1h-1V7Zm3 0v1h-1V7h1Zm-2-2v1h-1V5h1Zm1 0h1v1h-1V5Z"/>
</svg>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" color="white"><g fill="none" stroke="currentColor" stroke-width="8" stroke-linejoin="round"><rect x="27" y="27" width="74" height="74" rx="9"/><rect x="46" y="46" width="36" height="36" rx="3"/><path d="M45 9V27M64 9V27M83 9V27M45 101V119M64 101V119M83 101V119M9 45H27M9 64H27M9 83H27M101 45H119M101 64H119M101 83H119"/></g></svg>

Before

Width:  |  Height:  |  Size: 562 B

After

Width:  |  Height:  |  Size: 418 B

@@ -1,10 +1,6 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="100 50 600 680">
<!-- Location pin with circular cutout. Coordinates in 1000-unit space (canvas scale: size/1000). -->
<!-- States: color via fill attribute — default white for 3D canvas, orange (#ffaa00) for normal, white for hover/locked -->
<path
fill-rule="evenodd"
fill="currentColor"
d="M400 704 C386 704 375 697 367 684 L173 378 C117 290 144 173 229 111 C278 75 337 57 400 57 C463 57 522 75 571 111 C656 173 683 290 627 378 L433 684 C425 697 414 704 400 704 Z
M400 320 m-86 0 a86 86 0 1 0 172 0 a86 86 0 1 0 -172 0"
/>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128" color="white">
<defs><radialGradient id="halo"><stop offset="0.55" stop-color="currentColor" stop-opacity="0.28"/><stop offset="1" stop-color="currentColor" stop-opacity="0"/></radialGradient></defs>
<circle cx="64" cy="64" r="60" fill="url(#halo)"/>
<circle cx="64" cy="64" r="34" fill="currentColor"/>
<circle cx="64" cy="64" r="34" fill="none" stroke="currentColor" stroke-width="7"/>
</svg>

Before

Width:  |  Height:  |  Size: 611 B

After

Width:  |  Height:  |  Size: 490 B

+4 -4
View File
@@ -25,10 +25,10 @@
--hud-title-size: calc(1.02rem * var(--hud-scale));
--hud-panel-header-title-size: calc(0.82rem * var(--hud-scale));
--hud-kicker-size: calc(0.68rem * var(--hud-scale));
--hud-surface-top: rgba(17, 31, 53, 0.84);
--hud-surface-bottom: rgba(7, 17, 31, 0.76);
--hud-surface-top: rgba(10, 23, 37, 0.92);
--hud-surface-bottom: rgba(5, 13, 24, 0.88);
--hud-surface-overlay: rgba(157, 204, 255, 0.07);
--hud-border: rgba(201, 225, 247, 0.14);
--hud-border: rgba(124, 190, 218, 0.18);
--hud-border-hover: rgba(226, 238, 250, 0.24);
--hud-border-active: rgba(235, 244, 255, 0.32);
--hud-shadow: 0 18px 46px rgba(1, 7, 16, 0.34);
@@ -38,7 +38,7 @@
--hud-title: #dbe8f5;
--hud-text: #eef4fb;
--hud-text-muted: #8ea3ba;
--hud-text-soft: #6f849b;
--hud-text-soft: #a0b5c7;
--hud-accent: #91baff;
--hud-accent-strong: #d7e8ff;
--glass-fill-top: rgba(255, 255, 255, 0.08);
+19 -8
View File
@@ -9,10 +9,11 @@
position: absolute;
overflow: hidden;
isolation: isolate;
border-radius: 0;
background:
radial-gradient(circle at var(--panel-glow-x) var(--panel-glow-y), rgba(255, 255, 255, calc(0.08 + var(--panel-glow-opacity))), transparent 30%),
radial-gradient(circle at var(--panel-glow-x) var(--panel-glow-y), rgba(91, 190, 230, calc(0.025 + var(--panel-glow-opacity) * 0.25)), transparent 45%),
radial-gradient(circle at 86% 115%, rgba(145, 186, 255, 0.08), transparent 36%),
linear-gradient(180deg, rgba(255, 255, 255, 0.05), transparent 26%),
linear-gradient(180deg, rgba(145, 211, 240, 0.025), transparent 26%),
linear-gradient(180deg, var(--hud-surface-top), var(--hud-surface-bottom));
border: 1px solid var(--hud-border);
box-shadow:
@@ -21,8 +22,8 @@
var(--hud-shadow),
0 0 0 1px rgba(255, 255, 255, 0.02),
0 0 20px rgba(123, 176, 236, calc(0.04 + var(--panel-glow-opacity) * 0.32));
backdrop-filter: blur(18px) saturate(125%);
-webkit-backdrop-filter: blur(18px) saturate(125%);
backdrop-filter: blur(12px) saturate(115%);
-webkit-backdrop-filter: blur(12px) saturate(115%);
transition:
background 0.22s ease,
border-color 0.22s ease,
@@ -36,7 +37,7 @@
border-radius: inherit;
background:
linear-gradient(180deg, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.02) 58%, transparent 100%);
opacity: 0.52;
opacity: 0.16;
pointer-events: none;
transform:
perspective(240px)
@@ -83,7 +84,7 @@
}
.hud-panel:hover:not(.is-dragging)::before {
opacity: 0.6;
opacity: 0.23;
}
.hud-panel:hover:not(.is-dragging)::after {
@@ -2566,8 +2567,8 @@ label.is-disabled.earth-mobile-settings-card {
.earth-tooltip {
position: absolute;
background:
linear-gradient(180deg, rgba(21, 37, 61, 0.96), rgba(8, 18, 31, 0.95));
border: 1px solid rgba(214, 230, 247, 0.14);
linear-gradient(180deg, rgba(10, 27, 43, 0.97), rgba(5, 15, 28, 0.96));
border: 1px solid rgba(90, 196, 228, 0.32);
border-radius: 10px;
padding: 8px 12px;
font-size: 0.78rem;
@@ -2577,6 +2578,16 @@ label.is-disabled.earth-mobile-settings-card {
box-shadow: var(--hud-shadow-soft);
display: none;
user-select: none;
animation: earth-tooltip-reveal 0.2s cubic-bezier(0.16, 1, 0.3, 1) both;
}
@keyframes earth-tooltip-reveal {
from { opacity: 0; transform: translateX(-6px); }
to { opacity: 1; transform: translateX(0); }
}
@media (prefers-reduced-motion: reduce) {
.earth-tooltip { animation: none; }
}
.earth-search-modal {
+1 -1
View File
@@ -217,7 +217,7 @@
position: relative;
flex: 1 1 auto;
min-height: calc(220px * var(--hud-scale));
border-radius: calc(16px * var(--hud-scale));
border-radius: 0;
overflow: hidden;
border: 1px solid rgba(201, 225, 247, 0.1);
background:
+32 -4
View File
@@ -1,4 +1,5 @@
import * as THREE from "three";
import { CABLE_CONFIG } from "./constants.js";
const CABLE_STYLE_TEXTURE_MAX_WIDTH = 1024;
@@ -24,6 +25,7 @@ export function createCableLineBatch(lines) {
count + Math.max(0, line.geometry.attributes.position.count - 1) * 2, 0);
const positions = new Float32Array(vertexCount * 3);
const styleIndices = new Float32Array(vertexCount);
const progress = new Float32Array(vertexCount);
const width = Math.min(lines.length, CABLE_STYLE_TEXTURE_MAX_WIDTH);
const height = Math.ceil(lines.length / width);
const styles = new Float32Array(width * height * 4);
@@ -32,12 +34,19 @@ export function createCableLineBatch(lines) {
let cursor = 0;
lines.forEach((line, index) => {
const source = line.geometry.attributes.position;
const distances = new Float32Array(source.count);
for (let i = 1; i < source.count; i++) {
distances[i] = distances[i - 1] + Math.hypot(source.getX(i) - source.getX(i - 1),
source.getY(i) - source.getY(i - 1), source.getZ(i) - source.getZ(i - 1));
}
const totalDistance = distances[source.count - 1] || 1;
for (let segment = 0; segment < source.count - 1; segment += 1) {
for (const endpoint of [segment, segment + 1]) {
positions[cursor * 3] = source.getX(endpoint);
positions[cursor * 3 + 1] = source.getY(endpoint);
positions[cursor * 3 + 2] = source.getZ(endpoint);
styleIndices[cursor] = index;
progress[cursor] = distances[endpoint] / totalDistance;
cursor += 1;
}
}
@@ -48,30 +57,44 @@ export function createCableLineBatch(lines) {
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("styleIndex", new THREE.BufferAttribute(styleIndices, 1));
geometry.setAttribute("progress", new THREE.BufferAttribute(progress, 1));
const material = new THREE.ShaderMaterial({
uniforms: {
styles: { value: styleTexture },
styleSize: { value: new THREE.Vector2(width, height) },
uTime: { value: 0 },
},
transparent: true,
depthTest: true,
depthWrite: true,
depthWrite: false,
vertexShader: `
uniform sampler2D styles;
uniform vec2 styleSize;
attribute float styleIndex;
attribute float progress;
varying vec4 vStyle;
varying float vProgress;
void main() {
vec2 uv = (vec2(mod(styleIndex, styleSize.x), floor(styleIndex / styleSize.x)) + 0.5) / styleSize;
vStyle = texture2D(styles, uv);
vProgress = progress;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
varying vec4 vStyle;
varying float vProgress;
uniform float uTime;
void main() {
if (vStyle.a <= 0.0) discard;
gl_FragColor = vStyle;
float alpha = abs(vStyle.a);
if (alpha <= 0.0) discard;
vec3 color = vStyle.rgb;
if (vStyle.a < 0.0) {
float pulse = smoothstep(0.6, 1.0, fract(vProgress * ${CABLE_CONFIG.visual.pulseRepeats.toFixed(1)} - uTime * ${CABLE_CONFIG.visual.pulseSpeed.toFixed(1)}));
color = mix(vec3(0.3, 0.8, 1.0), vec3(0.7, 1.0, 1.0), pulse);
alpha = max(alpha, 0.8 + pulse * 0.2);
}
gl_FragColor = vec4(color, alpha);
}
`,
});
@@ -80,11 +103,12 @@ export function createCableLineBatch(lines) {
object.name = "cable-line-batch";
object.renderOrder = lines[0].renderOrder;
object.onBeforeRender = () => {
material.uniforms.uTime.value = performance.now() * 0.001;
let changed = false;
lines.forEach((line, index) => {
const { color, opacity } = line.material;
const offset = index * 4;
const alpha = line.visible ? opacity : 0;
const alpha = line.visible ? opacity * (line.material.userData.cableSelected ? -1 : 1) : 0;
if (styles[offset] !== Math.fround(color.r) || styles[offset + 1] !== Math.fround(color.g)
|| styles[offset + 2] !== Math.fround(color.b) || styles[offset + 3] !== Math.fround(alpha)) {
styles[offset] = color.r;
@@ -145,6 +169,10 @@ export function createLandingPointBatch(markers, texture) {
varying vec4 vStyle;
void main() {
vec4 color = texture2D(map, vUv) * vStyle;
float radius = distance(vUv, vec2(0.5));
float border = smoothstep(0.242, 0.254, radius) * (1.0 - smoothstep(0.283, 0.296, radius));
float brightness = max(vStyle.r, max(vStyle.g, vStyle.b));
color.rgb = mix(color.rgb, vec3(1.0, 0.953, 0.78) * brightness, border);
if (color.a < 0.01) discard;
gl_FragColor = color;
}
+9 -50
View File
@@ -3,6 +3,7 @@
import * as THREE from "three";
import { createCableLineBatch, createLandingPointBatch } from "./cable-batches.js";
import { earthSurfacePoint } from "./earth-surface.js";
import { configureColorTexture } from "./texture-colors.js";
import {
CONFIG,
@@ -36,7 +37,6 @@ const LANDING_POINT_SPRITE_ASPECT = 1;
const LANDING_POINT_SIZE_REFERENCE_FOV = 75;
const LANDING_POINT_SIZE_SCALE_MIN = 0.16;
const LANDING_POINT_SIZE_SCALE_MAX = 3;
const LANDING_POINT_ATLAS_CELL_SIZE = 128;
let landingPointTexture = null;
function getLandingPointPulse() {
@@ -56,57 +56,14 @@ function getLandingPointDimColor() {
return `#${color.getHexString()}`;
}
function createLandingPointBallTexture() {
const canvas = document.createElement("canvas");
canvas.width = LANDING_POINT_ATLAS_CELL_SIZE;
canvas.height = LANDING_POINT_ATLAS_CELL_SIZE;
const context = canvas.getContext("2d");
const center = LANDING_POINT_ATLAS_CELL_SIZE / 2;
const radius = 46;
context.clearRect(0, 0, canvas.width, canvas.height);
const shadow = context.createRadialGradient(
center - 16,
center - 18,
8,
center,
center,
radius,
);
shadow.addColorStop(0, "rgba(255, 255, 255, 1)");
shadow.addColorStop(0.48, "rgba(238, 238, 238, 0.98)");
shadow.addColorStop(0.82, "rgba(178, 178, 178, 0.94)");
shadow.addColorStop(1, "rgba(92, 92, 92, 0.88)");
context.beginPath();
context.arc(center, center, radius, 0, Math.PI * 2);
context.fillStyle = shadow;
context.fill();
context.beginPath();
context.ellipse(center - 14, center - 18, 14, 9, -0.45, 0, Math.PI * 2);
context.fillStyle = "rgba(255, 255, 255, 0.38)";
context.fill();
context.beginPath();
context.arc(center, center, radius - 1, 0, Math.PI * 2);
context.strokeStyle = "rgba(255, 255, 255, 0.24)";
context.lineWidth = 2;
context.stroke();
const texture = new THREE.CanvasTexture(canvas);
texture.colorSpace = THREE.SRGBColorSpace;
texture.generateMipmaps = false;
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.needsUpdate = true;
return texture;
}
async function getLandingPointTexture() {
if (landingPointTexture) return landingPointTexture;
landingPointTexture = createLandingPointBallTexture();
const source = new URL("../assets/icons/marker-landing-point.svg", import.meta.url).href;
landingPointTexture = await new THREE.TextureLoader().loadAsync(source);
configureColorTexture(landingPointTexture);
landingPointTexture.generateMipmaps = false;
landingPointTexture.minFilter = THREE.LinearFilter;
landingPointTexture.magFilter = THREE.LinearFilter;
return landingPointTexture;
}
@@ -192,6 +149,8 @@ function getCableColor(properties) {
function createCableLine(points, color, properties) {
if (points.length < 2) return null;
color = new THREE.Color(CABLE_CONFIG.visual.normalTint)
.lerp(new THREE.Color(color), CABLE_CONFIG.visual.sourceColorWeight).getHex();
const lineGeometry = new THREE.BufferGeometry().setFromPoints(points);
lineGeometry.computeBoundingSphere();
+1
View File
@@ -205,6 +205,7 @@ function createSkySphere() {
opacity: CELESTIAL_CONFIG.skyOpacity,
depthWrite: false,
depthTest: false,
toneMapped: false,
fog: false,
});
+3 -1
View File
@@ -10,7 +10,7 @@ import { latLonToVector3 } from "./utils.js";
const COMPUTE_CENTER_RENDER_ORDER = 4.5;
const COMPUTE_CENTER_POINT_SIZE = 36;
const COMPUTE_CENTER_ICON_FIT_SIZE = 60;
const COMPUTE_CENTER_ICON_FIT_SIZE = 100;
const COMPUTE_CENTER_ATLAS_CELL_SIZE = 128;
const COMPUTE_CENTER_ICON_SOURCES = {
supercomputer: new URL("../assets/icons/compute-supercomputer.svg", import.meta.url).href,
@@ -191,6 +191,8 @@ const computeCenterIconLayer = createInteractableLayer({
amplitude: COMPUTE_CENTER_CONFIG.marker.pulseAmplitude,
},
icon: {
colorable: false,
badge: ({ marker, item }) => ({ color: COMPUTE_CENTER_CONFIG.colors[marker?.userData?.site_type || item?.site_type] || "#14b8a6" }),
coordinates: "canvas",
fitSize: COMPUTE_CENTER_ICON_FIT_SIZE,
glowBlur: 16,
+57 -45
View File
@@ -120,7 +120,7 @@ export const CELESTIAL_CONFIG = {
updateIntervalMs: 10_000,
skyRadius: 2600,
skyOpacity: 1,
starMapUrl: "./assets/celestial/starmap_equatorial_4k.jpg",
starMapUrl: "./assets/celestial/starmap_deep_8k.jpg",
brightStarsUrl: "./assets/celestial/bright-stars.json",
orientationEulerRad: {
x: 0.46,
@@ -208,8 +208,8 @@ export const TERRAIN_CONFIG = {
opacity: 0.68,
color: 0x8aa884,
emissive: 0x030704,
specular: 0x344438,
shininess: 16,
specular: 0x000000,
shininess: 0,
urlTemplate:
"/api/v1/visualization/terrain/terrarium/{z}/{x}/{y}.png",
batchUrl: "/api/v1/visualization/terrain/terrarium/batch",
@@ -291,12 +291,12 @@ export const VESSEL_CONFIG = {
dimmedOpacity: 0.26,
},
colors: {
cargo: "#4A90D9",
tanker: "#E85D04",
passenger: "#06D6A0",
fishing: "#FFD166",
military: "#73797E",
other: "#9B9B9B",
cargo: "#38bdf8",
tanker: "#f97316",
passenger: "#14b8a6",
fishing: "#f59e0b",
military: "#818cf8",
other: "#94a3b8",
},
sizeStabilization: {
min: 0.1,
@@ -329,8 +329,9 @@ export const COMPUTE_CENTER_CONFIG = {
pulseAmplitude: 0.03,
},
colors: {
supercomputer: "#38bdf8",
gpu_cluster: "#2dd4bf",
supercomputer: "#a855f7",
gpu_cluster: "#a855f7",
infrastructure: "#14b8a6",
linked: "#f8fafc",
},
sizeStabilization: {
@@ -349,6 +350,13 @@ export const CABLE_COLORS = {
};
export const CABLE_CONFIG = {
visual: {
normalTint: 0x328ebc,
sourceColorWeight: 0.38,
normalOpacity: 0.7,
pulseRepeats: 6,
pulseSpeed: 4.5,
},
lockedOpacityMin: 0.2,
lockedOpacityMax: 1.0,
otherOpacity: 0.5,
@@ -365,7 +373,7 @@ export const CABLE_CONFIG = {
},
landingPoint: {
altitudeOffset: EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET,
color: 0xffaa00,
color: 0xf59e0b,
opacity: 1.0,
renderOrder: 1,
},
@@ -403,9 +411,13 @@ export const SATELLITE_CONFIG = {
maxRealAltitudeOffset: 25,
frontFacingDotThreshold: 0.015,
overlayRenderOrder: 12,
dotBaseSize: 2.8,
dotBackdropScale: 1.28,
dotZoomScalePower: 1,
dotBaseSize: 2.2,
dotBackdropScale: 1.4,
dotOutlineOpacity: 0.46,
footprintColor: 0x3399ff,
footprintOpacity: 0.34,
footprintDayVisibilityBoost: 1.65,
dotZoomScalePower: 0.55,
ringSize: 0.07,
apiPath: '/api/v1/visualization/geo/satellites',
breathingSpeed: 0.036,
@@ -414,7 +426,7 @@ export const SATELLITE_CONFIG = {
breathingOpacityMax: 0.9,
dotBreathingSpeed: 0.12,
dotBreathingScaleAmplitude: 0.28,
dotOpacityMin: 0.42,
dotOpacityMin: 0.72,
dotOpacityMax: 1.0
};
@@ -448,10 +460,10 @@ export const BGP_CONFIG = {
lockedMax: 1.0
},
severityColors: {
critical: 0xff4d4f,
high: 0xff9f43,
medium: 0xffd166,
low: 0x4dabf7
critical: 0xf43f5e,
high: 0xf97316,
medium: 0xf59e0b,
low: 0x38bdf8
},
severityScales: {
critical: 1.18,
@@ -544,42 +556,42 @@ export const EARTH_MATERIAL_CONFIG = {
// Base sphere sits below the country fill and high-res texture overlays.
// Keep it dark so a delayed overlay never flashes or reads as a white layer.
color: 0x010609,
specular: 0x1a2d45,
shininess: 12,
specular: 0x000000,
shininess: 0,
emissive: 0x010609,
opacity: 1,
textureOverlayAltitudeOffset: EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET,
textureWidthSegments: 128,
textureHeightSegments: 128,
textureOverlayOpacity: 1,
textureOverlayRenderOrder: 0.96,
// Depth-mask occluder keeps far-side objects hidden behind the earth
occluderRadiusFactor: 0.999,
occluderSegments: 48,
// Fresnel atmosphere glow — inner rim
atmosInnerRadiusFactor: 1.01,
atmosInnerSegments: 64,
atmosInnerColor: [0.38, 0.60, 0.84],
atmosInnerRimPower: 3.2,
atmosInnerIntensity: 0.10,
// Fresnel atmosphere glow — outer corona
atmosOuterRadiusFactor: 1.025,
atmosOuterSegments: 48,
atmosOuterColor: [0.32, 0.52, 0.74],
atmosOuterRimPower: 6.0,
atmosOuterIntensity: 0.08,
atmosOuterEdgeFeather: 0.14,
// Subtle Fresnel edge cue shown when the high-res texture is hidden or unavailable.
rimGlowColor: [0.42, 0.72, 1.0],
rimGlowRadiusFactor: 1.0035,
rimGlowPower: 3.4,
rimGlowIntensity: 0.24,
rimGlowSegments: 96,
rimGlowRenderOrder: 1.08,
surface: {
exposure: 0.9,
landSaturation: 0.9,
oceanAbsorption: 0.36,
oceanDeepColor: [0.004, 0.012, 0.032],
// Independent night-side texture contrast and cool ambient, in linear RGB.
night: {
detailGamma: 0.55,
landTint: [0.07, 0.075, 0.08],
landAmbient: [0.003, 0.005, 0.008],
oceanTint: [0.008, 0.016, 0.024],
oceanAmbient: [0.0015, 0.004, 0.012],
},
terminator: [-0.075, 0.16],
oceanReflection: [0.025, 0.12, 0.32],
atmosphereColor: [0.08, 0.28, 0.65],
innerRimStrength: 0.28,
},
atmosphere: {
radiusFactor: 1.025,
color: [0.18, 0.48, 0.88],
strength: 0.65,
},
dayNight: {
enabled: true,
+1 -10
View File
@@ -1574,7 +1574,7 @@ function cloneEarthSettings(settings) {
satelliteRealAltitudeEnabled:
settings.shared.satelliteRealAltitudeEnabled !== false,
interactableCompactDotsEnabled:
settings.shared.interactableCompactDotsEnabled !== false,
settings.shared.interactableCompactDotsEnabled === true,
surfaceHoverInfoMode: normalizeSurfaceHoverInfoMode(
settings.shared.surfaceHoverInfoMode,
),
@@ -4303,15 +4303,6 @@ function resetAllShortcutBindings() {
showStatusMessage(earthMessage("status.shortcutsReset"), "info");
}
function moveCruiseRegionInOrder(region, targetRegion) {
if (!region || !targetRegion || region === targetRegion) return;
const currentOrder = getCruiseRegionOrder().filter((item) => item !== region);
const targetIndex = currentOrder.indexOf(targetRegion);
if (targetIndex < 0) return;
currentOrder.splice(targetIndex, 0, region);
setCruiseRegionOrder(currentOrder);
}
function getCruiseRegionOrderRows(list) {
if (!(list instanceof HTMLElement)) return [];
return Array.from(list.querySelectorAll("[data-cruise-region-order-item]")).filter(
+3 -20
View File
@@ -5,6 +5,7 @@ import Pbf from "pbf";
import { CONFIG, COUNTRY_BOUNDARY_CONFIG } from "./constants.js";
import { screenToEarthCoords, vector3ToLatLon } from "./utils.js";
import { appendSurfaceSegments } from "./earth-surface.js";
import { setEarthLandMask } from "./earth.js";
// ─── Module state ──────────────────────────────────────────────────────────────
let _earthObj = null;
@@ -401,16 +402,6 @@ function setActiveTileKeys(nextKeys) {
});
}
function tileUrlForKey(key) {
const [kind, z, x, y] = key.split("/");
const prefix = COUNTRY_BOUNDARY_CONFIG.tileBasePath.replace(/\/?$/, "/");
const versionSuffix = _tileAssetVersion ? `?v=${encodeURIComponent(_tileAssetVersion)}` : "";
if (kind === "claim") {
return `${prefix}china-claims/${z}/${x}/${y}.geojson${versionSuffix}`;
}
return `${prefix}${z}/${x}/${y}.geojson${versionSuffix}`;
}
function versionedBoundaryAssetUrl(path) {
const url = new URL(path, COUNTRY_BOUNDARY_CONFIG.tileBasePath);
if (_tileAssetVersion) url.searchParams.set("v", _tileAssetVersion);
@@ -487,16 +478,6 @@ async function loadPmtilesMvtFeatures(key) {
return features;
}
async function loadDebugGeojsonFeatures(key) {
const resp = await fetch(tileUrlForKey(key));
if (!resp.ok) {
if (resp.status === 404) return [];
throw new Error(`boundary tile ${key} HTTP ${resp.status}`);
}
const payload = await resp.json();
return (payload.features || []).filter(f => f.geometry);
}
async function loadBoundaryTile(key) {
if (_tileCache.has(key)) {
touchTileKey(key);
@@ -1028,6 +1009,7 @@ export async function loadCountryBoundaries() {
const coastlineFeatures = baseFeatures.filter(isStandaloneCoastlineFeature);
_landTexture = buildLandTexture(_features);
setEarthLandMask(_landTexture, OCEAN_HEX, COUNTRY_BOUNDARY_CONFIG.landColor);
_landMesh = makeLandMesh(_landTexture);
_earthObj.add(_landMesh);
@@ -1245,6 +1227,7 @@ export function clearCountryBoundaryData() {
disposeObj(_claimGroup);
disposeObj(_landMesh);
disposeObj(_tintMesh);
setEarthLandMask(null);
_landTexture?.dispose?.();
_tileCache.forEach(entry => disposeTileObject(entry.object));
_tileCache.clear();
+22 -12
View File
@@ -37,22 +37,30 @@ function normalizeInteractableItem(item) {
};
}
function drawInteractableIcon(context, { glow = false, color = "#7dd3fc" }) {
if (glow) {
context.shadowColor = color;
context.shadowBlur = 16;
}
function drawInteractableIcon(context, { marker, color = "#7dd3fc" }) {
const kind = marker?.userData?.kind || "default";
context.strokeStyle = color;
context.fillStyle = color;
context.strokeStyle = "rgba(8, 15, 27, 0.92)";
context.lineWidth = 7;
context.lineCap = "round";
context.lineJoin = "round";
context.beginPath();
context.arc(0, 0, 27, 0, Math.PI * 2);
context.fill();
if (kind === "note") {
context.roundRect(-27, -34, 54, 68, 6);
context.moveTo(-14, -16); context.lineTo(14, -16);
context.moveTo(-14, 0); context.lineTo(14, 0);
context.moveTo(-14, 16); context.lineTo(6, 16);
} else if (kind === "alert") {
context.moveTo(0, -34); context.lineTo(34, 28); context.lineTo(-34, 28); context.closePath();
context.moveTo(0, -13); context.lineTo(0, 6);
context.moveTo(0, 17); context.lineTo(0, 18);
} else {
context.moveTo(0, 36);
context.bezierCurveTo(-49, -6, -29, -35, 0, -35);
context.bezierCurveTo(29, -35, 49, -6, 0, 36);
context.moveTo(11, -10); context.arc(0, -10, 11, 0, Math.PI * 2);
}
context.stroke();
context.fillStyle = "rgba(255,255,255,0.95)";
context.beginPath();
context.arc(0, 0, 9, 0, Math.PI * 2);
context.fill();
}
const earthInteractableLayer = createInteractableLayer({
@@ -81,6 +89,7 @@ const earthInteractableLayer = createInteractableLayer({
},
avoidance: SURFACE_AVOIDANCE_PROFILES.city,
icon: {
badge: true,
draw: drawInteractableIcon,
},
getPosition: (item) => ({
@@ -88,6 +97,7 @@ const earthInteractableLayer = createInteractableLayer({
longitude: item.longitude,
}),
getKind: (item) => item.kind || "default",
getBucketKey: (marker) => marker.userData.kind || "default",
getUserData: (item) => ({
...item,
type: "earth_interactable",
@@ -1,7 +1,7 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import { applyEarthDayNightShader } from "./earth.js";
import { CELESTIAL_CONFIG, EARTH_MATERIAL_CONFIG } from "./constants.js";
import { CELESTIAL_CONFIG } from "./constants.js";
import { configureColorTexture, preserveTextureOutput } from "./texture-colors.js";
function basicShader(legacy = false) {
@@ -27,10 +27,9 @@ for (const legacy of [false, true]) {
});
}
test("color maps are sRGB and the surface does not blend the dark base into the image", () => {
test("color maps are sRGB without a legacy sky tint", () => {
const texture = new THREE.Texture();
configureColorTexture(texture);
expect(texture.colorSpace).toBe(THREE.SRGBColorSpace);
expect(EARTH_MATERIAL_CONFIG.textureOverlayOpacity).toBe(1);
expect(CELESTIAL_CONFIG.skyTint).toBeUndefined();
});
@@ -0,0 +1,168 @@
import * as THREE from "three";
// ShaderMaterial does not apply output conversion automatically. r128 samples
// encoded color textures; modern Three uploads them using the sRGB GPU format.
const LEGACY_TEXTURE_ENCODING = !THREE.SRGBColorSpace;
const COLOR_PIPELINE = `
vec3 surfaceLinear(vec3 color) {
return mix(color / 12.92, pow((color + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), color));
}
vec3 surfaceSRGB(vec3 color) {
color = max(color, vec3(0.0));
return mix(color * 12.92, 1.055 * pow(color, vec3(1.0 / 2.4)) - 0.055, step(vec3(0.0031308), color));
}
vec3 surfaceToneMap(vec3 color) {
// Bounded filmic shoulder, local to Earth so sky and data colors stay stable.
return clamp((color * (2.51 * color + 0.03)) / (color * (2.43 * color + 0.59) + 0.14), 0.0, 1.0);
}
`;
export const SURFACE_VERTEX_SHADER = `
varying vec2 vUv;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
void main() {
vUv = uv;
vec4 worldPosition = modelMatrix * vec4(position, 1.0);
vWorldPosition = worldPosition.xyz;
// normalMatrix handles parent transforms; move its view-space result back
// to world space without assuming the camera is at the origin.
vWorldNormal = normalize(vec3(normalize(normalMatrix * normal) * mat3(viewMatrix)));
gl_Position = projectionMatrix * viewMatrix * worldPosition;
}
`;
export const SURFACE_FRAGMENT_SHADER = `
uniform sampler2D uDayMap;
uniform sampler2D uLandMask;
uniform float uLandMaskAvailable;
uniform vec3 uMaskOcean;
uniform vec3 uMaskLand;
uniform vec3 uSunDirectionWorld;
uniform float uDayNightEnabled;
uniform float uExposure;
uniform float uOceanAbsorption;
uniform vec3 uOceanDeepColor;
uniform float uLandSaturation;
uniform float uNightDetailGamma;
uniform vec3 uNightLandTint;
uniform vec3 uNightLandAmbient;
uniform vec3 uNightOceanTint;
uniform vec3 uNightOceanAmbient;
uniform vec2 uTerminator;
uniform vec3 uOceanReflection;
uniform vec3 uAtmosphereColor;
uniform float uInnerRimStrength;
varying vec2 vUv;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
${COLOR_PIPELINE}
void main() {
vec3 source = texture2D(uDayMap, vUv).rgb;
#ifdef LEGACY_TEXTURE_ENCODING
source = surfaceLinear(source);
#endif
vec3 normal = normalize(vWorldNormal);
vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float sunFacing = dot(normal, normalize(uSunDirectionWorld));
float daylight = mix(1.0, smoothstep(uTerminator.x, uTerminator.y, sunFacing), uDayNightEnabled);
float luminance = dot(source, vec3(0.2126, 0.7152, 0.0722));
// Until geography is ready use a conservative blue-chroma estimate. Once
// available the shared geographic mask is independent of the chosen map.
float ocean = smoothstep(0.015, 0.12, source.b - max(source.r, source.g));
if (uLandMaskAvailable > 0.5) {
vec3 mask = texture2D(uLandMask, vUv).rgb;
vec3 range = uMaskLand - uMaskOcean;
ocean = 1.0 - clamp(dot(mask - uMaskOcean, range) / max(dot(range, range), 0.00001), 0.0, 1.0);
}
// Ice retains its source appearance, even over ocean polygons.
ocean *= 1.0 - smoothstep(0.45, 0.8, min(source.r, min(source.g, source.b)));
vec3 land = mix(vec3(luminance), source, uLandSaturation);
vec3 base = mix(land, source * uOceanAbsorption + uOceanDeepColor, ocean);
float diffuse = mix(1.0, 0.78 + 0.22 * max(sunFacing, 0.0), uDayNightEnabled);
vec3 color = base * diffuse;
float fresnel = pow(1.0 - clamp(dot(normal, viewDirection), 0.0, 1.0), 3.4);
// No white specular lobe: only grazing-angle sky reflection on water.
color += uOceanReflection * fresnel * ocean * daylight;
float rimLight = mix(1.0, smoothstep(-0.18, 0.45, sunFacing), uDayNightEnabled);
color += uAtmosphereColor * pow(fresnel, 1.6) * uInnerRimStrength * rimLight;
// A separate night branch preserves geographic contrast without raising
// day exposure or adding a uniform gray veil. All values remain linear.
vec3 nightDetail = pow(surfaceToneMap(mix(land, source * uOceanAbsorption, ocean) * uExposure), vec3(uNightDetailGamma));
vec3 nightLand = nightDetail * uNightLandTint + uNightLandAmbient;
vec3 nightOcean = nightDetail * uNightOceanTint + uNightOceanAmbient;
vec3 nightColor = mix(nightLand, nightOcean, ocean);
color = mix(nightColor, surfaceToneMap(color * uExposure), daylight);
gl_FragColor = vec4(surfaceSRGB(color), 1.0);
}
`;
export function createEarthSurfaceMaterial(config, sunDirection, enabled) {
return new THREE.ShaderMaterial({
uniforms: {
uDayMap: { value: null },
uLandMask: { value: null },
uLandMaskAvailable: { value: 0 },
uMaskOcean: { value: new THREE.Vector3() },
uMaskLand: { value: new THREE.Vector3(1, 1, 1) },
uSunDirectionWorld: { value: sunDirection.clone() },
uDayNightEnabled: { value: enabled ? 1 : 0 },
uExposure: { value: config.exposure },
uOceanAbsorption: { value: config.oceanAbsorption },
uOceanDeepColor: { value: new THREE.Vector3(...config.oceanDeepColor) },
uLandSaturation: { value: config.landSaturation },
uNightDetailGamma: { value: config.night.detailGamma },
uNightLandTint: { value: new THREE.Vector3(...config.night.landTint) },
uNightLandAmbient: { value: new THREE.Vector3(...config.night.landAmbient) },
uNightOceanTint: { value: new THREE.Vector3(...config.night.oceanTint) },
uNightOceanAmbient: { value: new THREE.Vector3(...config.night.oceanAmbient) },
uTerminator: { value: new THREE.Vector2(...config.terminator) },
uOceanReflection: { value: new THREE.Vector3(...config.oceanReflection) },
uAtmosphereColor: { value: new THREE.Vector3(...config.atmosphereColor) },
uInnerRimStrength: { value: config.innerRimStrength },
},
defines: LEGACY_TEXTURE_ENCODING ? { LEGACY_TEXTURE_ENCODING: 1 } : {},
vertexShader: SURFACE_VERTEX_SHADER,
fragmentShader: SURFACE_FRAGMENT_SHADER,
side: THREE.FrontSide,
transparent: true,
depthTest: true,
depthWrite: false,
toneMapped: false,
});
}
export function createEarthAtmosphereMaterial(config, sunDirection, enabled) {
return new THREE.ShaderMaterial({
uniforms: {
uSunDirectionWorld: { value: sunDirection.clone() },
uDayNightEnabled: { value: enabled ? 1 : 0 },
uColor: { value: new THREE.Vector3(...config.color) },
uStrength: { value: config.strength },
},
vertexShader: SURFACE_VERTEX_SHADER,
fragmentShader: `
uniform vec3 uSunDirectionWorld;
uniform float uDayNightEnabled;
uniform vec3 uColor;
uniform float uStrength;
varying vec3 vWorldNormal;
varying vec3 vWorldPosition;
void main() {
vec3 normal = normalize(vWorldNormal);
vec3 viewDirection = normalize(cameraPosition - vWorldPosition);
float facing = clamp(abs(dot(normal, viewDirection)), 0.0, 1.0);
float rim = pow(1.0 - facing, 3.0) * smoothstep(0.0, 0.22, facing);
float daylight = smoothstep(-0.22, 0.45, dot(normal, normalize(uSunDirectionWorld)));
float illumination = mix(1.0, mix(0.12, 1.0, daylight), uDayNightEnabled);
gl_FragColor = vec4(uColor, rim * illumination * uStrength);
}
`,
side: THREE.BackSide,
transparent: true,
blending: THREE.AdditiveBlending,
depthWrite: false,
depthTest: true,
toneMapped: false,
});
}
@@ -0,0 +1,77 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import {
createEarth, getEarthSurfacePickTarget, setDayNightEnabled,
setEarthLandMask, setEarthSunDirection, setEarthTextureVisible,
} from "./earth.js";
import { CONFIG, EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET } from "./constants.js";
import { createCableLineBatch } from "./cable-batches.js";
test("the real texture shell retains its geometry and pick target, with one atmosphere draw", () => {
const earth = createEarth(new THREE.Scene());
const surface = earth.getObjectByName("earth-high-res-texture-overlay");
const atmosphere = earth.getObjectByName("earth-atmosphere-scattering");
expect(surface.geometry.parameters.radius).toBe(CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET);
expect(surface.material.isShaderMaterial).toBe(true);
expect(surface.material.depthWrite).toBe(false);
expect(surface.raycast).toBe(THREE.Mesh.prototype.raycast);
expect(earth.children.filter(child => child.material?.isShaderMaterial).length).toBe(2);
expect(atmosphere.material.side).toBe(THREE.BackSide);
expect(atmosphere.material.depthWrite).toBe(false);
expect(atmosphere.material.depthTest).toBe(true);
expect(getEarthSurfacePickTarget()).toBe(earth);
setEarthTextureVisible(false);
expect(getEarthSurfacePickTarget()).toBe(earth);
setEarthTextureVisible(true);
});
test("world-space sunlight, day/night and geographic masking update the visible shader owners", () => {
const earth = createEarth(new THREE.Scene());
const surface = earth.getObjectByName("earth-high-res-texture-overlay");
const atmosphere = earth.getObjectByName("earth-atmosphere-scattering");
const direction = new THREE.Vector3(-2, 1, 3);
setEarthSunDirection(direction);
for (const mesh of [surface, atmosphere]) {
expect(mesh.material.uniforms.uSunDirectionWorld.value.distanceTo(direction.clone().normalize())).toBeLessThan(1e-8);
}
setDayNightEnabled(false);
expect(surface.material.uniforms.uDayNightEnabled.value).toBe(0);
expect(atmosphere.material.uniforms.uDayNightEnabled.value).toBe(0);
setDayNightEnabled(true);
const mask = new THREE.Texture();
setEarthLandMask(mask, 0x010609, 0x080f1b);
expect(surface.material.uniforms.uLandMask.value).toBe(mask);
expect(surface.material.uniforms.uMaskLand.value.z).toBeCloseTo(27 / 255);
setEarthLandMask(null);
expect(surface.material.uniforms.uLandMask.value).toBeNull();
expect(surface.material.uniforms.uLandMaskAvailable.value).toBe(0);
});
test("cable pulses use arc length while keeping original pick objects and independent states", () => {
const lines = [0, 1].map(index => {
const geometry = new THREE.BufferGeometry().setFromPoints([
new THREE.Vector3(0, index, 0), new THREE.Vector3(1, index, 0), new THREE.Vector3(4, index, 0),
]);
const line = new THREE.Line(geometry, new THREE.LineBasicMaterial({ color: 0x328ebc, opacity: 0.7 }));
line.userData.cableId = `route-${index}`;
return line;
});
const originalPositions = lines[0].geometry.attributes.position.array.slice();
const originalRaycast = lines[0].raycast;
const batch = createCableLineBatch(lines);
const progress = batch.object.geometry.attributes.progress;
expect([...progress.array.slice(0, 4)]).toEqual([0, 0.25, 0.25, 1]);
lines[0].material.userData.cableSelected = true;
batch.object.onBeforeRender();
const styles = batch.object.material.uniforms.styles.value.image.data;
expect(styles[3]).toBeLessThan(0);
expect(styles[7]).toBeGreaterThan(0);
lines[0].visible = false;
batch.object.onBeforeRender();
expect(styles[3]).toBe(0);
expect(lines[0].raycast).toBe(originalRaycast);
expect(lines[0].userData.cableId).toBe("route-0");
expect(lines[0].geometry.attributes.position.array).toEqual(originalPositions);
batch.dispose();
expect(lines[0].geometry.attributes.position.count).toBe(3);
});
+27 -128
View File
@@ -14,6 +14,7 @@ import { latLonToVector3 } from './utils.js';
import { configureColorTexture, preserveTextureOutput, shaderOutputMarker } from './texture-colors.js';
import { createEarthMapController } from './earth-map-sources.js';
import { earthTextureImages } from './earth-texture-image.js';
import { createEarthAtmosphereMaterial, createEarthSurfaceMaterial } from './earth-surface-material.js';
export let earth = null;
export let clouds = null;
@@ -28,7 +29,6 @@ let _earthTextureOverlayMaterial = null;
let _earthShaders = [];
let _dayNightEnabled = true;
let _textureVisible = true;
let _earthRimGlow = null;
let _cloudTexture = null;
let _cloudTextureLoadPromise = null;
const _earthSunDirection = new THREE.Vector3(
@@ -50,6 +50,7 @@ const earthMap = createEarthMapController({
texture.wrapS = THREE.RepeatWrapping;
texture.wrapT = THREE.ClampToEdgeWrapping;
texture.anisotropy = 16;
texture.generateMipmaps = true;
texture.minFilter = THREE.LinearMipmapLinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.needsUpdate = true;
@@ -57,11 +58,9 @@ const earthMap = createEarthMapController({
},
applyTexture: (texture) => {
if (_earthTextureOverlayMaterial) {
_earthTextureOverlayMaterial.map = texture;
_earthTextureOverlayMaterial.needsUpdate = true;
_earthTextureOverlayMaterial.uniforms.uDayMap.value = texture;
}
if (_earthTextureOverlay) _earthTextureOverlay.visible = _textureVisible && Boolean(texture);
if (_earthRimGlow) _earthRimGlow.visible = !(_textureVisible && texture);
},
onChange: (detail) => {
if (typeof window !== "undefined") {
@@ -146,16 +145,8 @@ export function createEarth(scene) {
C.textureWidthSegments,
C.textureHeightSegments,
);
_earthTextureOverlayMaterial = new THREE.MeshBasicMaterial({
color: 0xffffff,
toneMapped: false,
transparent: true,
opacity: C.textureOverlayOpacity,
side: THREE.FrontSide,
depthWrite: false,
depthTest: true,
});
applyEarthDayNightShader(_earthTextureOverlayMaterial);
_earthTextureOverlayMaterial = createEarthSurfaceMaterial(C.surface, _earthSunDirection, _dayNightEnabled);
_earthShaders.push(_earthTextureOverlayMaterial);
_earthTextureOverlay = new THREE.Mesh(
textureOverlayGeometry,
_earthTextureOverlayMaterial,
@@ -182,115 +173,14 @@ export function createEarth(scene) {
occluder.renderOrder = 0.5;
earth.add(occluder);
// Keep the original atmosphere shells on the legacy camera-facing shader so
// they stay as a soft edge cue instead of becoming a visible transparent hull
// at close zoom levels.
const ATMOS_VERTEX_SHADER = `
varying vec3 vNormal;
void main() {
vNormal = normalize(normalMatrix * normal);
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`;
const RIM_VERTEX_SHADER = `
varying vec3 vNormal;
varying vec3 vViewDirection;
void main() {
vNormal = normalize(normalMatrix * normal);
vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
vViewDirection = normalize(-mvPosition.xyz);
gl_Position = projectionMatrix * mvPosition;
}
`;
// Fresnel atmosphere — inner rim
const [ir, ig, ib] = C.atmosInnerColor;
const atmosInnerGeo = new THREE.SphereGeometry(
CONFIG.earthRadius * C.atmosInnerRadiusFactor,
C.atmosInnerSegments,
C.atmosInnerSegments,
const atmosphere = new THREE.Mesh(
new THREE.SphereGeometry(CONFIG.earthRadius * C.atmosphere.radiusFactor, 64, 48),
createEarthAtmosphereMaterial(C.atmosphere, _earthSunDirection, _dayNightEnabled),
);
const atmosInnerMat = new THREE.ShaderMaterial({
vertexShader: ATMOS_VERTEX_SHADER,
fragmentShader: `
varying vec3 vNormal;
void main() {
float rim = 1.0 - abs(dot(vNormal, vec3(0.0, 0.0, 1.0)));
float intensity = pow(rim, ${C.atmosInnerRimPower.toFixed(1)});
gl_FragColor = vec4(${ir.toFixed(2)}, ${ig.toFixed(2)}, ${ib.toFixed(2)}, intensity * ${C.atmosInnerIntensity.toFixed(2)});
}
`,
blending: THREE.AdditiveBlending,
side: THREE.BackSide,
transparent: true,
depthWrite: false,
});
const atmosInner = new THREE.Mesh(atmosInnerGeo, atmosInnerMat);
atmosInner.renderOrder = 1;
earth.add(atmosInner);
// Fresnel atmosphere — outer corona
const [outerR, outerG, outerB] = C.atmosOuterColor;
const atmosOuterGeo = new THREE.SphereGeometry(
CONFIG.earthRadius * C.atmosOuterRadiusFactor,
C.atmosOuterSegments,
C.atmosOuterSegments,
);
const atmosOuterMat = new THREE.ShaderMaterial({
vertexShader: ATMOS_VERTEX_SHADER,
fragmentShader: `
varying vec3 vNormal;
void main() {
float rim = 1.0 - abs(dot(vNormal, vec3(0.0, 0.0, 1.0)));
// Fade at the outer silhouette instead of drawing a hard luminous ring.
float facing = abs(dot(normalize(vNormal), vec3(0.0, 0.0, 1.0)));
float edgeFade = smoothstep(0.0, ${C.atmosOuterEdgeFeather.toFixed(2)}, facing);
float intensity = pow(rim, ${C.atmosOuterRimPower.toFixed(1)}) * edgeFade;
gl_FragColor = vec4(${outerR.toFixed(2)}, ${outerG.toFixed(2)}, ${outerB.toFixed(2)}, intensity * ${C.atmosOuterIntensity.toFixed(2)});
}
`,
blending: THREE.AdditiveBlending,
side: THREE.BackSide,
transparent: true,
depthWrite: false,
});
const atmosOuter = new THREE.Mesh(atmosOuterGeo, atmosOuterMat);
atmosOuter.renderOrder = 1;
earth.add(atmosOuter);
// Fresnel rim cue: an outer shell keeps the edge tied to the globe while bypassing
// the darker fill layers that can otherwise hide a same-radius glow. Unlike the
// legacy atmosphere shells, this one uses the real view direction so its highlight
// stays attached to the visible globe edge while zooming.
const [rr, rg, rb] = C.rimGlowColor;
const rimGlowGeo = new THREE.SphereGeometry(
CONFIG.earthRadius * C.rimGlowRadiusFactor,
C.rimGlowSegments,
C.rimGlowSegments,
);
const rimGlowMat = new THREE.ShaderMaterial({
vertexShader: RIM_VERTEX_SHADER,
fragmentShader: `
varying vec3 vNormal;
varying vec3 vViewDirection;
void main() {
float viewFacing = max(dot(normalize(vNormal), normalize(vViewDirection)), 0.0);
float rim = 1.0 - viewFacing;
float alpha = pow(rim, ${C.rimGlowPower.toFixed(1)}) * ${C.rimGlowIntensity.toFixed(2)};
gl_FragColor = vec4(${rr.toFixed(2)}, ${rg.toFixed(2)}, ${rb.toFixed(2)}, alpha);
}
`,
blending: THREE.AdditiveBlending,
side: THREE.FrontSide,
transparent: true,
depthTest: false,
depthWrite: false,
});
_earthRimGlow = new THREE.Mesh(rimGlowGeo, rimGlowMat);
_earthRimGlow.name = "earth-rim-glow";
_earthRimGlow.renderOrder = C.rimGlowRenderOrder;
earth.add(_earthRimGlow);
atmosphere.name = "earth-atmosphere-scattering";
atmosphere.renderOrder = 1;
_earthShaders.push(atmosphere.material);
earth.add(atmosphere);
// Texture is loaded separately via loadEarthTexture() for staged loading
return earth;
@@ -302,7 +192,7 @@ export function createClouds(scene, earthObj) {
CLOUD_LAYER_CONFIG.widthSegments,
CLOUD_LAYER_CONFIG.heightSegments,
);
const material = new THREE.MeshPhongMaterial({
const material = new THREE.MeshBasicMaterial({
transparent: true,
opacity: CLOUD_LAYER_CONFIG.opacity,
depthTest: true,
@@ -310,9 +200,11 @@ export function createClouds(scene, earthObj) {
blending: THREE.AdditiveBlending,
side: THREE.DoubleSide
});
applyEarthDayNightShader(material);
clouds = new THREE.Mesh(geometry, material);
clouds.name = "earth-atmosphere-clouds";
clouds.renderOrder = 1.1;
clouds.visible = false;
earthObj.add(clouds);
@@ -343,6 +235,7 @@ export function loadCloudTexture() {
textureLoader.load(
CLOUD_LAYER_CONFIG.textureUrl,
(texture) => {
configureColorTexture(texture);
_cloudTexture = texture;
clouds.material.map = texture;
clouds.material.needsUpdate = true;
@@ -513,6 +406,16 @@ export function clearEarthTexture() {
earthMap.clear();
}
export function setEarthLandMask(texture, oceanHex = 0, landHex = 0xffffff) {
const uniforms = _earthTextureOverlayMaterial?.uniforms;
if (!uniforms) return;
uniforms.uLandMask.value = texture;
uniforms.uLandMaskAvailable.value = texture ? 1 : 0;
for (const [uniform, color] of [[uniforms.uMaskOcean, oceanHex], [uniforms.uMaskLand, landHex]]) {
uniform.value.set(((color >> 16) & 255) / 255, ((color >> 8) & 255) / 255, (color & 255) / 255);
}
}
export function setEarthSunDirection(direction) {
if (!direction) return;
_earthSunDirection.copy(direction).normalize();
@@ -556,11 +459,7 @@ export function setEarthTextureVisible(visible) {
_earthTextureOverlay.visible = textureShowing;
}
if (_earthTextureOverlayMaterial) {
_earthTextureOverlayMaterial.map = earthMap.getTexture();
_earthTextureOverlayMaterial.needsUpdate = true;
}
if (_earthRimGlow) {
_earthRimGlow.visible = !textureShowing;
_earthTextureOverlayMaterial.uniforms.uDayMap.value = earthMap.getTexture();
}
}
+40 -86
View File
@@ -1,15 +1,5 @@
import * as THREE from "three";
const DRAG_INERTIA = Object.freeze({
frameMs: 16,
minimumSampleMs: 8,
maximumFrameMs: 40,
releasePauseMs: 80,
minimumSpeed: 0.000005,
maximumSpeed: 0.003,
damping: 0.92,
});
// Magnify the apparent sphere radius, not the camera's distance to its center.
// At zoom=1 the existing camera pose is unchanged; larger zoom never enters it.
export function distanceForGlobeZoom(zoom, radius, defaultDistance, minimumAltitude = 10) {
@@ -23,91 +13,55 @@ export function globeZoomForDistance(distance, radius, defaultDistance) {
Math.max(0.0001, distance ** 2 - radius ** 2));
}
// Use the actual camera frustum so portrait screens switch by their width,
// while landscape screens switch by their height. Decide only on pointer-down.
export function isGlobeClippedByViewport(earth, camera, radius) {
camera.updateMatrixWorld();
const center = earth.getWorldPosition(new THREE.Vector3());
const scale = earth.getWorldScale(new THREE.Vector3());
const worldRadius = radius * Math.max(Math.abs(scale.x), Math.abs(scale.y), Math.abs(scale.z));
const viewProjection = new THREE.Matrix4().multiplyMatrices(
camera.projectionMatrix, camera.matrixWorldInverse,
// Keep the legacy pixel sensitivity until the globe fills the viewport. At
// extreme zoom cap it by the surface distance, with no pointer/sphere gating.
export function globeDragRotationFactor(zoom, camera, viewport, config) {
const legacy = config.dragRotationFactorBase * THREE.MathUtils.clamp(
Math.pow(Math.max(zoom, 0.01), -config.dragRotationZoomExponent),
config.dragRotationScaleMin, config.dragRotationScaleMax,
);
const frustum = new THREE.Frustum().setFromProjectionMatrix(viewProjection);
return frustum.planes.slice(0, 4).some(plane => plane.distanceToPoint(center) < worldRadius);
const distance = camera.position.length();
const radius = config.earthRadius;
const tangent = Math.tan(THREE.MathUtils.degToRad(camera.fov) / 2);
const diameter = radius / Math.sqrt(Math.max(1, distance * distance - radius * radius)) * viewport.height / tangent;
const coverage = diameter / Math.max(1, Math.min(viewport.width, viewport.height));
const blend = THREE.MathUtils.smoothstep(coverage, 1, 1.5);
const surface = 2 * Math.max(config.minimumCameraAltitude, distance - radius) * tangent / (Math.max(1, viewport.height) * radius);
return legacy + (Math.min(legacy, surface) - legacy) * blend;
}
export function createSurfaceDrag(radius) {
const raycaster = new THREE.Raycaster();
const pointer = new THREE.Vector2();
const center = new THREE.Vector3();
const hit = new THREE.Vector3();
const sphere = new THREE.Sphere(center, radius);
const anchor = new THREE.Vector3();
const current = new THREE.Vector3();
// All pointer drags are pixel-driven, including outside the silhouette. Rotate
// around the geographic axis horizontally and camera right vertically. Keep
// quaternion math so Euler rebasing cannot reverse drag or add unwanted bank.
export function createScreenSpaceDrag() {
const pending = new THREE.Vector2();
const cameraRotation = new THREE.Quaternion();
const parentInverse = new THREE.Quaternion();
const initial = new THREE.Quaternion();
const change = new THREE.Quaternion();
const previous = new THREE.Quaternion();
const axis = new THREE.Vector3();
let active = false, speed = 0, lastMoveAt = 0;
function pointerNormal(earth, camera, point, viewport, output) {
camera.updateMatrixWorld();
earth.getWorldPosition(center);
raycaster.setFromCamera(pointer.set(
(point.x - viewport.left) / viewport.width * 2 - 1,
1 - (point.y - viewport.top) / viewport.height * 2,
), camera);
if (!raycaster.ray.intersectSphere(sphere, hit)) {
// No real surface point exists here. A closest-point substitute folds
// back toward the camera as the pointer moves away, reversing rotation.
return false;
}
output.copy(hit).sub(center).normalize().applyQuaternion(parentInverse);
return true;
}
const screenUp = new THREE.Vector3();
const north = new THREE.Vector3();
const localNorth = new THREE.Vector3(0, 1, 0);
const change = new THREE.Quaternion();
return {
begin(earth, camera, point, viewport, now) {
speed = 0; active = true; lastMoveAt = now;
move(yaw, pitch) { pending.x += yaw; pending.y += pitch; },
stop() { pending.set(0, 0); },
advance(earth, camera, smoothing) {
const length = pending.length();
if (!length) return;
// Bound a delayed frame without throwing away accumulated pointer motion.
const fraction = Math.min(smoothing, (Math.PI / 4) / length);
camera.getWorldQuaternion(cameraRotation);
parentInverse.identity();
if (earth.parent) earth.parent.getWorldQuaternion(parentInverse).invert();
active = pointerNormal(earth, camera, point, viewport, anchor);
initial.copy(earth.quaternion);
return active;
},
move(earth, camera, point, viewport, now) {
if (!active) return;
if (!pointerNormal(earth, camera, point, viewport, current)) {
speed = 0;
lastMoveAt = now;
return;
}
previous.copy(earth.quaternion);
change.setFromUnitVectors(anchor, current);
earth.quaternion.copy(initial).premultiply(change);
change.copy(earth.quaternion).multiply(previous.invert()).normalize();
if (change.w < 0) change.set(-change.x, -change.y, -change.z, -change.w);
axis.set(change.x, change.y, change.z);
const angle = 2 * Math.atan2(axis.length(), Math.max(0, change.w));
axis.normalize();
speed = Math.min(DRAG_INERTIA.maximumSpeed, angle / Math.max(DRAG_INERTIA.minimumSampleMs, now - lastMoveAt));
lastMoveAt = now;
},
end(now, cancelled = false) {
active = false;
if (cancelled || now - lastMoveAt > DRAG_INERTIA.releasePauseMs) speed = 0;
},
stop() { active = false; speed = 0; },
hasInertia() { return !active && speed > DRAG_INERTIA.minimumSpeed; },
advance(earth, deltaMs) {
if (active || speed <= DRAG_INERTIA.minimumSpeed) return false;
const elapsed = Math.min(deltaMs, DRAG_INERTIA.maximumFrameMs);
change.setFromAxisAngle(axis, speed * elapsed);
screenUp.set(0, 1, 0).applyQuaternion(cameraRotation).applyQuaternion(parentInverse);
north.copy(localNorth).applyQuaternion(earth.quaternion);
const direction = north.dot(screenUp) < 0 ? -1 : 1;
change.setFromAxisAngle(localNorth, pending.x * fraction * direction);
earth.quaternion.multiply(change);
axis.set(1, 0, 0).applyQuaternion(cameraRotation).applyQuaternion(parentInverse);
change.setFromAxisAngle(axis, pending.y * fraction);
earth.quaternion.premultiply(change).normalize();
speed *= Math.pow(DRAG_INERTIA.damping, elapsed / DRAG_INERTIA.frameMs);
return true;
pending.multiplyScalar(1 - fraction);
},
};
}
@@ -1,7 +1,7 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import { CONFIG, EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET } from "./constants.js";
import { createSurfaceDrag, distanceForGlobeZoom, globeZoomForDistance, isGlobeClippedByViewport } from "./globe-navigation.js";
import { createScreenSpaceDrag, globeDragRotationFactor, distanceForGlobeZoom, globeZoomForDistance } from "./globe-navigation.js";
const radius = CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET;
const distance = zoom => distanceForGlobeZoom(zoom, CONFIG.earthRadius,
@@ -33,84 +33,96 @@ function scene(zoom, width, height) {
const p = local.clone().applyMatrix4(earth.matrixWorld).project(camera);
return { x: viewport.left + (p.x + 1) * width / 2, y: viewport.top + (1 - p.y) * height / 2 };
};
const grabbed = new THREE.Vector3(0, 0, radius).applyQuaternion(earth.quaternion.clone().invert());
return { camera, earth, viewport, project, grabbed };
return { camera, earth, viewport, project };
}
for (const [zoom, width, height, clipped] of [
[0.5, 1440, 900, false], [1, 1440, 900, false], [2, 1440, 900, false],
[3, 1440, 900, true], [5, 1440, 900, true],
[0.5, 390, 844, false], [0.9, 390, 844, false], [1, 390, 844, true], [2, 390, 844, true],
]) {
test(`${zoom * 100}% at ${width}x${height}: choose surface drag only when the globe is clipped`, () => {
const f = scene(zoom, width, height);
expect(isGlobeClippedByViewport(f.earth, f.camera, radius)).toBe(clipped);
});
}
test("a grab outside the globe is rejected so screen-space dragging can handle it", () => {
const f = scene(1, 1440, 900);
const drag = createSurfaceDrag(radius);
expect(drag.begin(f.earth, f.camera, { x: 20, y: 30 }, f.viewport, 0)).toBe(false);
const before = f.earth.quaternion.clone();
drag.move(f.earth, f.camera, { x: 150, y: 30 }, f.viewport, 16);
expect(f.earth.quaternion.angleTo(before)).toBeCloseTo(0, 7);
});
test("moving a large-globe grab beyond its limb never reverses or generates inertia", () => {
const f = scene(3, 1440, 900);
const drag = createSurfaceDrag(radius), start = f.project(f.grabbed);
expect(drag.begin(f.earth, f.camera, start, f.viewport, 0)).toBe(true);
let previous = f.earth.quaternion.clone();
for (let step = 1; step <= 100; step++) {
drag.move(f.earth, f.camera, { x: start.x + step * 10, y: start.y }, f.viewport, step * 16);
const delta = f.earth.quaternion.clone().multiply(previous.clone().invert());
expect(delta.y).toBeGreaterThanOrEqual(-1e-10);
previous.copy(f.earth.quaternion);
}
drag.end(1601);
expect(drag.hasInertia()).toBe(false);
});
for (const zoom of [0.5, 1, 2, 3, 5]) for (const [width, height] of [[1440, 900], [390, 844]]) {
test(`${zoom * 100}% at ${width}px: the grabbed surface follows the pointer pixel for pixel`, () => {
const f = scene(zoom, width, height);
const drag = createSurfaceDrag(radius);
const start = f.project(f.grabbed);
drag.begin(f.earth, f.camera, start, f.viewport, 0);
for (let step = 1; step <= 20; step++) {
const target = { x: start.x + step, y: start.y + step * 0.6 };
drag.move(f.earth, f.camera, target, f.viewport, step * 16);
const actual = f.project(f.grabbed);
expect(actual.x).toBeCloseTo(target.x, 6);
expect(actual.y).toBeCloseTo(target.y, 6);
expect(drag.advance(f.earth, 16)).toBe(false);
for (const [width, height] of [[1440, 900], [390, 844]]) {
test(`screen drag keeps pointer direction after multiple revolutions and quaternion rebasing at ${width}px`, () => {
const f = scene(0.5, width, height);
const drag = createScreenSpaceDrag();
for (const turns of [-12, -3, 0, 5, 20]) for (const pitch of [0.3, 2.6, -2.7]) {
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
f.earth.rotation.set(pitch, turns * Math.PI * 2 + 1.8, 0.7);
// Camera focusing writes quaternions; this
// canonicalizes XYZ angles, reproducing the legacy reversed Y axis.
f.earth.quaternion.copy(f.earth.quaternion.clone());
const point = new THREE.Vector3(0, 0, radius).applyQuaternion(f.earth.quaternion.clone().invert());
const before = f.project(point);
drag.stop();
drag.move(dx * 0.02, dy * 0.02);
drag.advance(f.earth, f.camera, 0.25);
const after = f.project(point);
if (dx) expect((after.x - before.x) * dx).toBeGreaterThan(0);
if (dy) expect((after.y - before.y) * dy).toBeGreaterThan(0);
expect(f.earth.quaternion.length()).toBeCloseTo(1, 10);
}
}
});
}
test("a paused release or cancellation cannot fling the globe", () => {
const f = scene(5, 1440, 900);
const drag = createSurfaceDrag(radius), start = f.project(f.grabbed);
drag.begin(f.earth, f.camera, start, f.viewport, 0);
drag.move(f.earth, f.camera, { x: start.x + 50, y: start.y }, f.viewport, 16);
drag.end(200);
expect(drag.hasInertia()).toBe(false);
drag.begin(f.earth, f.camera, start, f.viewport, 220);
drag.move(f.earth, f.camera, { x: start.x + 30, y: start.y }, f.viewport, 236);
drag.end(237, true);
expect(drag.hasInertia()).toBe(false);
test("screen drag follows a rotated camera with a transformed parent and retains damped motion", () => {
const f = scene(0.5, 1440, 900), drag = createScreenSpaceDrag();
const parent = new THREE.Object3D();
parent.rotation.set(0.8, 1.2, -0.7); parent.add(f.earth);
f.camera.position.set(250, 100, 400); f.camera.lookAt(0, 0, 0); f.camera.updateMatrixWorld();
parent.updateMatrixWorld(true);
const point = f.camera.position.clone().normalize().multiplyScalar(radius);
f.earth.worldToLocal(point);
let previous = f.project(point);
drag.move(0.05, 0.02);
for (let i = 0; i < 12; i++) {
drag.advance(f.earth, f.camera, 0.25);
const current = f.project(point);
expect(current.x).toBeGreaterThan(previous.x);
expect(current.y).toBeGreaterThan(previous.y);
previous = current;
}
drag.stop();
const rotation = f.earth.quaternion.clone();
drag.advance(f.earth, f.camera, 0.25);
expect(f.earth.quaternion.angleTo(rotation)).toBeCloseTo(0, 7);
});
test("pinch zoom can rebase the remaining finger without a jump", () => {
const f = scene(1, 390, 844), drag = createSurfaceDrag(radius);
const start = f.project(f.grabbed);
drag.begin(f.earth, f.camera, start, f.viewport, 0);
drag.stop();
f.camera.position.z = distance(5);
f.camera.updateMatrixWorld();
const before = f.earth.quaternion.clone();
drag.begin(f.earth, f.camera, start, f.viewport, 100);
drag.move(f.earth, f.camera, start, f.viewport, 116);
expect(f.earth.quaternion.angleTo(before)).toBeCloseTo(0, 7);
test("repeated horizontal small-globe drags and inertia preserve the existing geographic axis", () => {
const f = scene(1, 1440, 900), drag = createScreenSpaceDrag();
for (const pitch of [0.4, 2.6, -2.7]) {
f.earth.rotation.set(pitch, 18 * Math.PI + 1.8, 0.35);
const north = new THREE.Vector3(0, 1, 0).applyQuaternion(f.earth.quaternion);
for (let step = 0; step < 600; step++) {
drag.move(step % 80 < 40 ? 0.035 : -0.035, 0);
drag.advance(f.earth, f.camera, 0.18);
expect(new THREE.Vector3(0, 1, 0).applyQuaternion(f.earth.quaternion).distanceTo(north)).toBeLessThan(1e-10);
}
drag.stop();
}
});
test("vertical small-globe input deliberately changes tilt", () => {
const f = scene(1, 1440, 900), drag = createScreenSpaceDrag();
const north = new THREE.Vector3(0, 1, 0).applyQuaternion(f.earth.quaternion);
drag.move(0, 0.3); drag.advance(f.earth, f.camera, 1);
expect(new THREE.Vector3(0, 1, 0).applyQuaternion(f.earth.quaternion).distanceTo(north)).toBeGreaterThan(0.1);
});
for (const [width, height] of [[1440, 900], [390, 844]]) for (const zoom of [0.5, 1, 3, 5]) {
test(`${zoom * 100}% at ${width}px: dragging outside the globe keeps rotating in the pointer direction`, () => {
const f = scene(zoom, width, height), drag = createScreenSpaceDrag();
const factor = globeDragRotationFactor(zoom, f.camera, f.viewport, CONFIG);
let previous = f.earth.quaternion.clone();
for (let x = width / 2; x < width * 1.2; x += 10) {
drag.move(10 * factor, 0); drag.advance(f.earth, f.camera, 0.18);
const north = new THREE.Vector3(0, 1, 0).applyQuaternion(previous);
const delta = f.earth.quaternion.clone().multiply(previous.clone().invert());
expect(new THREE.Vector3(delta.x, delta.y, delta.z).dot(north)).toBeGreaterThan(0);
previous.copy(f.earth.quaternion);
}
});
}
test("normal zoom keeps legacy sensitivity while extreme zoom limits magnification", () => {
const normal = scene(1, 1440, 900), large = scene(5, 1440, 900);
expect(globeDragRotationFactor(1, normal.camera, normal.viewport, CONFIG)).toBe(CONFIG.dragRotationFactorBase);
expect(globeDragRotationFactor(5, large.camera, large.viewport, CONFIG)).toBeLessThan(CONFIG.dragRotationFactorBase * CONFIG.dragRotationScaleMin);
});
+17 -27
View File
@@ -1,3 +1,4 @@
import { drawMarkerBadge } from "./marker-badges.js";
import * as THREE from "three";
import { CONFIG } from "./constants.js";
@@ -16,7 +17,6 @@ const CLUSTER_OVERLAP_FACTOR = 0.9;
const CLUSTER_MIN_COUNT = 2;
const CLUSTER_MAX_MARKERS_PER_DOT = 14;
const CLUSTER_MAX_POINT_SIZE = 32;
const CLUSTER_MAX_SCREEN_DIAMETER_PX = 96;
const CLUSTER_SEED_DISTANCE_FACTOR = 1.8;
const CLUSTER_TRANSITION_MS = 220;
const CLUSTER_BAND_HYSTERESIS = 0.08;
@@ -50,7 +50,7 @@ const SPHERICAL_CLUSTER_BANDS = Object.freeze([
Object.freeze({ key: "near", maxZoom: 3.5, distance: 4 }),
Object.freeze({ key: "detail", maxZoom: Number.POSITIVE_INFINITY, distance: 0 }),
]);
let compactDotsEnabled = true;
let compactDotsEnabled = false;
let screenAvoidanceRevision = 0;
// Named overlap profiles. Layers that should be recognized as sharing a place
@@ -530,32 +530,11 @@ function findScreenClusterGroups(entries) {
return groups;
}
function getScreenDistance(entryA, entryB) {
return Math.hypot(entryA.x - entryB.x, entryA.y - entryB.y);
}
function getAngularDistance(entryA, entryB) {
const dot = entryA.direction.dot(entryB.direction);
return Math.acos(Math.min(1, Math.max(-1, dot)));
}
function getScreenBounds(entries) {
return entries.reduce(
(bounds, entry) => ({
left: Math.min(bounds.left, entry.x - entry.radiusPx),
right: Math.max(bounds.right, entry.x + entry.radiusPx),
top: Math.min(bounds.top, entry.y - entry.radiusPx),
bottom: Math.max(bounds.bottom, entry.y + entry.radiusPx),
}),
{
left: Number.POSITIVE_INFINITY,
right: Number.NEGATIVE_INFINITY,
top: Number.POSITIVE_INFINITY,
bottom: Number.NEGATIVE_INFINITY,
},
);
}
function splitLargeScreenClusterGroup(groupEntries) {
const maxMarkersPerDot = groupEntries.reduce(
(maxCount, entry) => Math.min(maxCount, entry.maxMarkersPerDot || CLUSTER_MAX_MARKERS_PER_DOT),
@@ -965,7 +944,7 @@ export function createInteractableLayer(options = {}) {
const drawX = (atlasCellSize - drawWidth) / 2;
const drawY = (atlasCellSize - drawHeight) / 2;
if (icon.colorable !== false && drawOptions.color) {
if ((icon.colorable !== false || icon.badge) && drawOptions.color) {
const tintCanvas = createCanvas(atlasCellSize, atlasCellSize);
const tintContext = tintCanvas.getContext("2d");
tintContext.clearRect(0, 0, atlasCellSize, atlasCellSize);
@@ -993,7 +972,15 @@ export function createInteractableLayer(options = {}) {
atlasCellSize,
...drawOptions,
};
if (icon.coordinates !== "canvas") {
const badgeOptions = typeof icon.badge === "function" ? icon.badge(resolvedDrawOptions) : icon.badge;
if (badgeOptions) {
const palette = drawMarkerBadge(context, { ...resolvedDrawOptions, ...badgeOptions });
resolvedDrawOptions.color = palette.ink;
resolvedDrawOptions.glow = false;
context.translate(canvas.width / 2, canvas.height / 2);
context.scale(0.6, 0.6);
if (icon.coordinates === "canvas") context.translate(-canvas.width / 2, -canvas.height / 2);
} else if (icon.coordinates !== "canvas") {
context.translate(canvas.width / 2, canvas.height / 2);
}
if (icon.draw) {
@@ -1001,7 +988,10 @@ export function createInteractableLayer(options = {}) {
} else {
drawAssetIcon(context, getIconSource(resolvedDrawOptions), resolvedDrawOptions);
}
icon.afterDraw?.(context, resolvedDrawOptions);
context.restore();
context.save();
if (icon.coordinates !== "canvas") context.translate(canvas.width / 2, canvas.height / 2);
icon.afterDraw?.(context, { atlasCellSize, ...drawOptions });
context.restore();
const texture = new THREE.CanvasTexture(canvas);
@@ -1136,7 +1126,7 @@ export function createInteractableLayer(options = {}) {
}
function shouldUseCompactDots(camera) {
return getCameraZoom(camera) <= COMPACT_DOT_ZOOM_THRESHOLD;
return compactDotsEnabled && getCameraZoom(camera) <= COMPACT_DOT_ZOOM_THRESHOLD;
}
function getMarkerStableId(marker, fallbackIndex = 0) {
@@ -1,11 +1,12 @@
import * as THREE from "three";
import { SATELLITE_CONFIG } from "./constants.js";
const EARTH_RADIUS_KM = 6378.137;
const SURFACE_SCALE = 1.003;
const SURFACE_OFFSET = 0.72;
const CLUSTER_DIAMETER_KM_APPROX = 4500;
const CLUSTER_RADIUS_KM_BASE = CLUSTER_DIAMETER_KM_APPROX / 2;
const IRIDIUM_OVERLAY_COLOR = 0x5faeff;
const IRIDIUM_OVERLAY_COLOR = SATELLITE_CONFIG.footprintColor;
const IRIDIUM_REFERENCE_ALTITUDE_KM = 780;
const FILL_RINGS = 12;
const FILL_SEGMENTS = 48;
+35 -50
View File
@@ -1,4 +1,4 @@
import { createSurfaceDrag, isGlobeClippedByViewport } from "./globe-navigation.js";
import { createScreenSpaceDrag, globeDragRotationFactor } from "./globe-navigation.js";
import * as THREE from "three";
import {
@@ -345,8 +345,8 @@ let isDragging = false;
let previousMousePosition = { x: 0, y: 0 };
let targetRotation = { x: 0, y: 0 };
let inertialVelocity = { x: 0, y: 0 };
const surfaceDrag = createSurfaceDrag(CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET);
let surfaceDragging = false;
const screenSpaceDrag = createScreenSpaceDrag();
let screenSpaceInertia = false;
let hoveredCable = null;
let hoveredBGP = null;
let hoveredComputeCenter = null;
@@ -368,7 +368,6 @@ let lastBGPClickCollector = null;
let lastBGPClickType = null;
let lastBGPClickPos = { x: 0, y: 0 };
let lastVesselHoverPickTime = 0;
let earthTexture = null;
let animationFrameId = null;
let initialized = false;
let destroyed = false;
@@ -578,20 +577,13 @@ function setGlobeDraggingUiState(active) {
function hasActiveGlobeInertia() {
return (
surfaceDrag.hasInertia() ||
Math.abs(inertialVelocity.x) > INERTIA_MIN_VELOCITY ||
Math.abs(inertialVelocity.y) > INERTIA_MIN_VELOCITY
);
}
function getDragRotationFactor() {
const zoom = Math.max(getZoomLevel(), 0.01);
const scale = THREE.MathUtils.clamp(
Math.pow(zoom, -CONFIG.dragRotationZoomExponent),
CONFIG.dragRotationScaleMin,
CONFIG.dragRotationScaleMax,
);
return CONFIG.dragRotationFactorBase * scale;
return globeDragRotationFactor(getZoomLevel(), camera, renderer.domElement.getBoundingClientRect(), CONFIG);
}
function getTargetSwitchZoomOptions(requestedZoom) {
@@ -3848,6 +3840,7 @@ function applyCableVisualState() {
allCables.forEach((cable) => {
const cableId = cable.userData.cableId;
const state = getCableState(cableId);
cable.material.userData.cableSelected = state === CABLE_STATE.LOCKED;
const hasFocus =
(lockedObjectType === "cable" && lockedObject) ||
@@ -3883,7 +3876,7 @@ function applyCableVisualState() {
((origColor & 255) / 255) * brightness,
);
} else {
cable.material.opacity = 1;
cable.material.opacity = CABLE_CONFIG.visual.normalOpacity;
cable.material.color.setHex(cable.userData.originalColor);
}
}
@@ -4528,7 +4521,8 @@ function setupMotionControl() {
export function applyMotionRotate(axisOrDirection, directionOrIntensity = 1, maybeIntensity = 1) {
const earth = getEarth();
if (!earth) return false;
surfaceDrag.stop();
screenSpaceDrag.stop();
screenSpaceInertia = false;
const axisCall = axisOrDirection === "horizontal" || axisOrDirection === "vertical";
const axis = axisCall ? axisOrDirection : "horizontal";
const direction = axisCall ? directionOrIntensity : axisOrDirection;
@@ -5764,18 +5758,11 @@ function onMouseMove(event) {
isLongDrag = true;
}
if (surfaceDragging) {
surfaceDrag.move(earth, camera, { x: event.clientX, y: event.clientY },
renderer.domElement.getBoundingClientRect(), event.timeStamp || performance.now());
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
} else {
const factor = getDragRotationFactor();
const deltaX = (event.clientX - previousMousePosition.x) * factor;
const deltaY = (event.clientY - previousMousePosition.y) * factor;
targetRotation.x += deltaY;
targetRotation.y += deltaX;
inertialVelocity = { x: deltaY, y: deltaX };
}
const factor = getDragRotationFactor();
const deltaX = (event.clientX - previousMousePosition.x) * factor;
const deltaY = (event.clientY - previousMousePosition.y) * factor;
screenSpaceDrag.move(deltaX, deltaY);
inertialVelocity = { x: deltaY, y: deltaX };
previousMousePosition = { x: event.clientX, y: event.clientY };
if (!document.body.classList.contains("layout-mode-mobile")) {
clearCountryBoundaryHover();
@@ -6067,14 +6054,10 @@ function onMouseDown(event) {
previousMousePosition = { x: event.clientX, y: event.clientY };
dragStartPointer = { ...previousMousePosition };
inertialVelocity = { x: 0, y: 0 };
surfaceDrag.stop();
surfaceDragging = false;
screenSpaceDrag.stop();
screenSpaceInertia = true;
if (earth) {
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
surfaceDragging = isGlobeClippedByViewport(earth, camera,
CONFIG.earthRadius + EARTH_SURFACE_TEXTURE_ALTITUDE_OFFSET) &&
surfaceDrag.begin(earth, camera, { x: event.clientX, y: event.clientY },
renderer.domElement.getBoundingClientRect(), event.timeStamp || performance.now());
}
clearDocumentSelection();
setGlobeDraggingUiState(true);
@@ -6084,9 +6067,7 @@ function onMouseDown(event) {
function onMouseUp(event = {}, cancelInertia = false) {
const cancelled = cancelInertia || event.type === "pointercancel";
surfaceDrag.end(event.timeStamp || performance.now(), cancelled);
if (cancelled) inertialVelocity = { x: 0, y: 0 };
surfaceDragging = false;
isDragging = false;
setGlobeDraggingUiState(false);
clearDocumentSelection();
@@ -6116,7 +6097,7 @@ function onPointerDown(event) {
};
activeDragPointerId = null;
onMouseUp();
surfaceDrag.stop();
screenSpaceDrag.stop();
inertialVelocity = { x: 0, y: 0 };
return;
}
@@ -6451,7 +6432,7 @@ function animate() {
const hasInertia = hasActiveGlobeInertia();
if (getAutoRotate() && getRotationMode() === ROTATION_MODE.ROTATE && earth && !isDragging && activeTouchPoints.size === 0 && !hasInertia) {
earth.rotation.y += getAutoRotationSpeed() * (deltaTime / 16);
earth.rotateY(getAutoRotationSpeed() * (deltaTime / 16));
// Keep the drag target aligned with autorotation only when the user is not
// actively dragging and there is no residual inertial motion to preserve.
@@ -6462,29 +6443,32 @@ function animate() {
}
if (earth) {
if ((isDragging && surfaceDragging) || surfaceDrag.advance(earth, deltaTime)) {
// Pointer movement has already placed the grabbed surface point exactly.
targetRotation.x = earth.rotation.x;
targetRotation.y = earth.rotation.y;
} else if (isDragging) {
earth.rotation.x += (targetRotation.x - earth.rotation.x) * DRAG_SMOOTHING_FACTOR;
earth.rotation.y += (targetRotation.y - earth.rotation.y) * DRAG_SMOOTHING_FACTOR;
if (isDragging) {
screenSpaceDrag.advance(earth, camera, DRAG_SMOOTHING_FACTOR);
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
} else if (
Math.abs(inertialVelocity.x) > INERTIA_MIN_VELOCITY ||
Math.abs(inertialVelocity.y) > INERTIA_MIN_VELOCITY
) {
// Continue rotating after release and gradually decay the motion.
targetRotation.x += inertialVelocity.x * (deltaTime / 16);
targetRotation.y += inertialVelocity.y * (deltaTime / 16);
earth.rotation.x +=
(targetRotation.x - earth.rotation.x) * DRAG_SMOOTHING_FACTOR;
earth.rotation.y +=
(targetRotation.y - earth.rotation.y) * DRAG_SMOOTHING_FACTOR;
if (screenSpaceInertia) {
screenSpaceDrag.move(inertialVelocity.y * (deltaTime / 16), inertialVelocity.x * (deltaTime / 16));
screenSpaceDrag.advance(earth, camera, DRAG_SMOOTHING_FACTOR);
targetRotation = { x: earth.rotation.x, y: earth.rotation.y };
} else {
// Keep the gesture-control rotation path independent of pointer drag.
targetRotation.x += inertialVelocity.x * (deltaTime / 16);
targetRotation.y += inertialVelocity.y * (deltaTime / 16);
earth.rotation.x += (targetRotation.x - earth.rotation.x) * DRAG_SMOOTHING_FACTOR;
earth.rotation.y += (targetRotation.y - earth.rotation.y) * DRAG_SMOOTHING_FACTOR;
}
inertialVelocity.x *= Math.pow(INERTIA_DAMPING, deltaTime / 16);
inertialVelocity.y *= Math.pow(INERTIA_DAMPING, deltaTime / 16);
} else {
inertialVelocity.x = 0;
inertialVelocity.y = 0;
screenSpaceDrag.stop();
screenSpaceInertia = false;
targetRotation.x = earth.rotation.x;
targetRotation.y = earth.rotation.y;
}
@@ -6586,7 +6570,8 @@ function animate() {
export function destroy() {
if (destroyed) return;
destroyed = true;
surfaceDrag.stop();
screenSpaceDrag.stop();
screenSpaceInertia = false;
stopVesselRealtime();
currentLoadToken += 1;
isDataLoading = false;
+53
View File
@@ -0,0 +1,53 @@
// Reference-aligned badge surfaces shared by all finite ground-object layers.
// Painted into the existing texture atlas: no DOM nodes or per-marker meshes.
const REFERENCE_BADGES = {
'#14b8a6': { top: '#14b8a6', bottom: '#0d9488', border: '#5eead4', ink: '#042f2e' },
'#a855f7': { top: '#a855f7', bottom: '#7e22ce', border: '#d8b4fe', ink: '#3b0764' },
'#f59e0b': { top: '#f59e0b', bottom: '#d97706', border: '#fef3c7', ink: '#451a03' },
};
function blend(color, target, amount) {
const value = Number.parseInt(color.slice(1), 16);
const end = Number.parseInt(target.slice(1), 16);
return '#' + [16, 8, 0].map(shift => Math.round(((value >> shift) & 255) * (1 - amount) + ((end >> shift) & 255) * amount).toString(16).padStart(2, '0')).join('');
}
export function markerBadgePalette(color = '#38bdf8') {
const normalized = /^#[0-9a-f]{6}$/i.test(color) ? color.toLowerCase() : '#38bdf8';
return REFERENCE_BADGES[normalized] || {
top: normalized,
bottom: blend(normalized, '#020617', 0.25),
border: blend(normalized, '#ffffff', 0.64),
ink: blend(normalized, '#020617', 0.87),
};
}
export function drawMarkerBadge(context, { color, atlasCellSize = 128, glow = false }) {
const palette = markerBadgePalette(color);
const scale = atlasCellSize / 128;
context.save();
context.scale(scale, scale);
const gradient = context.createLinearGradient(22, 18, 108, 110);
gradient.addColorStop(0, palette.top);
gradient.addColorStop(1, palette.bottom);
context.shadowColor = glow ? palette.top : 'rgba(0,0,0,0.65)';
context.shadowBlur = glow ? 17 : 11;
context.shadowOffsetY = glow ? 0 : 6;
context.beginPath();
context.roundRect(20, 18, 88, 88, 19);
context.fillStyle = gradient;
context.fill();
context.shadowBlur = 0;
context.shadowOffsetY = 0;
context.lineWidth = 2.8;
context.strokeStyle = palette.border;
context.stroke();
context.beginPath();
context.moveTo(38, 23);
context.lineTo(89, 23);
context.strokeStyle = 'rgba(255,255,255,0.23)';
context.lineWidth = 2;
context.stroke();
context.restore();
return palette;
}
@@ -0,0 +1,57 @@
import { expect, test } from 'bun:test';
import * as THREE from 'three';
import { markerBadgePalette } from './marker-badges.js';
import { createInteractableLayer, getInteractableCompactDotsEnabled, setInteractableCompactDotsEnabled } from './interactable.js';
test('reference teal, purple and amber palettes retain their exact plate, rim and ink colors', () => {
expect(markerBadgePalette('#14b8a6')).toEqual({ top: '#14b8a6', bottom: '#0d9488', border: '#5eead4', ink: '#042f2e' });
expect(markerBadgePalette('#a855f7')).toEqual({ top: '#a855f7', bottom: '#7e22ce', border: '#d8b4fe', ink: '#3b0764' });
expect(markerBadgePalette('#f59e0b').border).toBe('#fef3c7');
});
test('compact dots are optional; complete badges keep marker identity, anchors and batched rendering', () => {
const previousDocument = globalThis.document, previousWindow = globalThis.window;
const previousCompact = getInteractableCompactDotsEnabled();
const canvases = [];
globalThis.window = { innerWidth: 1280, innerHeight: 720, devicePixelRatio: 1 };
globalThis.document = { createElement() {
const trace = [];
const canvas = { width: 128, height: 128, trace, getContext() { return new Proxy({}, {
get(_target, key) { if (key === 'createLinearGradient' || key === 'createRadialGradient') return () => ({ addColorStop() {} });
if (key === 'measureText') return () => ({ width: 10 });
return (...args) => { trace.push([key, ...args]); };
},
}); } };
canvases.push(canvas); return canvas;
} };
let layer;
try {
setInteractableCompactDotsEnabled(false);
layer = createInteractableLayer({ id: 'badge-regression', pointSize: 36, cluster: false,
colors: { normal: '#14b8a6' }, icon: { badge: { color: '#14b8a6' }, colorable: false, draw(context) { context.fillRect(-10, -10, 20, 20); } },
getPosition: item => ({ latitude: item.latitude, longitude: item.longitude }),
});
const earth = new THREE.Object3D(), camera = new THREE.PerspectiveCamera(75, 1280 / 720, 0.1, 5000);
camera.position.z = 350; camera.updateMatrixWorld();
layer.attach(earth); layer.setVisible(true);
layer.setData([{ id: 'same-object', latitude: 15, longitude: 25 }]);
const marker = layer.getMarkers()[0], anchor = marker.position.clone();
layer.updateVisualState(null, null, camera);
const points = layer.group.children.find(group => group.children.some(child => child.isPoints)).children.find(child => child.isPoints);
const badgeTexture = points.material.map;
expect(badgeTexture.image.trace.some(call => call[0] === 'roundRect')).toBe(true);
setInteractableCompactDotsEnabled(true);
layer.updateVisualState(null, null, camera);
let dotTexture;
layer.group.traverse(object => { if (object.isPoints && object.userData.markers?.length) dotTexture = object.material.map; });
expect(dotTexture.image.trace.some(call => call[0] === 'roundRect')).toBe(false);
expect(layer.getMarkers()[0]).toBe(marker);
expect(marker.position.distanceTo(anchor)).toBe(0);
layer.setMarkerState(marker, 'locked');
expect(marker.userData.state).toBe('locked');
} finally {
layer?.clearData();
setInteractableCompactDotsEnabled(previousCompact);
globalThis.document = previousDocument; globalThis.window = previousWindow;
}
});
@@ -0,0 +1,43 @@
// Smooth rendering between propagated orbit samples; never propagate synthetic
// orbits or lerp satellite identities. Radial normalization avoids chord sinking.
export function createSatelliteMotion() {
let from = new Float32Array(), target = new Float32Array(), rendered = new Float32Array();
let startedAt = 0, duration = 1, lastAlpha = -1;
function sample(now, output) {
if (!target.length) return false;
const alpha = Math.max(0, Math.min(1, (now - startedAt) / duration));
if (alpha === lastAlpha) return false;
for (let i = 0; i < target.length; i += 3) {
const a = Math.hypot(from[i], from[i + 1], from[i + 2]);
const b = Math.hypot(target[i], target[i + 1], target[i + 2]);
const x = from[i] + (target[i] - from[i]) * alpha;
const y = from[i + 1] + (target[i + 1] - from[i + 1]) * alpha;
const z = from[i + 2] + (target[i + 2] - from[i + 2]) * alpha;
const length = Math.hypot(x, y, z);
const scale = length > 1e-8 ? (a + (b - a) * alpha) / length : 0;
rendered[i] = output[i] = x * scale;
rendered[i + 1] = output[i + 1] = y * scale;
rendered[i + 2] = output[i + 2] = z * scale;
}
lastAlpha = alpha;
return true;
}
return {
push(values, now, intervalMs) {
if (target.length !== values.length || !target.length) {
from = new Float32Array(values); target = new Float32Array(values); rendered = new Float32Array(values);
} else {
sample(now, rendered);
from.set(rendered); target.set(values);
for (let i = 0; i < target.length; i += 3) {
const dot = from[i] * target[i] + from[i + 1] * target[i + 1] + from[i + 2] * target[i + 2];
// A large discontinuity means data/altitude was replaced, not motion.
if (dot <= 0) from.set(target.subarray(i, i + 3), i);
}
}
startedAt = now; duration = Math.max(1, intervalMs); lastAlpha = -1;
},
sample,
reset() { from = new Float32Array(); target = new Float32Array(); rendered = new Float32Array(); lastAlpha = -1; },
};
}
@@ -0,0 +1,35 @@
import { expect, test } from 'bun:test';
import { createSatelliteMotion } from './satellite-motion.js';
test('orbit samples move smoothly at render cadence without sinking inside their radius', () => {
const motion=createSatelliteMotion(), out=new Float32Array(3);
motion.push(new Float32Array([100,0,0]),0,250); motion.sample(0,out);
motion.push(new Float32Array([0,100,0]),0,250);
let previous=0;
for(let time=0;time<=250;time+=10){
motion.sample(time,out);
expect(Math.hypot(...out)).toBeCloseTo(100,4);
expect(out[1]).toBeGreaterThanOrEqual(previous); previous=out[1];
}
expect(out[1]).toBeCloseTo(100,5);
expect(motion.sample(300,out)).toBe(false);
});
test('a new worker sample rebases from the displayed position without a jump',()=>{
const motion=createSatelliteMotion(),out=new Float32Array(3);
motion.push(new Float32Array([100,0,0]),0,250); motion.sample(0,out);
motion.push(new Float32Array([90,44,0]),0,250); motion.sample(100,out);
const before=out.slice();
motion.push(new Float32Array([80,60,0]),100,250); motion.sample(100,out);
expect([...out]).toEqual([...before]);
motion.sample(116,out); expect(out[1]).toBeGreaterThan(before[1]);
});
test('reset, count changes and discontinuous replacement do not blend unrelated satellites',()=>{
const motion=createSatelliteMotion(),out=new Float32Array(6);
motion.push(new Float32Array([100,0,0]),0,250); motion.sample(0,out);
motion.reset(); motion.push(new Float32Array([0,100,0,0,0,120]),100,250); motion.sample(100,out);
expect([...out]).toEqual([0,100,0,0,0,120]);
motion.push(new Float32Array([0,-100,0,0,0,120]),200,250); motion.sample(200,out);
expect([...out]).toEqual([0,-100,0,0,0,120]);
});
@@ -0,0 +1,57 @@
import * as THREE from 'three';
export const ORBIT_VISUAL = Object.freeze({
visibleFraction: 0.96,
sampleSeconds: 10,
flowRepeats: 16,
flowSpeed: 0.45,
endFade: 0.015,
});
export function openOrbitSampleTimes(periodSeconds) {
const duration = periodSeconds * ORBIT_VISUAL.visibleFraction;
const segments = Math.max(2, Math.ceil(duration / ORBIT_VISUAL.sampleSeconds));
return Array.from({ length: segments + 1 }, (_, index) => duration * index / segments);
}
export function createOrbitFlowGeometry(points) {
const positions = new Float32Array(points.length * 3);
const distance = new Float32Array(points.length);
points.forEach((point, index) => {
point.toArray(positions, index * 3);
if (index) distance[index] = distance[index - 1] + point.distanceTo(points[index - 1]);
});
const length = distance[distance.length - 1] || 1;
for (let i = 0; i < distance.length; i++) distance[i] /= length;
const geometry = new THREE.BufferGeometry();
geometry.setAttribute('position', new THREE.BufferAttribute(positions, 3));
geometry.setAttribute('orbitProgress', new THREE.BufferAttribute(distance, 1));
return geometry;
}
export function createOrbitFlowMaterial(color) {
return new THREE.ShaderMaterial({
uniforms: { uColor: { value: new THREE.Color(color) }, uTime: { value: 0 } },
transparent: true, depthTest: true, depthWrite: false, toneMapped: false,
vertexShader: `
attribute float orbitProgress;
varying float vProgress;
void main() {
vProgress = orbitProgress;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
fragmentShader: `
uniform vec3 uColor;
uniform float uTime;
varying float vProgress;
void main() {
// Increasing progress is increasing prediction time / travel direction.
float phase = fract(vProgress * ${ORBIT_VISUAL.flowRepeats.toFixed(1)} - uTime * ${ORBIT_VISUAL.flowSpeed.toFixed(2)});
float pulse = smoothstep(0.45, 0.95, phase) * (1.0 - smoothstep(0.95, 1.0, phase));
float ends = smoothstep(0.0, ${ORBIT_VISUAL.endFade}, vProgress) * (1.0 - smoothstep(${1 - ORBIT_VISUAL.endFade}, 1.0, vProgress));
gl_FragColor = vec4(mix(uColor, vec3(1.0), pulse * 0.65), (0.56 + 0.44 * pulse) * ends);
}
`,
});
}
@@ -0,0 +1,28 @@
import { expect, test } from "bun:test";
import * as THREE from "three";
import { openOrbitSampleTimes, createOrbitFlowGeometry } from "./satellite-orbit-visual.js";
test("prediction samples form an open chronological arc with no overshoot or closing chord", () => {
for (const period of [5573.7, 86400]) {
const times = openOrbitSampleTimes(period);
expect(times[0]).toBe(0);
expect(times.at(-1)).toBeLessThan(period);
const points = times.map(time => new THREE.Vector3(Math.cos(time / period * 2 * Math.PI), Math.sin(time / period * 2 * Math.PI), 0));
const geometry = createOrbitFlowGeometry(points);
const positions = geometry.attributes.position;
expect(positions.count).toBe(points.length);
expect(new THREE.Vector3().fromBufferAttribute(positions, 0).distanceTo(new THREE.Vector3().fromBufferAttribute(positions, positions.count - 1))).toBeGreaterThan(0.1);
for (let i = 1; i < times.length; i++) expect(times[i]).toBeGreaterThan(times[i - 1]);
geometry.dispose();
}
});
test("flow progress follows distance and chronological direction across unequal orbit segments", () => {
const points = [new THREE.Vector3(0,0,0),new THREE.Vector3(1,0,0),new THREE.Vector3(1,3,0)];
const geometry = createOrbitFlowGeometry(points);
expect([...geometry.attributes.orbitProgress.array]).toEqual([0,0.25,1]);
geometry.dispose();
const degenerate = createOrbitFlowGeometry([points[0],points[0]]);
expect([...degenerate.attributes.orbitProgress.array]).toEqual([0,0]);
degenerate.dispose();
});
+77 -95
View File
@@ -1,3 +1,5 @@
import { ORBIT_VISUAL, openOrbitSampleTimes, createOrbitFlowGeometry, createOrbitFlowMaterial } from "./satellite-orbit-visual.js";
import { createSatelliteMotion } from "./satellite-motion.js";
// satellites.js - Satellite visualization module with real SGP4 positions and animations
import * as THREE from "three";
@@ -33,6 +35,7 @@ let showSatellites = false;
let showTrails = true;
let selectedSatellite = null;
let satellitePositions = [];
const satelliteMotion = createSatelliteMotion();
let hoverRingSprite = null;
let lockedRingSprite = null;
let lockedDotSprite = null;
@@ -220,7 +223,7 @@ function createSatellitePointMaterial({
}) {
return new THREE.ShaderMaterial({
uniforms: {
pointTexture: { value: texture },
...(texture ? { pointTexture: { value: texture } } : {}),
size: { value: size * getPointPixelRatio() },
opacity: { value: opacity },
baseColor: { value: new THREE.Color(baseColor) },
@@ -259,16 +262,30 @@ function createSatellitePointMaterial({
}
`,
fragmentShader: `
uniform sampler2D pointTexture;
${useVertexColor ? "" : "uniform sampler2D pointTexture;"}
uniform float opacity;
varying float vAlpha;
varying vec3 vColor;
void main() {
${useVertexColor ? `
vec2 disc = (gl_PointCoord - 0.5) * 2.0;
float distanceSquared = dot(disc, disc);
float edge = 1.0 - smoothstep(0.72, 1.0, distanceSquared);
float depth = sqrt(max(0.0, 1.0 - distanceSquared));
float light = 0.82 + 0.18 * max(dot(normalize(vec3(-disc.x, disc.y, depth)), normalize(vec3(-0.3, 0.4, 1.0))), 0.0);
float brightness = max(vColor.r, max(vColor.g, vColor.b));
// Stable category hue on both hemispheres; only a small core highlight.
vec3 particleColor = mix(vColor, vec3(brightness), pow(depth, 12.0) * 0.12);
float alphaValue = edge * opacity * vAlpha;
if (alphaValue < 0.02) discard;
gl_FragColor = vec4(particleColor * light, alphaValue);
` : `
vec4 texel = texture2D(pointTexture, gl_PointCoord);
float alphaValue = texel.a * opacity * vAlpha;
if (alphaValue < ${alphaTest.toFixed(3)}) discard;
gl_FragColor = vec4(vColor * texel.rgb, alphaValue);
`}
}
`,
});
@@ -278,7 +295,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "equatorial",
label: "赤道轨道(0-30°)",
color: "#ff3333",
color: "#3399ff",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 0 && inclination < 30;
@@ -287,7 +304,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "low",
label: "低倾角轨道(30-60°)",
color: "#ff9933",
color: "#ff801a",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 30 && inclination < 60;
@@ -296,7 +313,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "medium",
label: "中倾角轨道(60-90°)",
color: "#ffff33",
color: "#00e680",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 60 && inclination < 90;
@@ -305,7 +322,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "high",
label: "高倾角轨道(90-120°)",
color: "#33ff33",
color: "#cc33ff",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 90 && inclination < 120;
@@ -314,7 +331,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "retrograde",
label: "逆行轨道(120-180°)",
color: "#3333ff",
color: "#ff3366",
match: (props) => {
const inclination = Number(props?.inclination ?? 0);
return inclination >= 120 && inclination <= 180;
@@ -323,7 +340,7 @@ const SATELLITE_LEGEND_RULES = [
{
key: "other",
label: "其他",
color: "#d7e2f4",
color: "#94a3b8",
match: () => true,
},
];
@@ -399,9 +416,9 @@ export function updateSatelliteIdleBreathingVisual(isIdle = true) {
}
if (satelliteBackdropPoints.material.uniforms?.opacity) {
satelliteBackdropPoints.material.uniforms.opacity.value = 0.42;
satelliteBackdropPoints.material.uniforms.opacity.value = SATELLITE_CONFIG.dotOutlineOpacity;
} else {
satelliteBackdropPoints.material.opacity = 0.42;
satelliteBackdropPoints.material.opacity = SATELLITE_CONFIG.dotOutlineOpacity;
}
for (const points of [satellitePoints, satelliteBackdropPoints]) {
@@ -506,36 +523,6 @@ function disposeObjectTree(object, parent = earthObjRef) {
disposeObject3D(object, parent);
}
function createDotTexture() {
const canvas = document.createElement("canvas");
canvas.width = DOT_TEXTURE_SIZE;
canvas.height = DOT_TEXTURE_SIZE;
const ctx = canvas.getContext("2d");
const center = DOT_TEXTURE_SIZE / 2;
const radius = center - 2;
const gradient = ctx.createRadialGradient(
center,
center,
0,
center,
center,
radius,
);
gradient.addColorStop(0, "rgba(255, 255, 255, 1)");
gradient.addColorStop(0.5, "rgba(255, 255, 255, 0.8)");
gradient.addColorStop(1, "rgba(255, 255, 255, 0)");
ctx.fillStyle = gradient;
ctx.beginPath();
ctx.arc(center, center, radius, 0, Math.PI * 2);
ctx.fill();
const texture = new THREE.CanvasTexture(canvas);
texture.needsUpdate = true;
return texture;
}
function createBackdropDotTexture() {
const canvas = document.createElement("canvas");
canvas.width = DOT_TEXTURE_SIZE;
@@ -607,7 +594,6 @@ function createFilledCircleTexture(color = "#ffcc00") {
export function createSatellites(scene, earthObj) {
initSatelliteScene(scene, earthObj);
const dotTexture = createDotTexture();
const backdropTexture = createBackdropDotTexture();
const pointsGeometry = new THREE.BufferGeometry();
@@ -618,13 +604,12 @@ export function createSatellites(scene, earthObj) {
texture: backdropTexture,
useVertexColor: false,
baseColor: 0x0b1626,
opacity: 0.42,
opacity: SATELLITE_CONFIG.dotOutlineOpacity,
alphaTest: 0.04,
});
const pointsMaterial = createSatellitePointMaterial({
size: getSatelliteDotBaseSize(),
texture: dotTexture,
useVertexColor: true,
opacity: 0.9,
alphaTest: 0.1,
@@ -759,6 +744,7 @@ function clearSatelliteTrailGeometry() {
}
function clearSatelliteTrails() {
satelliteMotion.reset();
resetSatelliteTrailState();
clearSatelliteTrailGeometry();
if (satelliteData.length) startSatellitePositionWorker();
@@ -1020,6 +1006,7 @@ export async function loadSatellites(options = {}) {
const data = await response.json();
satelliteData = data.features || [];
satelliteMotion.reset();
satellitePropagator.reset();
resetSatelliteTrailState();
ensureSatelliteCapacity(satelliteData.length);
@@ -1055,6 +1042,7 @@ export function updateSatellitePositions(deltaTime = 0, force = false, options =
positionUpdateAccumulator += deltaTime;
}
renderSatelliteMotion();
if (!force && positionUpdateAccumulator < POSITION_UPDATE_INTERVAL_MS) {
return;
}
@@ -1078,6 +1066,7 @@ export function updateSatellitePositions(deltaTime = 0, force = false, options =
return;
}
applySatellitePositionSnapshot({ baseTime: Date.now() + elapsedMs }, shouldUpdateTrails);
renderSatelliteMotion();
}
function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
@@ -1213,8 +1202,10 @@ function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
instanceColorEnds[base + 2] = b * fallbackAlphaEnd;
trailSegmentCount++;
}
satPosition.renderTrailTipOffset = (trailSegmentCount - 1) * 3;
}
satelliteMotion.push(positions.subarray(0, count * 3), performance.now(), POSITION_UPDATE_INTERVAL_MS);
for (let i = count; i < satelliteCapacity; i++) {
positions[i * 3] = 0;
positions[i * 3 + 1] = 0;
@@ -1269,6 +1260,29 @@ function applySatellitePositionSnapshot(snapshot, shouldUpdateTrails) {
}
}
function renderSatelliteMotion() {
if (!showSatellites && lockedSatelliteIndex === null && hoveredSatelliteIndex === null) return;
if (!satellitePoints || !satelliteBackdropPoints || !satellitePositions.length) return;
const positions = satellitePoints.geometry.attributes.position;
if (!satelliteMotion.sample(performance.now(), positions.array)) return;
const count = Math.min(satelliteData.length, satelliteCapacity);
const backdrop = satelliteBackdropPoints.geometry.attributes.position;
backdrop.array.set(positions.array.subarray(0, count * 3));
const trailEnds = satelliteTrails.geometry.attributes.instanceEnd;
const now = Date.now();
for (let i = 0; i < count; i++) {
const state = satellitePositions[i];
state.current.fromArray(positions.array, i * 3);
state.currentTime?.setTime(getSatelliteSampleTimeMs(now, i, count));
if (showTrails && state.renderTrailTipOffset >= 0) {
state.current.toArray(trailEnds.array, state.renderTrailTipOffset);
}
}
positions.needsUpdate = true;
backdrop.needsUpdate = true;
if (showTrails) trailEnds.needsUpdate = true;
}
export function toggleSatellites(visible) {
showSatellites = visible;
if (satelliteBackdropPoints) {
@@ -1559,8 +1573,8 @@ function createGroundFootprintMaterial() {
depthTest: true,
depthWrite: false,
uniforms: {
uColor: { value: new THREE.Color(0xffffff) },
uOpacity: { value: 0.46 },
uColor: { value: new THREE.Color(SATELLITE_CONFIG.footprintColor) },
uOpacity: { value: SATELLITE_CONFIG.footprintOpacity },
uMajorKm: { value: 1000 },
uMinorKm: { value: 700 },
uGapCenterNorthKm: { value: 0 },
@@ -1576,7 +1590,7 @@ function createGroundFootprintMaterial() {
uGapSoftnessKm: { value: 6 },
uGlowMode: { value: 0 },
uSunDirectionWorld: { value: satelliteSunDirection.clone() },
uDayVisibilityBoost: { value: 1.48 },
uDayVisibilityBoost: { value: SATELLITE_CONFIG.footprintDayVisibilityBoost },
},
vertexShader: `
varying vec3 vWorldPosition;
@@ -1654,12 +1668,10 @@ function createGroundFootprintMaterial() {
float daylight = clamp(sunFacing * 0.5 + 0.5, 0.0, 1.0);
alpha *= mix(1.0, uDayVisibilityBoost, daylight);
vec3 nightColor = vec3(0.24, 0.56, 1.0);
vec3 dayColor = vec3(1.0, 0.72, 0.08);
vec3 finalColor = mix(nightColor, dayColor, daylight);
// A footprint keeps one blue hue. Daylight only raises contrast through
// opacity; it must never recolor the same coverage patch yellow.
if (alpha <= 0.001) discard;
gl_FragColor = vec4(finalColor, alpha);
gl_FragColor = vec4(uColor, alpha);
}
`,
});
@@ -2345,7 +2357,7 @@ function applyDimMaterialState(isDimmed) {
}
}
if (satelliteBackdropPoints) {
const opacity = isDimmed ? DIMMED_SATELLITE_BACKDROP_OPACITY : 0.42;
const opacity = isDimmed ? DIMMED_SATELLITE_BACKDROP_OPACITY : SATELLITE_CONFIG.dotOutlineOpacity;
if (satelliteBackdropPoints.material.uniforms?.opacity) {
satelliteBackdropPoints.material.uniforms.opacity.value = opacity;
} else {
@@ -2446,15 +2458,14 @@ function calculateOrbitalPeriod(meanMotion) {
function calculatePredictedOrbit(
satellite,
periodSeconds,
sampleInterval = 10,
) {
const points = [];
const samples = Math.ceil(periodSeconds / sampleInterval);
const sampleTimes = openOrbitSampleTimes(periodSeconds);
const startTime = getSelectedSatellitePositionState(satellite)?.currentTime || new Date();
const fixedSiderealTime = gstime(startTime);
for (let i = 0; i <= samples; i++) {
const time = new Date(startTime.getTime() + i * sampleInterval * 1000);
for (const offsetSeconds of sampleTimes) {
const time = new Date(startTime.getTime() + offsetSeconds * 1000);
const pos = computeSatelliteInertialOrbitPosition(
satellite,
time,
@@ -2463,21 +2474,13 @@ function calculatePredictedOrbit(
if (pos) points.push(pos);
}
if (points.length < samples * 0.5) {
return calculateFallbackPredictedOrbit(satellite, samples);
if (points.length < sampleTimes.length * 0.5) {
return calculateFallbackPredictedOrbit(satellite, sampleTimes.length - 1);
}
closeOrbitLoop(points);
return points;
}
function closeOrbitLoop(points) {
if (points.length > 2) {
points.push(points[0].clone());
}
}
function calculateFallbackPredictedOrbit(satellite, samples) {
const points = [];
const radius =
@@ -2492,7 +2495,7 @@ function calculateFallbackPredictedOrbit(satellite, samples) {
const sinInclination = Math.sin(inclinationRad);
for (let i = 0; i <= samples; i++) {
const argument = (i / samples) * Math.PI * 2;
const argument = (i / samples) * Math.PI * 2 * ORBIT_VISUAL.visibleFraction;
const cosArgument = Math.cos(argument);
const sinArgument = Math.sin(argument);
@@ -2509,7 +2512,6 @@ function calculateFallbackPredictedOrbit(satellite, samples) {
points.push(new THREE.Vector3(ecfX, ecfZ, -ecfY));
}
closeOrbitLoop(points);
return points;
}
@@ -2537,34 +2539,13 @@ export function showPredictedOrbit(satellite) {
const points = calculatePredictedOrbit(satellite, periodSeconds);
if (points.length < 2) return;
const positions = new Float32Array(points.length * 3);
const colors = new Float32Array(points.length * 3);
for (let i = 0; i < points.length; i++) {
positions[i * 3] = points[i].x;
positions[i * 3 + 1] = points[i].y;
positions[i * 3 + 2] = points[i].z;
const t = i / (points.length - 1);
colors[i * 3] = 1 - t * 0.4;
colors[i * 3 + 1] = 1 - t * 0.6;
colors[i * 3 + 2] = t;
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(positions, 3));
geometry.setAttribute("color", new THREE.BufferAttribute(colors, 3));
const material = new THREE.LineBasicMaterial({
vertexColors: true,
transparent: true,
opacity: 0.8,
blending: THREE.AdditiveBlending,
depthTest: true,
depthWrite: false,
});
const geometry = createOrbitFlowGeometry(points);
const material = createOrbitFlowMaterial(getSatelliteLegendRule(satellite.properties).color);
predictedOrbitLine = new THREE.Line(geometry, material);
const startedAt = performance.now();
predictedOrbitLine.onBeforeRender = () => {
material.uniforms.uTime.value = (performance.now() - startedAt) / 1000;
};
predictedOrbitLine.renderOrder = SATELLITE_CONFIG.overlayRenderOrder;
earthObjRef.add(predictedOrbitLine);
}
@@ -2577,6 +2558,7 @@ export function hidePredictedOrbit() {
}
export function clearSatelliteData() {
satelliteMotion.reset();
stopSatellitePositionWorker();
satelliteData = [];
satellitePropagator.reset();
+1
View File
@@ -198,6 +198,7 @@ const vesselIconLayer = createInteractableLayer({
},
avoidance: false,
icon: {
badge: true,
draw(context, { marker, rotationBin = 0, glow = false, color = "#ffffff" }) {
const anchored = Boolean(marker?.userData?.anchored);
if (!anchored) {
+20 -70
View File
@@ -45,6 +45,10 @@ import { ControlGroup as TactileControlGroup } from '../../components/tactile-ui
import { useToast } from '../components/ui/toast'
import { DetailPanel, EmptyState, PageFrame, Panel, StatCell, StatusText, SummaryStrip } from '../patterns/patterns'
import { ComputeComparisonSettings } from './ComputeComparisonSettings'
import {
COLLECTION_QUEUE_ACTIVE_STATUSES, isStaleTaskUpdate, patchCollectionTask, upsertCollectionTask,
type CollectionQueueItem, type CollectionQueueStatus,
} from './datasource-task-queue'
type AnyRecord = Record<string, unknown>
type Tone = 'success' | 'warning' | 'danger' | 'info' | 'neutral' | 'running' | 'ai'
@@ -103,28 +107,6 @@ type DatasourceFilters = {
dataStatus: string
}
type CollectionQueueStatus = 'queued' | 'running' | 'cancelling' | 'success' | 'failed' | 'skipped' | 'cancelled'
type CollectionQueueItem = {
key: string
sourceId: string
source?: string
name: string
taskId?: number | string | null
taskType?: string
status: CollectionQueueStatus
phase?: string
phaseMessage?: string
progress?: number | null
recordsProcessed?: number | null
totalRecords?: number | null
reason?: string
error?: string
createdAt: number
updatedAt: number
completedAt?: number
}
type DatasourceMetricBaseline = {
taskId: string
sourceId: string
@@ -146,7 +128,6 @@ const DEFAULT_DATASOURCE_FILTERS: DatasourceFilters = {
const DATASOURCE_FILTER_STORAGE_KEY = 'planet.admin.datasource.filters'
const DATASOURCE_FILTER_QUERY_KEYS = ['product', 'module', 'is_active', 'run_status', 'data_status']
const DATASOURCE_TERMINAL_STATUSES = new Set(['success', 'completed', 'failed', 'cancelled', 'canceled', 'stopped'])
const COLLECTION_QUEUE_ACTIVE_STATUSES = new Set<CollectionQueueStatus>(['queued', 'running', 'cancelling'])
const TASK_ACTIVE_STATUSES = new Set(['queued', 'pending', 'running', 'cancelling'])
const TASK_INACTIVE_STATUSES = new Set(['success', 'completed', 'failed', 'error', 'cancelled', 'canceled', 'stopped', 'idle'])
@@ -426,10 +407,6 @@ function queueItemKey(item: AnyRecord) {
return source ? `source-name:${taskType}:${source}` : `queue:${taskType}:${Date.now()}`
}
function isSameQueueTaskType(left?: string, right?: string) {
return text(left, 'collect') === text(right, 'collect')
}
function isActiveQueueStatus(status: CollectionQueueStatus) {
return COLLECTION_QUEUE_ACTIVE_STATUSES.has(status)
}
@@ -3219,49 +3196,22 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
}, [])
const upsertCollectionQueueItem = useCallback((item: CollectionQueueItem) => {
setCollectionQueue((current) => {
const index = current.findIndex((existing) => (
existing.key === item.key
|| (item.taskId && existing.taskId === item.taskId)
|| (isActiveQueueStatus(existing.status) && isSameQueueTaskType(existing.taskType, item.taskType) && item.sourceId && existing.sourceId === item.sourceId)
|| (isActiveQueueStatus(existing.status) && isSameQueueTaskType(existing.taskType, item.taskType) && item.source && existing.source === item.source)
))
if (index < 0) return [item, ...current]
const next = [...current]
next[index] = { ...next[index], ...item, key: next[index].key, createdAt: next[index].createdAt || item.createdAt }
return next
})
setCollectionQueue(current => upsertCollectionTask(current, item))
}, [])
const patchCollectionQueueFromTask = useCallback((payload: AnyRecord) => {
const sourceId = text(payload.datasource_id || payload.source_id || payload.id, '')
const source = text(payload.collector_name || payload.source, '')
const taskId = payload.task_id as number | string | null | undefined
const status = queueStatusFromTask(payload.status || payload.phase, payload.is_running)
const payloadTaskType = text(payload.task_type, '')
setCollectionQueue((current) => current.map((item) => {
const taskTypeMatched = !payloadTaskType || isSameQueueTaskType(item.taskType, payloadTaskType)
const matched = Boolean(taskId && item.taskId === taskId)
|| (taskTypeMatched && Boolean(sourceId && item.sourceId === sourceId))
|| (taskTypeMatched && Boolean(source && item.source === source))
if (!matched) return item
const terminal = ['success', 'failed', 'cancelled', 'skipped'].includes(status)
return {
...item,
taskId: taskId ?? item.taskId,
taskType: text(payload.task_type, item.taskType || ''),
sourceId: sourceId || item.sourceId,
source: source || item.source,
status,
phase: text(payload.phase, item.phase || ''),
phaseMessage: text(payload.phase_message, item.phaseMessage || ''),
progress: typeof payload.progress === 'number' ? payload.progress : item.progress,
recordsProcessed: typeof payload.records_processed === 'number' ? payload.records_processed : item.recordsProcessed,
totalRecords: typeof payload.total_records === 'number' ? payload.total_records : item.totalRecords,
error: text(payload.error_message, item.error || ''),
updatedAt: Date.now(),
completedAt: terminal ? Date.now() : item.completedAt,
}
setCollectionQueue(current => patchCollectionTask(current, {
sourceId: text(payload.datasource_id || payload.source_id || payload.id, '') || undefined,
source: text(payload.collector_name || payload.source, '') || undefined,
taskId: payload.task_id as number | string | null | undefined,
taskType: text(payload.task_type, '') || undefined,
status: queueStatusFromTask(payload.status || payload.phase, payload.is_running),
phase: payload.phase == null ? undefined : text(payload.phase, ''),
phaseMessage: payload.phase_message == null ? undefined : text(payload.phase_message, ''),
progress: typeof payload.progress === 'number' ? payload.progress : undefined,
recordsProcessed: typeof payload.records_processed === 'number' ? payload.records_processed : undefined,
totalRecords: typeof payload.total_records === 'number' ? payload.total_records : undefined,
error: payload.error_message == null ? undefined : text(payload.error_message, ''),
}))
}, [])
@@ -3391,14 +3341,14 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
return {
...state,
rows: state.rows.map((row) => {
if (!isSameDatasourceRow(row, sourceId, source)) return row
if (!isSameDatasourceRow(row, sourceId, source) || isStaleTaskUpdate(row.task_id, payload.task_id, activeDatasourceTaskStatus(row), taskStatus)) return row
const merged = applyLiveMetric(row, { ...row, ...rowPatch, id: row.id, source: row.source })
return normalizeDatasourceTableRecord(merged)
}),
}
}))
setSelected((current) => {
if (!current || !isSameDatasourceRow(current, sourceId, source)) return current
if (!current || !isSameDatasourceRow(current, sourceId, source) || isStaleTaskUpdate(current.task_id, payload.task_id, activeDatasourceTaskStatus(current), taskStatus)) return current
const merged = applyLiveMetric(current, { ...current, ...rowPatch, id: current.id, source: current.source })
return normalizeDatasourceTableRecord(merged)
})
@@ -3414,7 +3364,7 @@ function ModuleConsole({ config }: { config: ModuleConfig }) {
completedDatasourceTasksRef.current.add(pendingKey)
const pendingEntry = pendingDatasourceTasksRef.current[pendingKey]
? [pendingKey, pendingDatasourceTasksRef.current[pendingKey]] as const
: Object.entries(pendingDatasourceTasksRef.current).find(([, item]) => isSameDatasourceRow({ id: item.sourceId, source: item.source }, sourceId, source))
: !payload.task_id ? Object.entries(pendingDatasourceTasksRef.current).find(([, item]) => !item.taskId && isSameDatasourceRow({ id: item.sourceId, source: item.source }, sourceId, source)) : undefined
const pending = pendingEntry?.[1]
const lookupId = sourceId || pending?.sourceId || source
if (!lookupId) return
@@ -0,0 +1,69 @@
export type CollectionQueueStatus = 'queued' | 'running' | 'cancelling' | 'success' | 'failed' | 'skipped' | 'cancelled'
export type CollectionQueueItem = {
key: string
sourceId: string
source?: string
name: string
taskId?: number | string | null
taskType?: string
status: CollectionQueueStatus
phase?: string
phaseMessage?: string
progress?: number | null
recordsProcessed?: number | null
totalRecords?: number | null
reason?: string
error?: string
createdAt: number
updatedAt: number
completedAt?: number
}
type QueueUpdate = Partial<CollectionQueueItem> & Pick<CollectionQueueItem, 'status'>
export const COLLECTION_QUEUE_ACTIVE_STATUSES = new Set<CollectionQueueStatus>(['queued', 'running', 'cancelling'])
const taskId = (value: unknown) => value == null ? '' : String(value)
function sameAttempt(existing: CollectionQueueItem, update: Partial<CollectionQueueItem>) {
const existingId = taskId(existing.taskId)
const incomingId = taskId(update.taskId)
if (existing.taskType && update.taskType && existing.taskType !== update.taskType) return false
if (existingId) return Boolean(incomingId) && existingId === incomingId
// Only an active, ID-less placeholder may bind to its server task.
if (!COLLECTION_QUEUE_ACTIVE_STATUSES.has(existing.status)) return false
if (existing.sourceId && update.sourceId) return existing.sourceId === update.sourceId
return Boolean(existing.source && update.source && existing.source === update.source)
}
function mergeAttempt(existing: CollectionQueueItem, update: QueueUpdate, now: number): CollectionQueueItem {
// Delayed polling/WS events cannot resurrect or reclassify a finished attempt.
if (!COLLECTION_QUEUE_ACTIVE_STATUSES.has(existing.status) && update.status !== existing.status) return existing
const merged = { ...existing }
for (const [key, value] of Object.entries(update)) {
if (value !== undefined && key !== 'createdAt' && key !== 'key') Object.assign(merged, { [key]: value })
}
merged.key = taskId(merged.taskId) ? `task:${merged.taskType || 'collect'}:${taskId(merged.taskId)}` : existing.key
merged.updatedAt = now
merged.completedAt = COLLECTION_QUEUE_ACTIVE_STATUSES.has(merged.status) ? undefined : existing.completedAt ?? now
return merged
}
export function upsertCollectionTask(current: CollectionQueueItem[], item: CollectionQueueItem) {
const index = current.findIndex(existing => sameAttempt(existing, item))
if (index < 0) return [item, ...current]
return current.map((existing, i) => i === index ? mergeAttempt(existing, item, item.updatedAt) : existing)
}
export function patchCollectionTask(current: CollectionQueueItem[], update: QueueUpdate, now = Date.now()) {
return current.map(existing => sameAttempt(existing, update) ? mergeAttempt(existing, update, now) : existing)
}
// The datasource row is the latest attempt, while the queue holds all attempts.
export function isStaleTaskUpdate(currentId: unknown, incomingId: unknown, currentStatus?: string, incomingStatus?: string) {
const current = taskId(currentId), incoming = taskId(incomingId)
if (!current) return false
if (!incoming) return true
const terminal = ['success', 'completed', 'failed', 'error', 'cancelled', 'canceled', 'skipped', 'stopped']
if (current === incoming && currentStatus && incomingStatus && terminal.includes(currentStatus) && !terminal.includes(incomingStatus)) return true
return /^\d+$/.test(current) && /^\d+$/.test(incoming) && Number(incoming) < Number(current)
}
+2 -1
View File
@@ -8,6 +8,7 @@ import {
EyeOff,
FileText,
ImageUp,
ListChecks,
Pause,
Pickaxe,
Play,
@@ -56,7 +57,7 @@ export const tactileIconPresets = {
send: Send,
settings: SlidersHorizontal,
start: Play,
status: RefreshCw,
status: ListChecks,
stop: Square,
test: Unplug,
plug: Plug,
@@ -0,0 +1,60 @@
import { expect, test } from 'bun:test'
import { patchCollectionTask, upsertCollectionTask, isStaleTaskUpdate, type CollectionQueueItem } from '../src/admin/pages/datasource-task-queue'
const item = (id: number | string | null, status: CollectionQueueItem['status'] = 'failed', type = 'collect'): CollectionQueueItem => ({
key: id == null ? `source:${type}:20` : `task:${type}:${id}`, taskId: id, sourceId: '20', source: 'celestrak_tle', name: 'CelesTrak', taskType: type,
status, error: status === 'failed' ? `failure-${id}` : undefined, createdAt: 10, updatedAt: 20, completedAt: status === 'failed' ? 20 : undefined,
})
test('a retry creates a new queue attempt and leaves every failed attempt untouched', () => {
const history = [item(97), item(96), item(95)]
let queue = upsertCollectionTask(history, item(98, 'queued'))
queue = patchCollectionTask(queue, { taskId: '98', sourceId: '20', source: 'celestrak_tle', status: 'running', progress: 40 }, 100)
expect(queue).toHaveLength(4)
expect(queue[0].taskId).toBe('98')
expect(queue[0].status).toBe('running')
expect(queue.slice(1)).toEqual(history)
queue = patchCollectionTask(queue, { taskId: 98, sourceId: '20', status: 'failed', error: 'new failure' }, 120)
expect(queue.slice(1)).toEqual(history)
expect(queue[0].completedAt).toBe(120)
})
test('late websocket and upsert events cannot resurrect or reclassify a completed attempt', () => {
const failed = item(97)
expect(patchCollectionTask([failed], { taskId: 97, sourceId: '20', status: 'running' }, 200)).toEqual([failed])
expect(upsertCollectionTask([failed], item('97', 'queued'))).toEqual([failed])
expect(patchCollectionTask([failed], { taskId: 97, status: 'success' }, 200)).toEqual([failed])
expect(patchCollectionTask([failed], { taskId: 97, status: 'failed', error: 'more detail' }, 200)[0].completedAt).toBe(20)
})
test('same-source concurrent attempts and different task types are independent', () => {
const queue = upsertCollectionTask([item(98, 'running')], item(99, 'queued'))
expect(queue).toHaveLength(2)
expect(patchCollectionTask(queue, { taskId: 98, sourceId: '20', status: 'failed' })[0].status).toBe('queued')
expect(patchCollectionTask([item(98, 'running')], { taskId: 98, taskType: 'clear_data', status: 'success' })[0].status).toBe('running')
})
test('only an active ID-less placeholder binds by source; ID-less updates cannot touch real tasks', () => {
const placeholder = item(null, 'queued')
const bound = patchCollectionTask([placeholder, item(97)], { taskId: 98, sourceId: '20', status: 'running' }, 50)
expect(bound[0].key).toBe('task:collect:98')
expect(bound[0].createdAt).toBe(10)
expect(bound[1]).toEqual(item(97))
expect(patchCollectionTask(bound, { sourceId: '20', status: 'failed' }, 60)).toEqual(bound)
const differentSource = { ...placeholder, sourceId: '21' }
expect(patchCollectionTask([differentSource], { taskId: 99, sourceId: '20', source: 'celestrak_tle', status: 'running' })).toEqual([differentSource])
})
test('old poll responses cannot replace the datasource row for a newer task', () => {
expect(isStaleTaskUpdate(98, '97')).toBe(true)
expect(isStaleTaskUpdate(98, null)).toBe(true)
expect(isStaleTaskUpdate(98, '98')).toBe(false)
expect(isStaleTaskUpdate(98, 99)).toBe(false)
expect(isStaleTaskUpdate(null, 99)).toBe(false)
})
test('late running updates for the same completed task do not reactivate the datasource row', () => {
expect(isStaleTaskUpdate(98, '98', 'failed', 'running')).toBe(true)
expect(isStaleTaskUpdate(98, '98', 'success', 'queued')).toBe(true)
expect(isStaleTaskUpdate(98, '99', 'failed', 'queued')).toBe(false)
})
+4 -1
View File
@@ -3,7 +3,10 @@ setlocal EnableExtensions DisableDelayedExpansion
set "PLANET_LAUNCHER_SOURCE=%~f0"
set "PLANET_LAUNCHER_INSTALL_ONLY="
if /i "%~1"=="--install-only" set "PLANET_LAUNCHER_INSTALL_ONLY=1"
powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "& (Join-Path (Split-Path -LiteralPath $env:PLANET_LAUNCHER_SOURCE) 'scripts\windows\planet-launcher.ps1') -InstallOnly:($env:PLANET_LAUNCHER_INSTALL_ONLY -eq '1')"
set "PLANET_POWERSHELL=powershell.exe"
where.exe pwsh.exe >nul 2>&1
if not errorlevel 1 set "PLANET_POWERSHELL=pwsh.exe"
%PLANET_POWERSHELL% -NoLogo -NoProfile -ExecutionPolicy Bypass -Command "& (Join-Path (Split-Path -LiteralPath $env:PLANET_LAUNCHER_SOURCE) 'scripts\windows\planet-launcher.ps1') -InstallOnly:($env:PLANET_LAUNCHER_INSTALL_ONLY -eq '1')"
set "planet_launcher_exit=%errorlevel%"
if not "%planet_launcher_exit%"=="0" pause
exit /b %planet_launcher_exit%
+1 -1
View File
@@ -1,6 +1,6 @@
[project]
name = "planet"
version = "0.75.1"
version = "0.75.3"
description = "智能星球计划 - 态势感知系统"
requires-python = ">=3.14"
dependencies = [
+1 -1
View File
@@ -540,7 +540,7 @@ Current icons:
| File | Used in | Description |
|------|---------|-------------|
| `marker-landing-point.svg` | `cables.js` | Cable landing point pin |
| `marker-landing-point.svg` | `cables.js` | Flat landing-point micro-core |
| `bgp-collector.svg` | `bgp.js` | BGP collector marker |
| `bgp-glow-dot.svg` | `bgp.js` | Base radial glow dot |
| `bgp-event-ring.svg` | `bgp.js` | Event ring overlay |
+47
View File
@@ -78,3 +78,50 @@ try {
[IO.Path]::GetFileName($resolved) -notlike 'planet-launcher-tests-*') { throw 'Unsafe cleanup path' }
Remove-Item -LiteralPath $resolved -Recurse -Force
}
function Get-Command {
param([string]$Name, [string]$CommandType, [string]$ErrorAction)
if ($script:AvailableLaunchCommands.ContainsKey($Name)) {
return [pscustomobject]@{ Source = $script:AvailableLaunchCommands[$Name] }
}
}
$pwshPath = 'C:\Program Files\PowerShell\7\pwsh.exe'
$terminalPath = 'C:\Users\Test\AppData\Local\Microsoft\WindowsApps\wt.exe'
$legacyPath = 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
foreach ($hasTerminal in @($true, $false)) {
foreach ($hasPwsh in @($true, $false)) {
$script:AvailableLaunchCommands = @{ 'powershell.exe' = $legacyPath }
if ($hasTerminal) { $script:AvailableLaunchCommands['wt.exe'] = $terminalPath }
if ($hasPwsh) { $script:AvailableLaunchCommands['pwsh.exe'] = $pwshPath }
$launch = Get-PlanetTerminalLaunch 'TESTPAYLOAD'
$expectedShell = if ($hasPwsh) { $pwshPath } else { $legacyPath }
$expectedExecutable = if ($hasTerminal) { $terminalPath } else { $expectedShell }
Assert-Equal $expectedExecutable $launch.FilePath 'Terminal/shell priority'
if ($hasTerminal -and -not $launch.ArgumentList.Contains('"' + $expectedShell + '"')) {
throw 'Terminal shell path must be quoted, including Program Files paths'
}
if ($launch.ArgumentList -notmatch '-EncodedCommand TESTPAYLOAD$') {
throw 'Encoded bootstrap was not preserved'
}
}
}
function Test-PlanetAdministrator { return $script:IsTestAdministrator }
function Start-Process {
param($FilePath, $ArgumentList, $WindowStyle, $Verb)
$script:CapturedLaunch = @{ FilePath = $FilePath; ArgumentList = $ArgumentList; Verb = $Verb }
$script:LaunchCount++
}
$script:AvailableLaunchCommands = @{ 'pwsh.exe' = $pwshPath; 'wt.exe' = $terminalPath }
$script:LaunchCount = 0
foreach ($isAdmin in @($false, $true)) {
$script:IsTestAdministrator = $isAdmin
Start-PlanetRestart $target
Assert-Equal $terminalPath $script:CapturedLaunch.FilePath 'Admin and ordinary entry both use Terminal'
if ($isAdmin -and $script:CapturedLaunch.Verb) { throw 'Already elevated entry must not request UAC again' }
if (-not $isAdmin) { Assert-Equal 'RunAs' $script:CapturedLaunch.Verb 'Ordinary entry requires elevation' }
}
$script:IsTestAdministrator = $false
try { Start-PlanetRestart $target -AlreadyElevated; throw 'Unelevated child accepted' }
catch { if ($_.Exception.Message -ne 'Administrator elevation was not granted.') { throw } }
Assert-Equal 2 $script:LaunchCount 'Child must not recursively launch more windows'
Write-Host 'PASS: Terminal/PowerShell priority, quoted paths, elevation and no recursive dispatch'
+30 -6
View File
@@ -114,7 +114,10 @@ function Install-PlanetDesktopLauncher {
'@echo off', 'setlocal EnableExtensions DisableDelayedExpansion', $marker,
'set "PLANET_LAUNCHER_INSTALL_ONLY="',
'if /i "%~1"=="--install-only" set "PLANET_LAUNCHER_INSTALL_ONLY=1"',
"powershell.exe -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand $encoded",
'set "PLANET_POWERSHELL=powershell.exe"',
'where.exe pwsh.exe >nul 2>&1',
'if not errorlevel 1 set "PLANET_POWERSHELL=pwsh.exe"',
"%PLANET_POWERSHELL% -NoLogo -NoProfile -ExecutionPolicy Bypass -EncodedCommand $encoded",
'set "planet_launcher_exit=%errorlevel%"',
'if not "%planet_launcher_exit%"=="0" pause',
'exit /b %planet_launcher_exit%'
@@ -129,18 +132,39 @@ function Test-PlanetAdministrator {
return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
}
function Get-PlanetTerminalLaunch {
param([string]$EncodedCommand)
$shell = Get-Command pwsh.exe -CommandType Application -ErrorAction SilentlyContinue |
Select-Object -First 1
if (-not $shell) {
$shell = Get-Command powershell.exe -CommandType Application -ErrorAction Stop |
Select-Object -First 1
}
$shellArguments = "-NoLogo -NoProfile -NoExit -ExecutionPolicy Bypass -EncodedCommand $EncodedCommand"
$launch = @{ FilePath = $shell.Source; ArgumentList = $shellArguments; WindowStyle = 'Normal' }
$terminal = Get-Command wt.exe -CommandType Application -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($terminal) {
$launch.FilePath = $terminal.Source
# Start-Process joins arguments: quote the executable path explicitly.
$launch.ArgumentList = '-w new new-tab --title Planet "' + $shell.Source + '" ' + $shellArguments
}
return $launch
}
function Start-PlanetRestart {
param([hashtable]$Target, [switch]$AlreadyElevated)
$script:PlanetLauncherExitCode = 0
if (-not (Test-PlanetAdministrator)) {
if ($AlreadyElevated) { throw 'Administrator elevation was not granted.' }
$isAdministrator = Test-PlanetAdministrator
if (-not $AlreadyElevated) {
$encoded = ConvertTo-PlanetEncodedCommand (Get-PlanetBootstrap $Target -RunElevated)
$launch = Get-PlanetTerminalLaunch $encoded
if (-not $isAdministrator) { $launch.Verb = 'RunAs' }
# An interactive terminal is intentional: startup logs and the WSL shell stay visible.
Start-Process powershell.exe -Verb RunAs -WindowStyle Normal -ArgumentList @(
'-NoLogo', '-NoProfile', '-NoExit', '-ExecutionPolicy', 'Bypass', '-EncodedCommand', $encoded
) | Out-Null
Start-Process @launch | Out-Null
return
}
if (-not $isAdministrator) { throw 'Administrator elevation was not granted.' }
Write-Host "Restarting Planet in $($Target.Distro):$($Target.LinuxProjectRoot)"
& wsl.exe -d $Target.Distro --cd $Target.LinuxProjectRoot --exec zsh -l -i ($Target.LinuxProjectRoot + '/scripts/windows/restart.zsh')
$script:PlanetLauncherExitCode = $LASTEXITCODE
Generated
+1 -1
View File
@@ -757,7 +757,7 @@ wheels = [
[[package]]
name = "planet"
version = "0.75.1"
version = "0.75.3"
source = { virtual = "." }
dependencies = [
{ name = "aiofiles" },