diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 01b0768..a0c82f1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -34,6 +34,19 @@ jobs: - name: Tests run: pytest tests/ -v + rust: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@stable + - uses: swatinem/rust-cache@v2 + with: + workspaces: src-tauri -> target + - name: Run tests + run: cargo test -p kopdeltav --manifest-path src-tauri/Cargo.toml + - name: Clippy + run: cargo clippy -p kopdeltav --manifest-path src-tauri/Cargo.toml -- -D warnings + frontend: runs-on: ubuntu-latest defaults: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 9d4bbfe..5e008ff 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -42,15 +42,6 @@ jobs: - name: Install Tauri CLI run: cargo install tauri-cli --version "^2" - - name: Copy Python backend into Tauri resources - run: | - mkdir -p src-tauri/resources/kopdeltav - cp api.py src-tauri/resources/ - cp launcher.py src-tauri/resources/ - cp kopdeltav/*.py src-tauri/resources/kopdeltav/ - cp requirements.txt src-tauri/resources/ - shell: bash - - name: Build Tauri app run: cargo tauri build --bundles nsis working-directory: src-tauri @@ -66,5 +57,5 @@ jobs: with: draft: true name: "KSPDeltaVForMods ${{ github.ref_name }}" - body: "Windows desktop build.\n\n**Requirements:**\n- Python 3.10+\n- `pip install fastapi uvicorn[standard] python-multipart`" + body: "Windows desktop build. No external dependencies required." files: src-tauri/target/release/bundle/nsis/*.exe diff --git a/frontend/src/components/upload/ConfigUpload.vue b/frontend/src/components/upload/ConfigUpload.vue index da0e751..905ce93 100644 --- a/frontend/src/components/upload/ConfigUpload.vue +++ b/frontend/src/components/upload/ConfigUpload.vue @@ -30,7 +30,8 @@ async function onFileSelect(event: FileUploadSelectEvent): Promise { uploading.value = true try { - const uploadResult = await api.uploadConfig(file) + const fileContent = await file.text() + const uploadResult = await api.uploadConfig(fileContent) await afterSuccess(uploadResult.count) } catch (err) { toast.add({ diff --git a/frontend/src/composables/useApi.ts b/frontend/src/composables/useApi.ts index 1090a5c..0924ba9 100644 --- a/frontend/src/composables/useApi.ts +++ b/frontend/src/composables/useApi.ts @@ -1,117 +1,75 @@ +import { invoke } from '@tauri-apps/api/core' import { useToast } from 'primevue/usetoast' import type { AtmoProfileResponse, BodyDetail, BodySummary, + DestinationEntry, HealthResponse, - HohmannRequest, HohmannResponse, - LaunchRequest, LaunchResponse, - RouteRequest, RouteResponse, ScanRequest, SystemResponse, - TsiolkovskyRequest, TsiolkovskyResponse, UploadResponse, - DestinationEntry, } from '@/types/api' -const API_ORIGIN = import.meta.env.DEV - ? `${window.location.protocol}//${window.location.host}` - : 'http://localhost:8000' -const API_PREFIX = import.meta.env.DEV ? '/api' : '' - -function buildUrl(path: string, lang?: string): string { - const url = new URL(`${API_PREFIX}${path}`, API_ORIGIN) - if (lang) { - url.searchParams.set('lang', lang) - } - return url.toString() -} - -async function request( - path: string, - options: RequestInit = {}, - lang?: string, -): Promise { - const response = await fetch(buildUrl(path, lang), { - headers: { 'Content-Type': 'application/json', ...options.headers }, - ...options, - }) - if (!response.ok) { - const body = await response.json().catch(() => ({ detail: response.statusText })) - throw new Error(body.detail ?? `HTTP ${response.status}`) - } - return response.json() as Promise -} - -/** Wait for the backend to become available (used by Tauri on startup). */ -export async function waitForBackend( - maxRetries = 60, - intervalMs = 1000, -): Promise { - for (let i = 0; i < maxRetries; i++) { - try { - const res = await fetch(buildUrl('/health')) - if (res.ok) return true - } catch { - // Backend not ready yet - } - await new Promise((r) => setTimeout(r, intervalMs)) - } - return false -} - export function useApi(lang?: string) { const toast = useToast() function handleError(err: unknown): void { const message = err instanceof Error ? err.message : String(err) - toast.add({ severity: 'error', summary: 'API Error', detail: message, life: 5000 }) + toast.add({ severity: 'error', summary: 'Error', detail: message, life: 5000 }) } return { - health: () => request('/health'), - listBodies: () => request('/bodies', {}, lang), - getBody: (name: string) => request(`/bodies/${encodeURIComponent(name)}`, {}, lang), + health: () => invoke('health'), + listBodies: () => invoke('list_bodies', { lang }), + getBody: (name: string) => invoke('get_body', { name, lang }), getBodyMoons: (name: string) => - request(`/bodies/${encodeURIComponent(name)}/moons`), + invoke('get_body_moons', { name }), - uploadConfig: async (file: File) => { - const formData = new FormData() - formData.append('file', file) - const response = await fetch(buildUrl('/upload-config', lang), { - method: 'POST', - body: formData, - }) - if (!response.ok) { - const body = await response.json().catch(() => ({ detail: response.statusText })) - throw new Error(body.detail ?? `HTTP ${response.status}`) - } - return response.json() as Promise - }, + uploadConfig: (fileContent: string) => + invoke('upload_config', { fileContent }), scan: (req: ScanRequest) => - request('/scan', { method: 'POST', body: JSON.stringify(req) }), + invoke('scan_gamedata', { + path: req.gamedata_path, + exclude: req.exclude_dirs, + }), + + calcLaunch: (req: { body_name: string; target_altitude: number }) => + invoke('calc_launch', { + bodyName: req.body_name, + targetAltitude: req.target_altitude, + }), + + calcHohmann: (req: { body_name: string; parking_altitude: number; target_sma: number }) => + invoke('calc_hohmann', { + bodyName: req.body_name, + parkingAlt: req.parking_altitude, + targetSma: req.target_sma, + }), + + calcTsiolkovsky: (req: { delta_v: number; isp: number; wet_mass: number }) => + invoke('calc_tsiolkovsky', { + deltaV: req.delta_v, + isp: req.isp, + wetMass: req.wet_mass, + }), - calcLaunch: (req: LaunchRequest) => - request('/calc/launch', { method: 'POST', body: JSON.stringify(req) }, lang), - calcHohmann: (req: HohmannRequest) => - request('/calc/hohmann', { method: 'POST', body: JSON.stringify(req) }, lang), - calcTsiolkovsky: (req: TsiolkovskyRequest) => - request('/calc/tsiolkovsky', { method: 'POST', body: JSON.stringify(req) }, lang), + getSystem: () => invoke('get_system'), + getDestinations: () => invoke('get_destinations'), - getSystem: () => request('/system'), - getDestinations: () => request('/system/destinations'), - calcRoute: (req: RouteRequest) => - request('/calc/route', { method: 'POST', body: JSON.stringify(req) }), + calcRoute: (req: { destination: string | null; moon: string | null }) => + invoke('calc_route', { + destination: req.destination, + moon: req.moon, + }), - getAtmoProfile: (name: string, steps?: number) => { - const params = steps ? `?steps=${steps}` : '' - return request(`/atmo-profile/${encodeURIComponent(name)}${params}`, {}, lang) - }, + getAtmoProfile: (name: string, steps?: number) => + invoke('get_atmo_profile', { name, steps }), handleError, } diff --git a/frontend/src/main.ts b/frontend/src/main.ts index 8bc615c..750cde5 100644 --- a/frontend/src/main.ts +++ b/frontend/src/main.ts @@ -7,42 +7,21 @@ import 'primeicons/primeicons.css' import App from './App.vue' import router from './router' import i18n from './i18n' -import { waitForBackend } from './composables/useApi' import './assets/styles/main.css' -async function bootstrap(): Promise { - // In production (Tauri), wait for the Python backend to start - if (!import.meta.env.DEV) { - const ready = await waitForBackend() - if (!ready) { - const el = document.getElementById('app') - if (el) { - el.textContent = - 'Failed to connect to Python backend. Ensure Python 3.10+ is installed and on PATH.' - el.style.color = '#ef4444' - el.style.padding = '2rem' - el.style.fontFamily = 'sans-serif' - } - return - } - } +const app = createApp(App) - const app = createApp(App) - - app.use(createPinia()) - app.use(router) - app.use(i18n) - app.use(PrimeVue, { - theme: { - preset: Aura, - options: { - darkModeSelector: '.app-dark', - }, +app.use(createPinia()) +app.use(router) +app.use(i18n) +app.use(PrimeVue, { + theme: { + preset: Aura, + options: { + darkModeSelector: '.app-dark', }, - }) - app.use(ToastService) - - app.mount('#app') -} + }, +}) +app.use(ToastService) -bootstrap() +app.mount('#app') diff --git a/frontend/vite.config.ts b/frontend/vite.config.ts index 0e77346..a8e91e2 100644 --- a/frontend/vite.config.ts +++ b/frontend/vite.config.ts @@ -11,12 +11,5 @@ export default defineConfig({ }, server: { port: 5173, - proxy: { - '/api': { - target: 'http://localhost:8000', - changeOrigin: true, - rewrite: (path) => path.replace(/^\/api/, ''), - }, - }, }, }) diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock index 04a9fba..8d1b63d 100644 --- a/src-tauri/Cargo.lock +++ b/src-tauri/Cargo.lock @@ -697,15 +697,6 @@ version = "1.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7" -[[package]] -name = "encoding_rs" -version = "0.8.35" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75030f3c4f45dafd7586dd6780965a8c7e8e285a5ecb86713e63a79c5b2766f3" -dependencies = [ - "cfg-if", -] - [[package]] name = "equivalent" version = "1.0.2" @@ -723,16 +714,6 @@ dependencies = [ "typeid", ] -[[package]] -name = "errno" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - [[package]] name = "fastrand" version = "2.3.0" @@ -1324,9 +1305,9 @@ checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" [[package]] name = "hyper" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ab2d4f250c3d7b1c9fcdff1cece94ea4e2dfbec68614f7b87cb205f24ca9d11" +checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca" dependencies = [ "atomic-waker", "bytes", @@ -1337,7 +1318,6 @@ dependencies = [ "httparse", "itoa", "pin-project-lite", - "pin-utils", "smallvec", "tokio", "want", @@ -1402,12 +1382,13 @@ dependencies = [ [[package]] name = "icu_collections" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" dependencies = [ "displaydoc", "potential_utf", + "utf8_iter", "yoke", "zerofrom", "zerovec", @@ -1415,9 +1396,9 @@ dependencies = [ [[package]] name = "icu_locale_core" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" dependencies = [ "displaydoc", "litemap", @@ -1428,9 +1409,9 @@ dependencies = [ [[package]] name = "icu_normalizer" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" dependencies = [ "icu_collections", "icu_normalizer_data", @@ -1442,15 +1423,15 @@ dependencies = [ [[package]] name = "icu_normalizer_data" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" [[package]] name = "icu_properties" -version = "2.1.2" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" dependencies = [ "icu_collections", "icu_locale_core", @@ -1462,15 +1443,15 @@ dependencies = [ [[package]] name = "icu_properties_data" -version = "2.1.2" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" [[package]] name = "icu_provider" -version = "2.1.1" +version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" dependencies = [ "displaydoc", "icu_locale_core", @@ -1527,9 +1508,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.13.0" +version = "2.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +checksum = "45a8a2b9cb3e0b0c1803dbb0758ffac5de2f425b23c28f518faabd9d805342ff" dependencies = [ "equivalent", "hashbrown 0.16.1", @@ -1562,25 +1543,6 @@ dependencies = [ "serde", ] -[[package]] -name = "is-docker" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "928bae27f42bc99b60d9ac7334e3a21d10ad8f1835a4e12ec3ec0464765ed1b3" -dependencies = [ - "once_cell", -] - -[[package]] -name = "is-wsl" -version = "0.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "173609498df190136aa7dea1a91db051746d339e18476eed5ca40521f02d7aa5" -dependencies = [ - "is-docker", - "once_cell", -] - [[package]] name = "itoa" version = "1.0.18" @@ -1656,9 +1618,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.93" +version = "0.3.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "797146bb2677299a1eb6b7b50a890f4c361b29ef967addf5b2fa45dae1bb6d7d" +checksum = "2e04e2ef80ce82e13552136fabeef8a5ed1f985a96805761cbb9a2c34e7664d9" dependencies = [ "cfg-if", "futures-util", @@ -1699,16 +1661,23 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "kopdeltav" +version = "0.1.0" +dependencies = [ + "serde", +] + [[package]] name = "kspdeltavformods" version = "0.1.0" dependencies = [ + "kopdeltav", "serde", "serde_json", "tauri", "tauri-build", "tauri-plugin-dialog", - "tauri-plugin-shell", ] [[package]] @@ -1719,7 +1688,7 @@ checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2" dependencies = [ "cssparser 0.29.6", "html5ever 0.29.1", - "indexmap 2.13.0", + "indexmap 2.13.1", "selectors 0.24.0", ] @@ -1755,9 +1724,9 @@ dependencies = [ [[package]] name = "libc" -version = "0.2.183" +version = "0.2.184" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d" +checksum = "48f5d2a454e16a5ea0f4ced81bd44e4cfc7bd3a507b61887c99fd3538b28e4af" [[package]] name = "libloading" @@ -1780,9 +1749,9 @@ dependencies = [ [[package]] name = "litemap" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" [[package]] name = "lock_api" @@ -2118,34 +2087,12 @@ version = "1.21.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" -[[package]] -name = "open" -version = "5.3.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "43bb73a7fa3799b198970490a51174027ba0d4ec504b03cd08caf513d40024bc" -dependencies = [ - "dunce", - "is-wsl", - "libc", - "pathdiff", -] - [[package]] name = "option-ext" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" -[[package]] -name = "os_pipe" -version = "1.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" -dependencies = [ - "libc", - "windows-sys 0.61.2", -] - [[package]] name = "pango" version = "0.18.3" @@ -2194,12 +2141,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "pathdiff" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3" - [[package]] name = "percent-encoding" version = "2.3.2" @@ -2399,12 +2340,6 @@ version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" -[[package]] -name = "pin-utils" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" - [[package]] name = "pkg-config" version = "0.3.32" @@ -2418,7 +2353,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "740ebea15c5d1428f910cd1a5f52cebf8d25006245ed8ade92702f4943d91e07" dependencies = [ "base64 0.22.1", - "indexmap 2.13.0", + "indexmap 2.13.1", "quick-xml", "serde", "time", @@ -2439,9 +2374,9 @@ dependencies = [ [[package]] name = "potential_utf" -version = "0.1.4" +version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" dependencies = [ "zerovec", ] @@ -2503,7 +2438,7 @@ version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" dependencies = [ - "toml_edit 0.25.8+spec-1.1.0", + "toml_edit 0.25.10+spec-1.1.0", ] [[package]] @@ -3011,9 +2946,9 @@ dependencies = [ [[package]] name = "serde_spanned" -version = "1.1.0" +version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "876ac351060d4f882bb1032b6369eb0aef79ad9df1ea8bc404874d8cc3d0cd98" +checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26" dependencies = [ "serde_core", ] @@ -3028,7 +2963,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.13.0", + "indexmap 2.13.1", "schemars 0.9.0", "schemars 1.2.1", "serde_core", @@ -3101,54 +3036,12 @@ dependencies = [ "digest", ] -[[package]] -name = "shared_child" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e362d9935bc50f019969e2f9ecd66786612daae13e8f277be7bfb66e8bed3f7" -dependencies = [ - "libc", - "sigchld", - "windows-sys 0.60.2", -] - [[package]] name = "shlex" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" -[[package]] -name = "sigchld" -version = "0.2.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "47106eded3c154e70176fc83df9737335c94ce22f821c32d17ed1db1f83badb1" -dependencies = [ - "libc", - "os_pipe", - "signal-hook", -] - -[[package]] -name = "signal-hook" -version = "0.3.18" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" -dependencies = [ - "libc", - "signal-hook-registry", -] - -[[package]] -name = "signal-hook-registry" -version = "1.4.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" -dependencies = [ - "errno", - "libc", -] - [[package]] name = "simd-adler32" version = "0.3.9" @@ -3590,27 +3483,6 @@ dependencies = [ "url", ] -[[package]] -name = "tauri-plugin-shell" -version = "2.3.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8457dbf9e2bab1edd8df22bb2c20857a59a9868e79cb3eac5ed639eec4d0c73b" -dependencies = [ - "encoding_rs", - "log", - "open", - "os_pipe", - "regex", - "schemars 0.8.22", - "serde", - "serde_json", - "shared_child", - "tauri", - "tauri-plugin", - "thiserror 2.0.18", - "tokio", -] - [[package]] name = "tauri-runtime" version = "2.10.1" @@ -3805,9 +3677,9 @@ dependencies = [ [[package]] name = "tinystr" -version = "0.8.2" +version = "0.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" dependencies = [ "displaydoc", "zerovec", @@ -3858,9 +3730,9 @@ version = "0.9.12+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863" dependencies = [ - "indexmap 2.13.0", + "indexmap 2.13.1", "serde_core", - "serde_spanned 1.1.0", + "serde_spanned 1.1.1", "toml_datetime 0.7.5+spec-1.1.0", "toml_parser", "toml_writer", @@ -3887,9 +3759,9 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "1.1.0+spec-1.1.0" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97251a7c317e03ad83774a8752a7e81fb6067740609f75ea2b585b569a59198f" +checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7" dependencies = [ "serde_core", ] @@ -3900,7 +3772,7 @@ version = "0.19.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" dependencies = [ - "indexmap 2.13.0", + "indexmap 2.13.1", "toml_datetime 0.6.3", "winnow 0.5.40", ] @@ -3911,7 +3783,7 @@ version = "0.20.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" dependencies = [ - "indexmap 2.13.0", + "indexmap 2.13.1", "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.3", @@ -3920,30 +3792,30 @@ dependencies = [ [[package]] name = "toml_edit" -version = "0.25.8+spec-1.1.0" +version = "0.25.10+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16bff38f1d86c47f9ff0647e6838d7bb362522bdf44006c7068c2b1e606f1f3c" +checksum = "a82418ca169e235e6c399a84e395ab6debeb3bc90edc959bf0f48647c6a32d1b" dependencies = [ - "indexmap 2.13.0", - "toml_datetime 1.1.0+spec-1.1.0", + "indexmap 2.13.1", + "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", "winnow 1.0.1", ] [[package]] name = "toml_parser" -version = "1.1.0+spec-1.1.0" +version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2334f11ee363607eb04df9b8fc8a13ca1715a72ba8662a26ac285c98aabb4011" +checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ "winnow 1.0.1", ] [[package]] name = "toml_writer" -version = "1.1.0+spec-1.1.0" +version = "1.1.1+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d282ade6016312faf3e41e57ebbba0c073e4056dab1232ab1cb624199648f8ed" +checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" [[package]] name = "tower" @@ -4240,9 +4112,9 @@ dependencies = [ [[package]] name = "wasm-bindgen" -version = "0.2.116" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7dc0882f7b5bb01ae8c5215a1230832694481c1a4be062fd410e12ea3da5b631" +checksum = "0551fc1bb415591e3372d0bc4780db7e587d84e2a7e79da121051c5c4b89d0b0" dependencies = [ "cfg-if", "once_cell", @@ -4253,9 +4125,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.66" +version = "0.4.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19280959e2844181895ef62f065c63e0ca07ece4771b53d89bfdb967d97cbf05" +checksum = "03623de6905b7206edd0a75f69f747f134b7f0a2323392d664448bf2d3c5d87e" dependencies = [ "js-sys", "wasm-bindgen", @@ -4263,9 +4135,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.116" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "75973d3066e01d035dbedaad2864c398df42f8dd7b1ea057c35b8407c015b537" +checksum = "7fbdf9a35adf44786aecd5ff89b4563a90325f9da0923236f6104e603c7e86be" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -4273,9 +4145,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.116" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "91af5e4be765819e0bcfee7322c14374dc821e35e72fa663a830bbc7dc199eac" +checksum = "dca9693ef2bab6d4e6707234500350d8dad079eb508dca05530c85dc3a529ff2" dependencies = [ "bumpalo", "proc-macro2", @@ -4286,9 +4158,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.116" +version = "0.2.117" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9bf0406a78f02f336bf1e451799cca198e8acde4ffa278f0fb20487b150a633" +checksum = "39129a682a6d2d841b6c429d0c51e5cb0ed1a03829d8b3d1e69a011e62cb3d3b" dependencies = [ "unicode-ident", ] @@ -4310,7 +4182,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", - "indexmap 2.13.0", + "indexmap 2.13.1", "wasm-encoder", "wasmparser", ] @@ -4336,15 +4208,15 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags 2.11.0", "hashbrown 0.15.5", - "indexmap 2.13.0", + "indexmap 2.13.1", "semver", ] [[package]] name = "web-sys" -version = "0.3.93" +version = "0.3.94" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "749466a37ee189057f54748b200186b59a03417a117267baf3fd89cecc9fb837" +checksum = "cd70027e39b12f0849461e08ffc50b9cd7688d942c1c8e3c7b22273236b4dd0a" dependencies = [ "js-sys", "wasm-bindgen", @@ -4929,7 +4801,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck 0.5.0", - "indexmap 2.13.0", + "indexmap 2.13.1", "prettyplease", "syn 2.0.117", "wasm-metadata", @@ -4960,7 +4832,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags 2.11.0", - "indexmap 2.13.0", + "indexmap 2.13.1", "log", "serde", "serde_derive", @@ -4979,7 +4851,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", - "indexmap 2.13.0", + "indexmap 2.13.1", "log", "semver", "serde", @@ -4991,9 +4863,9 @@ dependencies = [ [[package]] name = "writeable" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" [[package]] name = "wry" @@ -5062,9 +4934,9 @@ dependencies = [ [[package]] name = "yoke" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca" dependencies = [ "stable_deref_trait", "yoke-derive", @@ -5073,9 +4945,9 @@ dependencies = [ [[package]] name = "yoke-derive" -version = "0.8.1" +version = "0.8.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" dependencies = [ "proc-macro2", "quote", @@ -5105,18 +4977,18 @@ dependencies = [ [[package]] name = "zerofrom" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" dependencies = [ "zerofrom-derive", ] [[package]] name = "zerofrom-derive" -version = "0.1.6" +version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" dependencies = [ "proc-macro2", "quote", @@ -5126,9 +4998,9 @@ dependencies = [ [[package]] name = "zerotrie" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" dependencies = [ "displaydoc", "yoke", @@ -5137,9 +5009,9 @@ dependencies = [ [[package]] name = "zerovec" -version = "0.11.5" +version = "0.11.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" dependencies = [ "yoke", "zerofrom", @@ -5148,9 +5020,9 @@ dependencies = [ [[package]] name = "zerovec-derive" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" dependencies = [ "proc-macro2", "quote", diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml index 432111b..7ff0c0c 100644 --- a/src-tauri/Cargo.toml +++ b/src-tauri/Cargo.toml @@ -1,3 +1,6 @@ +[workspace] +members = ["crates/kopdeltav"] + [package] name = "kspdeltavformods" version = "0.1.0" @@ -7,6 +10,7 @@ edition = "2021" tauri-build = { version = "2", features = [] } [dependencies] +kopdeltav = { path = "crates/kopdeltav" } tauri = { version = "2", features = [] } tauri-plugin-dialog = "2" serde = { version = "1", features = ["derive"] } diff --git a/src-tauri/crates/kopdeltav/Cargo.toml b/src-tauri/crates/kopdeltav/Cargo.toml new file mode 100644 index 0000000..7f14a8f --- /dev/null +++ b/src-tauri/crates/kopdeltav/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "kopdeltav" +version = "0.1.0" +edition = "2021" + +[dependencies] +serde = { version = "1", features = ["derive"] } diff --git a/src-tauri/crates/kopdeltav/src/calculator.rs b/src-tauri/crates/kopdeltav/src/calculator.rs new file mode 100644 index 0000000..745095e --- /dev/null +++ b/src-tauri/crates/kopdeltav/src/calculator.rs @@ -0,0 +1,1107 @@ +//! Delta-V calculation engine for KSP celestial bodies. +//! +//! 天体のΔV計算エンジン。低軌道投入、ホーマン遷移、ツィオルコフスキー方程式を提供する。 +//! +//! Provides empirical launch-to-orbit estimation, Hohmann transfer computation, +//! Tsiolkovsky rocket equation, geostationary orbit calculation, escape/landing +//! ΔV helpers, and a multi-step route planner. + +use serde::Serialize; +use std::f64::consts::PI; + +use crate::models::{hermite_interp, CelestialBody, G0, R_GAS}; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +/// Fraction of orbital velocity attributed to gravity loss, scaled by surface gravity. +/// Calibrated against KSP flight data; accuracy ~10%. +const GRAVITY_LOSS_COEFF: f64 = 0.15; + +/// Fraction of orbital velocity attributed to atmospheric drag loss, +/// scaled by surface density relative to Earth. +const DRAG_LOSS_COEFF: f64 = 0.05; + +/// Fraction of orbital velocity saved by air-breathing (jet) engines in the lower atmosphere. +/// Capped when density ratio >= 1.0. +const JET_SAVINGS_COEFF: f64 = 0.44; + +/// Earth sea-level atmospheric density [kg/m^3], used as reference for empirical scaling. +const EARTH_RHO_SEA_LEVEL: f64 = 1.225; + +// --------------------------------------------------------------------------- +// Enums +// --------------------------------------------------------------------------- + +/// Type of a delta-V route segment, used for display coloring. +/// +/// ΔVルートセグメントの種別。表示時の色分けに使用。 +#[derive(Debug, Clone, Serialize)] +pub enum SegmentType { + /// Launch from surface to low orbit. + Launch, + /// Escape from a celestial body's gravity well. + Escape, + /// Interplanetary/interlunar Hohmann transfer. + Transfer, + /// Orbit insertion (capture burn) at destination. + Capture, + /// Landing on a celestial body. + Landing, + /// Escape from the entire star system (third cosmic velocity). + SystemEscape, + /// Transfer from a planet's orbit to a moon's orbit. + MoonTransfer, + /// Landing on a moon. + MoonLanding, +} + +// --------------------------------------------------------------------------- +// Result structs +// --------------------------------------------------------------------------- + +/// Results of a launch-to-orbit delta-V calculation. +/// +/// 低軌道投入ΔV計算の結果。 +#[derive(Debug, Clone, Serialize)] +pub struct LaunchResult { + /// Circular velocity at target orbit [m/s]. + pub orbital_velocity: f64, + /// Estimated gravity loss [m/s]. + pub gravity_loss: f64, + /// Estimated atmospheric drag loss [m/s]. + pub drag_loss: f64, + /// Theoretical minimum (= orbital velocity) [m/s]. + pub total_ideal: f64, + /// Practical rocket delta-V with losses [m/s]. + pub total_rocket: f64, + /// Delta-V saved if using jet engines in lower atmosphere [m/s]. + pub jet_savings: f64, + /// total_rocket - jet_savings [m/s]. + pub total_with_jets: f64, +} + +/// Results of a Hohmann transfer calculation. +/// +/// ホーマン遷移計算の結果。 +#[derive(Debug, Clone, Serialize)] +pub struct HohmannResult { + /// Delta-V for departure burn [m/s]. + pub departure_dv: f64, + /// Delta-V for arrival/capture burn [m/s]. + pub arrival_dv: f64, + /// Total delta-V (departure + arrival) [m/s]. + pub total_dv: f64, + /// Transfer time (half-period of the transfer ellipse) [s]. + pub transfer_time: f64, + /// True if the transfer is to an inner (lower) orbit. + pub inward: bool, +} + +/// Results of the Tsiolkovsky rocket equation. +/// +/// ツィオルコフスキーの式の計算結果。 +#[derive(Debug, Clone, Serialize)] +pub struct TsiolkovskyResult { + /// Wet mass / dry mass ratio. + pub mass_ratio: f64, + /// Fraction of total mass that is fuel (1 - 1/mass_ratio). + pub fuel_fraction: f64, + /// Dry (empty) mass [kg]. + pub dry_mass: f64, + /// Fuel mass [kg]. + pub fuel_mass: f64, +} + +/// A single step in a delta-V route. +/// +/// ΔVルートの1ステップ。 +#[derive(Debug, Clone, Serialize)] +pub struct DvStep { + /// Human-readable description of this maneuver. + pub label: String, + /// Delta-V for this step [m/s]. + pub dv: f64, + /// Running total delta-V from mission start [m/s]. + pub cumulative: f64, + /// Type of maneuver for display purposes. + pub segment_type: SegmentType, + /// Optional supplementary information (e.g. aerobrake alternative). + pub note: String, +} + +// --------------------------------------------------------------------------- +// Orbital mechanics +// --------------------------------------------------------------------------- + +/// Estimate a reasonable low orbit altitude for the body. +/// +/// 天体の妥当な低軌道高度を推定する。 +/// +/// For bodies with atmosphere, returns approximately 10% above the atmosphere +/// depth to ensure a stable orbit well outside the atmosphere. For airless +/// bodies, returns 5% of the body radius (minimum 10 000 m). +/// +/// # Arguments +/// * `body` - Target celestial body. +/// +/// # Returns +/// Estimated low orbit altitude above surface [m]. +pub fn low_orbit_altitude(body: &CelestialBody) -> f64 { + if let Some(ref atmo) = body.atmosphere { + atmo.atmosphere_depth * 1.1 + } else { + f64::max(body.radius * 0.05, 10_000.0) + } +} + +/// Circular orbital velocity at given altitude above surface. +/// +/// 指定高度での円軌道速度を計算する。 +/// +/// Uses `v_circular = sqrt(mu / r)` where `r = radius + altitude`. +/// +/// # Arguments +/// * `body` - Target celestial body. +/// * `altitude` - Altitude above surface [m]. +/// +/// # Returns +/// Orbital velocity [m/s]. +/// +/// # Panics +/// Panics if altitude is negative. +pub fn circular_velocity(body: &CelestialBody, altitude: f64) -> f64 { + assert!(altitude >= 0.0, "Altitude must be non-negative: {altitude}"); + let r = body.radius + altitude; + (body.mu / r).sqrt() +} + +/// Escape velocity at given altitude above surface. +/// +/// 指定高度での脱出速度を計算する。 +/// +/// Uses `v_escape = sqrt(2 * mu / r) = sqrt(2) * v_circular` at the same altitude. +/// +/// # Arguments +/// * `body` - Target celestial body. +/// * `altitude` - Altitude above surface [m]. +/// +/// # Returns +/// Escape velocity [m/s]. +/// +/// # Panics +/// Panics if altitude is negative. +pub fn escape_velocity(body: &CelestialBody, altitude: f64) -> f64 { + assert!(altitude >= 0.0, "Altitude must be non-negative: {altitude}"); + let r = body.radius + altitude; + (2.0 * body.mu / r).sqrt() +} + +// --------------------------------------------------------------------------- +// Atmospheric density +// --------------------------------------------------------------------------- + +/// Calculate atmospheric density at altitude using hermite-interpolated curves. +/// +/// 高度ごとの大気密度をエルミート補間カーブで計算する。 +/// +/// Applies the ideal gas law `rho = P * M / (R_gas * T)` where pressure and +/// temperature are obtained from the body's atmosphere curves via cubic +/// Hermite spline interpolation. When curves are empty, falls back to +/// sea-level scalar values (meaningful only at altitude 0). +/// +/// **Important**: Pressure in the curves is in kPa; it must be converted to +/// Pa (x1000) before applying the ideal gas law. +/// +/// # Arguments +/// * `body` - Target celestial body. +/// * `altitude` - Altitude above surface [m]. +/// +/// # Returns +/// Atmospheric density [kg/m^3], or `None` if the body has no atmosphere. +/// Returns `0.0` for altitudes at or above the atmosphere depth. +pub fn density_at_altitude(body: &CelestialBody, altitude: f64) -> Option { + let atmo = body.atmosphere.as_ref()?; + + if altitude >= atmo.atmosphere_depth { + return Some(0.0); + } + + // Pressure [kPa] from curve, falling back to sea-level scalar. + let pressure_kpa = if !atmo.pressure_curve.is_empty() { + hermite_interp(&atmo.pressure_curve, altitude).unwrap_or(0.0) + } else if altitude == 0.0 { + atmo.pressure_at_sea_level + } else { + 0.0 + }; + + // Temperature [K] from curve, falling back to sea-level scalar. + let temperature_k = if !atmo.temperature_curve.is_empty() { + hermite_interp(&atmo.temperature_curve, altitude).unwrap_or(0.0) + } else if altitude == 0.0 { + atmo.temperature_at_sea_level + } else { + 0.0 + }; + + if temperature_k <= 0.0 || pressure_kpa <= 0.0 { + return Some(0.0); + } + + // kPa -> Pa conversion, then ideal gas law: rho = P * M / (R * T). + let pressure_pa = pressure_kpa * 1000.0; + Some(pressure_pa * atmo.molar_mass / (R_GAS * temperature_k)) +} + +/// Calculate sea-level atmospheric density using the ideal gas law. +/// +/// 海面大気密度を理想気体の式で計算する。大気なしの場合は None。 +/// +/// Delegates to [`density_at_altitude`] at altitude 0, which evaluates +/// the pressure and temperature curves at sea level. +/// +/// # Arguments +/// * `body` - Target celestial body. +/// +/// # Returns +/// Sea-level atmospheric density [kg/m^3], or `None` if no atmosphere. +pub fn surface_density(body: &CelestialBody) -> Option { + density_at_altitude(body, 0.0) +} + +// --------------------------------------------------------------------------- +// Launch delta-V +// --------------------------------------------------------------------------- + +/// Calculate launch-to-orbit delta-V for a body. +/// +/// 天体の低軌道投入ΔVを計算する。 +/// +/// This is an **empirical** model. All loss and savings values are rough +/// approximations calibrated against KSP flight data. Estimated accuracy +/// is +/-10% for `total_rocket` and +/-15% for `jet_savings`. Actual values +/// depend heavily on vehicle design, thrust-to-weight ratio, and ascent profile. +/// +/// Assumptions: +/// - **Gravity loss** ~ 15% of orbital velocity, scaled linearly by `gee_asl`. +/// - **Drag loss** ~ 5% of orbital velocity, scaled by `rho/rho_earth`. +/// - **Jet savings** ~ 44% of orbital velocity, capped at density ratio 1.0. +/// +/// # Arguments +/// * `body` - Target celestial body. +/// * `target_altitude` - Target circular orbit altitude above surface [m]. +/// +/// # Returns +/// [`LaunchResult`] with computed delta-V values. +/// +/// # Panics +/// Panics if `target_altitude` is negative. +pub fn calculate_launch(body: &CelestialBody, target_altitude: f64) -> LaunchResult { + assert!( + target_altitude >= 0.0, + "Target altitude must be non-negative: {target_altitude}" + ); + + let v_orbital = circular_velocity(body, target_altitude); + + // Gravity loss: scales with surface gravity. + let gravity_loss = v_orbital * GRAVITY_LOSS_COEFF * body.gee_asl; + + // Drag loss: scales with atmospheric density relative to Earth. + let rho = surface_density(body); + let drag_loss = match rho { + Some(r) if r > 0.0 => v_orbital * DRAG_LOSS_COEFF * (r / EARTH_RHO_SEA_LEVEL), + _ => 0.0, + }; + + let total_ideal = v_orbital; + let total_rocket = v_orbital + gravity_loss + drag_loss; + + // Jet savings: only possible with atmosphere; capped at density ratio 1.0. + let jet_savings = match rho { + Some(r) if r > 0.0 => { + let density_factor = (r / EARTH_RHO_SEA_LEVEL).min(1.0); + v_orbital * JET_SAVINGS_COEFF * density_factor + } + _ => 0.0, + }; + + let total_with_jets = total_rocket - jet_savings; + + LaunchResult { + orbital_velocity: v_orbital, + gravity_loss, + drag_loss, + total_ideal, + total_rocket, + jet_savings, + total_with_jets, + } +} + +// --------------------------------------------------------------------------- +// Hohmann transfer +// --------------------------------------------------------------------------- + +/// Calculate Hohmann transfer from parking orbit to target orbit. +/// +/// パーキング軌道からターゲット軌道へのホーマン遷移ΔVを計算する。 +/// +/// Supports both outward (target > parking) and inward (target < parking) +/// transfers. For inward transfers the vis-viva computation uses the +/// swapped radii internally and the returned departure/arrival delta-Vs are +/// swapped so that `departure_dv` is the burn at the parking orbit and +/// `arrival_dv` is the burn at the target orbit. +/// +/// Standard Hohmann transfer equations (outward case): +/// ```text +/// a_transfer = (r1 + r2) / 2 +/// v_transfer_peri = sqrt(mu * (2/r1 - 1/a_transfer)) +/// departure_dv = v_transfer_peri - v_circular(r1) +/// v_transfer_apo = sqrt(mu * (2/r2 - 1/a_transfer)) +/// arrival_dv = v_circular(r2) - v_transfer_apo +/// transfer_time = pi * sqrt(a_transfer^3 / mu) +/// ``` +/// +/// # Arguments +/// * `body` - Central body being orbited. +/// * `parking_altitude` - Altitude of circular parking orbit above surface [m]. +/// * `target_sma` - Semi-major axis of target orbit [m] (from body center). +/// +/// # Returns +/// [`HohmannResult`] with delta-V and transfer time values. +/// +/// # Panics +/// Panics if `parking_altitude` is negative or the parking orbit radius +/// and `target_sma` are identical (zero-ΔV transfer). +pub fn calculate_hohmann( + body: &CelestialBody, + parking_altitude: f64, + target_sma: f64, +) -> HohmannResult { + assert!( + parking_altitude >= 0.0, + "Parking altitude must be non-negative: {parking_altitude}" + ); + + let r_parking = body.radius + parking_altitude; + let r_target = target_sma; + + assert!( + (r_parking - r_target).abs() / r_parking.max(r_target) > 1e-12, + "Parking orbit radius ({r_parking} m) and target SMA ({r_target} m) \ + are identical; Hohmann transfer is undefined" + ); + + let inward = r_target < r_parking; + + // For vis-viva, r_inner is the periapsis and r_outer is the apoapsis. + let r_inner = r_parking.min(r_target); + let r_outer = r_parking.max(r_target); + + let mu = body.mu; + let a_transfer = (r_inner + r_outer) / 2.0; + + // Burn at periapsis of the transfer ellipse. + let v_inner_circular = (mu / r_inner).sqrt(); + let v_transfer_peri = (mu * (2.0 / r_inner - 1.0 / a_transfer)).sqrt(); + let dv_peri = v_transfer_peri - v_inner_circular; + + // Burn at apoapsis of the transfer ellipse. + let v_outer_circular = (mu / r_outer).sqrt(); + let v_transfer_apo = (mu * (2.0 / r_outer - 1.0 / a_transfer)).sqrt(); + let dv_apo = v_outer_circular - v_transfer_apo; + + // Transfer time: half the period of the transfer ellipse. + let transfer_time = PI * (a_transfer.powi(3) / mu).sqrt(); + + let (departure_dv, arrival_dv) = if inward { + // Inward: departure is at the outer (parking) orbit, arrival at inner. + (dv_apo, dv_peri) + } else { + // Outward: departure is at the inner (parking) orbit, arrival at outer. + (dv_peri, dv_apo) + }; + + HohmannResult { + departure_dv, + arrival_dv, + total_dv: departure_dv + arrival_dv, + transfer_time, + inward, + } +} + +// --------------------------------------------------------------------------- +// Tsiolkovsky rocket equation +// --------------------------------------------------------------------------- + +/// Apply the Tsiolkovsky rocket equation. +/// +/// ツィオルコフスキーの式を適用して質量比を計算する。 +/// +/// ```text +/// dv = Isp * g0 * ln(m_wet / m_dry) +/// mass_ratio = exp(dv / (Isp * g0)) +/// ``` +/// +/// # Arguments +/// * `delta_v` - Required delta-V [m/s]. +/// * `isp` - Specific impulse [s]. +/// * `wet_mass` - Total (wet) mass [kg]. +/// +/// # Returns +/// [`TsiolkovskyResult`] with mass ratio and fuel breakdown. +/// +/// # Panics +/// Panics if `delta_v` is negative, `isp` is non-positive, or +/// `wet_mass` is non-positive. +pub fn calculate_tsiolkovsky(delta_v: f64, isp: f64, wet_mass: f64) -> TsiolkovskyResult { + assert!(delta_v >= 0.0, "delta_v must be non-negative: {delta_v}"); + assert!(isp > 0.0, "Isp must be positive: {isp}"); + assert!(wet_mass > 0.0, "wet_mass must be positive: {wet_mass}"); + + let ve = isp * G0; // effective exhaust velocity [m/s] + let mass_ratio = (delta_v / ve).exp(); + let fuel_fraction = 1.0 - 1.0 / mass_ratio; + let dry_mass = wet_mass / mass_ratio; + let fuel_mass = wet_mass - dry_mass; + + TsiolkovskyResult { + mass_ratio, + fuel_fraction, + dry_mass, + fuel_mass, + } +} + +// --------------------------------------------------------------------------- +// Geostationary orbit +// --------------------------------------------------------------------------- + +/// Calculate the altitude of a geostationary orbit. +/// +/// 静止軌道の高度を計算する。 +/// +/// Uses the formula: +/// ```text +/// r_geo = (mu * T^2 / (4 * pi^2))^(1/3) +/// altitude = r_geo - radius +/// ``` +/// +/// where `T` is the sidereal rotation period of the body. +/// +/// # Arguments +/// * `body` - Target celestial body. +/// +/// # Returns +/// Geostationary orbit altitude above surface [m]. +/// +/// # Panics +/// Panics if `body.rotational_period` is non-positive. +pub fn geostationary_altitude(body: &CelestialBody) -> f64 { + assert!( + body.rotational_period > 0.0, + "Rotational period must be positive for a geostationary orbit: {}", + body.rotational_period + ); + let t = body.rotational_period; + let r_geo = (body.mu * t * t / (4.0 * PI * PI)).powf(1.0 / 3.0); + r_geo - body.radius +} + +/// Calculate the delta-V for a Hohmann transfer from low orbit to geostationary orbit. +/// +/// 低軌道から静止軌道へのホーマン遷移ΔVを計算する。 +/// +/// # Arguments +/// * `body` - Target celestial body. +/// +/// # Returns +/// [`HohmannResult`] for the low orbit -> geostationary transfer. +/// +/// # Panics +/// Panics if `body.rotational_period` is non-positive, or if the +/// geostationary orbit is below the low orbit (extremely fast rotators). +pub fn geostationary_dv(body: &CelestialBody) -> HohmannResult { + let lo_alt = low_orbit_altitude(body); + let geo_alt = geostationary_altitude(body); + let geo_sma = body.radius + geo_alt; + calculate_hohmann(body, lo_alt, geo_sma) +} + +// --------------------------------------------------------------------------- +// Escape delta-V from low orbit +// --------------------------------------------------------------------------- + +/// Calculate the delta-V needed to escape from low orbit. +/// +/// 低軌道から脱出するのに必要なΔVを計算する。 +/// +/// Computes `v_escape(lo_alt) - v_circular(lo_alt)`, which is the +/// impulsive burn required to reach escape velocity from a circular +/// parking orbit at the standard low orbit altitude. +/// +/// # Arguments +/// * `body` - Target celestial body. +/// +/// # Returns +/// Escape delta-V from low orbit [m/s]. Always positive. +pub fn escape_dv_from_low_orbit(body: &CelestialBody) -> f64 { + let lo_alt = low_orbit_altitude(body); + let v_esc = escape_velocity(body, lo_alt); + let v_circ = circular_velocity(body, lo_alt); + v_esc - v_circ +} + +// --------------------------------------------------------------------------- +// Landing delta-V +// --------------------------------------------------------------------------- + +/// Estimate the delta-V required to land on a body. +/// +/// 天体への着陸に必要なΔVを推定する。 +/// +/// The powered landing delta-V is approximated as the circular orbital velocity +/// at the low orbit altitude -- representing the speed that must be cancelled +/// to descend from orbit to the surface. +/// +/// For bodies **with** atmosphere, aerobraking can absorb most of the +/// orbital energy; the aerobrake contribution is returned as `Some(0.0)`. +/// +/// For bodies **without** atmosphere, there is no aerobraking option, so +/// the second element is `None`. +/// +/// # Arguments +/// * `body` - Target celestial body. +/// +/// # Returns +/// A tuple `(powered_dv, aerobrake_dv)` where: +/// - `powered_dv`: delta-V for a fully powered landing [m/s]. Always > 0. +/// - `aerobrake_dv`: `Some(0.0)` if the body has atmosphere; `None` if no atmosphere. +pub fn landing_dv(body: &CelestialBody) -> (f64, Option) { + let lo_alt = low_orbit_altitude(body); + let powered_dv = circular_velocity(body, lo_alt); + let aerobrake_dv = if body.atmosphere.is_some() { + Some(0.0) + } else { + None + }; + (powered_dv, aerobrake_dv) +} + +// --------------------------------------------------------------------------- +// Delta-V route planner +// --------------------------------------------------------------------------- + +/// Compute a delta-V route from the home world to an optional destination. +/// +/// ホームワールドから目的地までのΔVルートを計算する。 +/// +/// Three modes depending on the arguments: +/// +/// **Third cosmic velocity** (`destination = None`): +/// 1. Launch to low orbit. +/// 2. Escape home world. +/// 3. Escape star system. +/// +/// **Planet flyby / capture** (`destination = Some(planet)`, `moon = None`): +/// 1. Launch to low orbit. +/// 2. Escape home world. +/// 3. Hohmann transfer in parent body's frame. +/// 4. Destination orbit insertion (capture burn). +/// 5. Landing on destination. +/// +/// **Moon mission** (`destination = Some(planet)`, `moon = Some(satellite)`): +/// Steps 1-4 as above. +/// 5. Hohmann transfer from destination low orbit to moon SMA. +/// 6. Landing on moon. +/// +/// # Arguments +/// * `home` - Home world celestial body (must have orbit and parent). +/// * `parent` - Parent star/body that home orbits. +/// * `destination` - Target planet (must orbit the same parent as home). Pass `None` for third cosmic velocity. +/// * `moon` - Target moon orbiting destination. Ignored when destination is `None`. +/// +/// # Returns +/// Ordered list of [`DvStep`] objects representing each maneuver. +/// +/// # Panics +/// Panics if home has no orbit data, or if destination/moon have no orbit data when provided. +pub fn compute_route( + home: &CelestialBody, + parent: &CelestialBody, + destination: Option<&CelestialBody>, + moon: Option<&CelestialBody>, +) -> Vec { + let home_orbit = home + .orbit + .as_ref() + .expect("Home world has no orbital elements; cannot compute interplanetary route."); + + let mut steps: Vec = Vec::new(); + let mut cumulative = 0.0; + + let add_step = |steps: &mut Vec, + cumulative: &mut f64, + label: String, + dv: f64, + seg_type: SegmentType, + note: String| { + *cumulative += dv; + steps.push(DvStep { + label, + dv, + cumulative: *cumulative, + segment_type: seg_type, + note, + }); + }; + + // Step 1: Launch to low orbit. + let lo_alt = low_orbit_altitude(home); + let launch = calculate_launch(home, lo_alt); + add_step( + &mut steps, + &mut cumulative, + "Launch to low orbit".to_string(), + launch.total_rocket, + SegmentType::Launch, + String::new(), + ); + + // Step 2: Escape home world. + let esc_home = escape_dv_from_low_orbit(home); + add_step( + &mut steps, + &mut cumulative, + format!("Escape {}", home.name), + esc_home, + SegmentType::Escape, + String::new(), + ); + + let destination = match destination { + Some(d) => d, + None => { + // Third cosmic velocity: escape the parent star system from home orbit. + let home_sma = home_orbit.semi_major_axis; + let home_orbit_alt = home_sma - parent.radius; + let v_esc_star = escape_velocity(parent, home_orbit_alt); + let v_circ_star = circular_velocity(parent, home_orbit_alt); + let esc_star = v_esc_star - v_circ_star; + add_step( + &mut steps, + &mut cumulative, + format!("Escape {} system", parent.name), + esc_star, + SegmentType::SystemEscape, + String::new(), + ); + return steps; + } + }; + + let dest_orbit = destination + .orbit + .as_ref() + .expect("Destination has no orbital elements."); + + // Step 3: Hohmann transfer in parent's frame. + let home_sma = home_orbit.semi_major_axis; + let home_orbit_alt = home_sma - parent.radius; + let dest_sma = dest_orbit.semi_major_axis; + let hohmann = calculate_hohmann(parent, home_orbit_alt, dest_sma); + add_step( + &mut steps, + &mut cumulative, + format!("Transfer to {}", destination.name), + hohmann.departure_dv, + SegmentType::Transfer, + String::new(), + ); + + // Step 4: Capture at destination. + let esc_dest = escape_dv_from_low_orbit(destination); + add_step( + &mut steps, + &mut cumulative, + format!("Capture at {}", destination.name), + esc_dest, + SegmentType::Capture, + String::new(), + ); + + match moon { + None => { + // Step 5: Land on destination. + let (powered_dv, aerobrake_dv) = landing_dv(destination); + let note = match aerobrake_dv { + Some(v) => format!("aerobrake option: {v} m/s"), + None => String::new(), + }; + add_step( + &mut steps, + &mut cumulative, + format!("Land on {}", destination.name), + powered_dv, + SegmentType::Landing, + note, + ); + } + Some(moon_body) => { + let moon_orbit = moon_body + .orbit + .as_ref() + .expect("Moon has no orbital elements."); + + // Step 5: Transfer from destination low orbit to moon SMA. + let dest_lo_alt = low_orbit_altitude(destination); + let moon_sma = moon_orbit.semi_major_axis; + let moon_hohmann = calculate_hohmann(destination, dest_lo_alt, moon_sma); + add_step( + &mut steps, + &mut cumulative, + format!("Transfer to {}", moon_body.name), + moon_hohmann.departure_dv, + SegmentType::MoonTransfer, + String::new(), + ); + + // Step 6: Land on moon. + let (powered_dv_moon, aerobrake_dv_moon) = landing_dv(moon_body); + let note_moon = match aerobrake_dv_moon { + Some(v) => format!("aerobrake option: {v} m/s"), + None => String::new(), + }; + add_step( + &mut steps, + &mut cumulative, + format!("Land on {}", moon_body.name), + powered_dv_moon, + SegmentType::MoonLanding, + note_moon, + ); + } + } + + steps +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::*; + + fn make_sanctar() -> CelestialBody { + let mut body = CelestialBody::new( + "Kerbin".to_string(), + 670_000.0, + 1.1, + true, + Some(Atmosphere { + atmosphere_depth: 72_000.0, + pressure_curve: vec![ + CurveKey { + position: 0.0, + value: 110.444, + in_tangent: 0.0, + out_tangent: -0.01793, + }, + CurveKey { + position: 3547.0, + value: 62.1074, + in_tangent: -0.01093, + out_tangent: -0.01093, + }, + ], + temperature_curve: vec![ + CurveKey { + position: 0.0, + value: 281.0, + in_tangent: 0.0, + out_tangent: -0.00536, + }, + CurveKey { + position: 72000.0, + value: 187.0, + in_tangent: 0.0, + out_tangent: 0.0, + }, + ], + molar_mass: 0.02897, + adiabatic_index: 1.4, + pressure_at_sea_level: 110.444, + temperature_at_sea_level: 281.0, + }), + None, + 90291.8, + "Sanctar".to_string(), + ); + body.is_home_world = true; + body + } + + fn make_kerbin() -> CelestialBody { + let mut body = CelestialBody::new( + "Kerbin".to_string(), + 600_000.0, + 1.0, + true, + Some(Atmosphere { + atmosphere_depth: 70_000.0, + pressure_curve: vec![ + CurveKey { + position: 0.0, + value: 101.325, + in_tangent: 0.0, + out_tangent: -0.015, + }, + CurveKey { + position: 70000.0, + value: 0.0, + in_tangent: -0.001, + out_tangent: 0.0, + }, + ], + temperature_curve: vec![ + CurveKey { + position: 0.0, + value: 288.0, + in_tangent: 0.0, + out_tangent: -0.006, + }, + CurveKey { + position: 70000.0, + value: 200.0, + in_tangent: 0.0, + out_tangent: 0.0, + }, + ], + molar_mass: 0.02897, + adiabatic_index: 1.4, + pressure_at_sea_level: 101.325, + temperature_at_sea_level: 288.0, + }), + None, + 21549.425, + "Kerbin".to_string(), + ); + body.is_home_world = true; + body + } + + fn make_airless() -> CelestialBody { + CelestialBody::new( + "Mun".to_string(), + 200_000.0, + 0.166, + false, + None, + None, + 0.0, + "Mun".to_string(), + ) + } + + #[test] + fn test_escape_velocity_sanctar() { + let body = make_sanctar(); + let v = escape_velocity(&body, 0.0); + assert!( + (v - 3802.0).abs() / 3802.0 < 0.001, + "Expected ~3802, got {v}" + ); + } + + #[test] + fn test_escape_velocity_kerbin() { + let body = make_kerbin(); + let v = escape_velocity(&body, 0.0); + assert!( + (v - 3431.0).abs() / 3431.0 < 0.002, + "Expected ~3431, got {v}" + ); + } + + #[test] + fn test_circular_velocity_sanctar_low_orbit() { + let body = make_sanctar(); + let alt = low_orbit_altitude(&body); + let v = circular_velocity(&body, alt); + assert!( + (v - 2541.1).abs() / 2541.1 < 0.01, + "Expected ~2541.1, got {v}" + ); + } + + #[test] + fn test_low_orbit_altitude_with_atmosphere() { + let body = make_sanctar(); + let alt = low_orbit_altitude(&body); + assert!( + (alt - 79200.0).abs() < 100.0, + "Expected ~79200 (72000 * 1.1), got {alt}" + ); + } + + #[test] + fn test_low_orbit_altitude_airless() { + let body = make_airless(); + let alt = low_orbit_altitude(&body); + assert!( + (alt - 10_000.0).abs() < 1.0, + "Expected ~10000 (max(200000*0.05=10000, 10000)), got {alt}" + ); + } + + #[test] + fn test_surface_density_sanctar() { + let body = make_sanctar(); + let rho = surface_density(&body).unwrap(); + assert!( + (rho - 1.4096).abs() / 1.4096 < 0.05, + "Expected ~1.4096, got {rho}" + ); + } + + #[test] + fn test_surface_density_airless() { + let body = make_airless(); + assert!(surface_density(&body).is_none()); + } + + #[test] + fn test_calculate_launch_sanctar() { + let body = make_sanctar(); + let alt = low_orbit_altitude(&body); + let result = calculate_launch(&body, alt); + assert!( + (result.total_rocket - 3110.0).abs() / 3110.0 < 0.02, + "Expected total_rocket ~3110, got {}", + result.total_rocket + ); + assert!( + (result.total_with_jets - 1982.0).abs() / 1982.0 < 0.02, + "Expected total_with_jets ~1982, got {}", + result.total_with_jets + ); + } + + #[test] + fn test_calculate_hohmann_outward() { + let body = make_sanctar(); + let result = calculate_hohmann(&body, 80_000.0, 13_116_000_574.0); + assert!(result.departure_dv > 0.0); + assert!(result.arrival_dv > 0.0); + assert!(!result.inward); + } + + #[test] + fn test_calculate_hohmann_inward() { + let body = make_sanctar(); + let result = calculate_hohmann(&body, 80_000.0, 100_000.0); + assert!(result.inward); + } + + #[test] + fn test_calculate_tsiolkovsky() { + let result = calculate_tsiolkovsky(3100.0, 310.0, 50_000.0); + assert!(result.mass_ratio > 1.0); + assert!(result.fuel_fraction > 0.0 && result.fuel_fraction < 1.0); + assert!( + (result.dry_mass + result.fuel_mass - 50_000.0).abs() < 1.0, + "dry + fuel should equal wet mass: {} + {} = {}", + result.dry_mass, + result.fuel_mass, + result.dry_mass + result.fuel_mass + ); + } + + #[test] + fn test_geostationary_altitude() { + let body = make_sanctar(); + let alt = geostationary_altitude(&body); + assert!( + alt > 0.0, + "Geostationary altitude should be positive, got {alt}" + ); + } + + #[test] + fn test_landing_dv_with_atmosphere() { + let body = make_sanctar(); + let (powered, aerobrake) = landing_dv(&body); + assert!(powered > 0.0); + assert_eq!(aerobrake, Some(0.0)); + } + + #[test] + fn test_landing_dv_airless() { + let body = make_airless(); + let (powered, aerobrake) = landing_dv(&body); + assert!(powered > 0.0); + assert!(aerobrake.is_none()); + } + + #[test] + fn test_escape_dv_from_low_orbit() { + let body = make_sanctar(); + let dv = escape_dv_from_low_orbit(&body); + assert!(dv > 0.0, "Escape dv should be positive, got {dv}"); + // Escape dv should be less than escape velocity (since we start from orbit) + let v_esc = escape_velocity(&body, 0.0); + assert!( + dv < v_esc, + "Escape dv from orbit ({dv}) should be < surface escape ({v_esc})" + ); + } + + #[test] + fn test_density_at_altitude_above_atmosphere() { + let body = make_sanctar(); + let rho = density_at_altitude(&body, 100_000.0).unwrap(); + assert!( + (rho - 0.0).abs() < 1e-10, + "Density above atmosphere should be 0, got {rho}" + ); + } + + #[test] + fn test_compute_route_third_cosmic() { + let mut home = make_sanctar(); + home.orbit = Some(OrbitalElements { + semi_major_axis: 13_116_000_574.0, + eccentricity: 0.0, + inclination: 0.0, + argument_of_periapsis: 0.0, + longitude_of_ascending_node: 0.0, + mean_anomaly_at_epoch: 0.0, + epoch: 0.0, + }); + + let parent = CelestialBody::new( + "Star".to_string(), + 261_600_000.0, + 1.0, + false, + None, + None, + 0.0, + "Star".to_string(), + ); + + let steps = compute_route(&home, &parent, None, None); + assert_eq!(steps.len(), 3, "Third cosmic velocity should have 3 steps"); + assert!(steps[0].dv > 0.0); + assert!(steps[1].dv > 0.0); + assert!(steps[2].dv > 0.0); + assert!(steps[2].cumulative > steps[1].cumulative); + } +} diff --git a/src-tauri/crates/kopdeltav/src/i18n.rs b/src-tauri/crates/kopdeltav/src/i18n.rs new file mode 100644 index 0000000..387418b --- /dev/null +++ b/src-tauri/crates/kopdeltav/src/i18n.rs @@ -0,0 +1,493 @@ +//! Multilingual translation system for CLI and backend output. +//! +//! Provides translation lookup by dot-notation keys with fallback to English +//! and then to the key itself. Supports Japanese, English, and Indonesian. +//! +//! 多言語翻訳モジュール。 + +use std::collections::HashMap; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +/// Supported language codes. +pub const SUPPORTED_LANGUAGES: &[&str] = &["ja", "en", "id"]; + +/// Default UI language. +pub const DEFAULT_LANGUAGE: &str = "ja"; + +// --------------------------------------------------------------------------- +// Translation data +// --------------------------------------------------------------------------- + +/// Build the complete translation table for a given language. +/// +/// 指定言語の翻訳テーブルを構築する。 +fn build_translations(lang: &str) -> HashMap<&'static str, &'static str> { + match lang { + "ja" => build_ja(), + "en" => build_en(), + "id" => build_id(), + _ => HashMap::new(), + } +} + +fn build_ja() -> HashMap<&'static str, &'static str> { + let mut m = HashMap::new(); + // nav + m.insert("nav.title", "KSPDeltaVForMods"); + m.insert("nav.bodies", "天体一覧"); + // body + m.insert("body.name", "天体名"); + m.insert("body.radius", "半径"); + m.insert("body.radius_short", "半径"); + m.insert("body.mass", "質量"); + m.insert("body.gravity", "表面重力"); + m.insert("body.atmosphere", "大気"); + m.insert("body.has_atmosphere", "大気あり"); + m.insert("body.no_atmosphere", "大気なし"); + m.insert("body.has_ocean", "海洋あり"); + m.insert("body.no_ocean", "海洋なし"); + // launch + m.insert("launch.title", "低軌道投入\u{0394}V"); + m.insert("launch.orbital_velocity", "軌道速度"); + m.insert("launch.gravity_loss", "重力損失"); + m.insert("launch.drag_loss", "大気抵抗損失"); + m.insert("launch.total_ideal", "理論最小\u{0394}V"); + m.insert("launch.total_rocket", "ロケット\u{0394}V\u{ff08}実用値\u{ff09}"); + m.insert("launch.jet_savings", "ジェット節約分"); + m.insert("launch.total_with_jets", "ジェット併用\u{0394}V"); + m.insert("launch.target_altitude", "目標高度"); + m.insert("launch.geostationary", "静止軌道遷移"); + m.insert("launch.geostationary_altitude", "静止軌道高度"); + // hohmann + m.insert("hohmann.title", "ホーマン遷移"); + m.insert("hohmann.departure_dv", "出発\u{0394}V"); + m.insert("hohmann.arrival_dv", "到着\u{0394}V"); + m.insert("hohmann.total_dv", "合計\u{0394}V"); + m.insert("hohmann.transfer_time", "遷移時間"); + // tsiolkovsky + m.insert("tsiolkovsky.title", "ツィオルコフスキーの公式"); + m.insert("tsiolkovsky.mass_ratio", "質量比"); + m.insert("tsiolkovsky.fuel_fraction", "燃料割合"); + m.insert("tsiolkovsky.dry_mass", "乾燥質量"); + m.insert("tsiolkovsky.fuel_mass", "燃料質量"); + m.insert("tsiolkovsky.delta_v", "\u{0394}V"); + m.insert("tsiolkovsky.isp", "比推力"); + m.insert("tsiolkovsky.wet_mass", "湿潤質量"); + // atmosphere + m.insert("atmosphere.title", "大気プロファイル"); + m.insert("atmosphere.depth", "大気高度上限"); + m.insert("atmosphere.sea_level_pressure", "海面気圧"); + m.insert("atmosphere.sea_level_temperature", "海面温度"); + m.insert("atmosphere.sea_level_density", "海面大気密度"); + m.insert("atmosphere.molar_mass", "モル質量"); + m.insert("atmosphere.adiabatic_index", "断熱指数"); + // common + m.insert("common.calculate", "計算"); + m.insert("common.reset", "リセット"); + m.insert("common.error", "エラー"); + m.insert("common.warning", "警告"); + m.insert("common.unit_m", "m"); + m.insert("common.unit_ms", "m/s"); + m.insert("common.unit_s", "秒"); + m.insert("common.unit_kg", "kg"); + m.insert("common.unit_kgm3", "kg/m\u{b3}"); + m.insert("common.unit_kpa", "kPa"); + m.insert("common.unit_k", "K"); + // route + m.insert("route.launch", "低軌道投入"); + m.insert("route.escape", "母星脱出"); + m.insert("route.transfer", "惑星間遷移"); + m.insert("route.orbit_insertion", "軌道投入"); + m.insert("route.landing", "着陸"); + m.insert("route.moon_transfer", "衛星遷移"); + m.insert("route.moon_landing", "衛星着陸"); + m.insert("route.system_escape", "恒星系脱出"); + m.insert("route.third_cosmic", "第三宇宙速度"); + m.insert("route.powered_landing", "パワード着陸"); + m.insert("route.aerobrake_landing", "エアロブレーキ着陸"); + m.insert("route.cumulative", "累積\u{0394}V"); + m.insert("route.step", "ステップ"); + m.insert("route.dv", "\u{0394}V"); + m.insert("route.total", "合計"); + // system + m.insert("system.home_world", "母星"); + m.insert("system.star", "恒星"); + m.insert("system.planets", "惑星一覧"); + m.insert("system.moons", "衛星一覧"); + m.insert("system.select_destination", "遷移先を選択"); + m.insert("system.select_moon", "衛星を選択"); + m.insert("system.press_enter_escape", "Enterで恒星系脱出"); + m.insert("system.press_enter_land", "Enterで着陸"); + m.insert("system.no_bodies", "天体が見つかりません"); + m.insert("system.scanning", "GameDataをスキャン中..."); + // error + m.insert("error.file_not_found", "ファイルが見つかりません"); + m.insert("error.parse_error", "設定ファイルの解析に失敗しました"); + m.insert("error.no_bodies", "天体が見つかりません"); + m.insert("error.invalid_altitude", "高度は非負でなければなりません"); + m +} + +fn build_en() -> HashMap<&'static str, &'static str> { + let mut m = HashMap::new(); + // nav + m.insert("nav.title", "KSPDeltaVForMods"); + m.insert("nav.bodies", "Celestial Bodies"); + // body + m.insert("body.name", "Body Name"); + m.insert("body.radius", "Radius"); + m.insert("body.radius_short", "R"); + m.insert("body.mass", "Mass"); + m.insert("body.gravity", "Surface Gravity"); + m.insert("body.atmosphere", "Atmosphere"); + m.insert("body.has_atmosphere", "Has Atmosphere"); + m.insert("body.no_atmosphere", "No Atmosphere"); + m.insert("body.has_ocean", "Has Ocean"); + m.insert("body.no_ocean", "No Ocean"); + // launch + m.insert("launch.title", "Launch to Low Orbit \u{0394}V"); + m.insert("launch.orbital_velocity", "Orbital Velocity"); + m.insert("launch.gravity_loss", "Gravity Loss"); + m.insert("launch.drag_loss", "Drag Loss"); + m.insert("launch.total_ideal", "Theoretical Minimum \u{0394}V"); + m.insert("launch.total_rocket", "Rocket \u{0394}V (Practical)"); + m.insert("launch.jet_savings", "Jet Engine Savings"); + m.insert("launch.total_with_jets", "\u{0394}V with Jets"); + m.insert("launch.target_altitude", "Target Altitude"); + m.insert("launch.geostationary", "Geostationary Transfer"); + m.insert("launch.geostationary_altitude", "Geostationary Altitude"); + // hohmann + m.insert("hohmann.title", "Hohmann Transfer"); + m.insert("hohmann.departure_dv", "Departure \u{0394}V"); + m.insert("hohmann.arrival_dv", "Arrival \u{0394}V"); + m.insert("hohmann.total_dv", "Total \u{0394}V"); + m.insert("hohmann.transfer_time", "Transfer Time"); + // tsiolkovsky + m.insert("tsiolkovsky.title", "Tsiolkovsky Rocket Equation"); + m.insert("tsiolkovsky.mass_ratio", "Mass Ratio"); + m.insert("tsiolkovsky.fuel_fraction", "Fuel Fraction"); + m.insert("tsiolkovsky.dry_mass", "Dry Mass"); + m.insert("tsiolkovsky.fuel_mass", "Fuel Mass"); + m.insert("tsiolkovsky.delta_v", "\u{0394}V"); + m.insert("tsiolkovsky.isp", "Specific Impulse"); + m.insert("tsiolkovsky.wet_mass", "Wet Mass"); + // atmosphere + m.insert("atmosphere.title", "Atmosphere Profile"); + m.insert("atmosphere.depth", "Atmosphere Ceiling"); + m.insert("atmosphere.sea_level_pressure", "Sea Level Pressure"); + m.insert("atmosphere.sea_level_temperature", "Sea Level Temperature"); + m.insert("atmosphere.sea_level_density", "Sea Level Density"); + m.insert("atmosphere.molar_mass", "Molar Mass"); + m.insert("atmosphere.adiabatic_index", "Adiabatic Index"); + // common + m.insert("common.calculate", "Calculate"); + m.insert("common.reset", "Reset"); + m.insert("common.error", "Error"); + m.insert("common.warning", "Warning"); + m.insert("common.unit_m", "m"); + m.insert("common.unit_ms", "m/s"); + m.insert("common.unit_s", "s"); + m.insert("common.unit_kg", "kg"); + m.insert("common.unit_kgm3", "kg/m\u{b3}"); + m.insert("common.unit_kpa", "kPa"); + m.insert("common.unit_k", "K"); + // route + m.insert("route.launch", "Launch to Low Orbit"); + m.insert("route.escape", "Escape Home World"); + m.insert("route.transfer", "Interplanetary Transfer"); + m.insert("route.orbit_insertion", "Orbit Insertion"); + m.insert("route.landing", "Landing"); + m.insert("route.moon_transfer", "Moon Transfer"); + m.insert("route.moon_landing", "Moon Landing"); + m.insert("route.system_escape", "Star System Escape"); + m.insert("route.third_cosmic", "Third Cosmic Velocity"); + m.insert("route.powered_landing", "Powered Landing"); + m.insert("route.aerobrake_landing", "Aerobrake Landing"); + m.insert("route.cumulative", "Cumulative \u{0394}V"); + m.insert("route.step", "Step"); + m.insert("route.dv", "\u{0394}V"); + m.insert("route.total", "Total"); + // system + m.insert("system.home_world", "Home World"); + m.insert("system.star", "Star"); + m.insert("system.planets", "Planets"); + m.insert("system.moons", "Moons"); + m.insert("system.select_destination", "Select destination"); + m.insert("system.select_moon", "Select moon"); + m.insert("system.press_enter_escape", "Press Enter for system escape"); + m.insert("system.press_enter_land", "Press Enter to land"); + m.insert("system.no_bodies", "No celestial bodies found"); + m.insert("system.scanning", "Scanning GameData..."); + // error + m.insert("error.file_not_found", "File not found"); + m.insert("error.parse_error", "Failed to parse configuration file"); + m.insert("error.no_bodies", "No celestial bodies found"); + m.insert("error.invalid_altitude", "Altitude must be non-negative"); + m +} + +fn build_id() -> HashMap<&'static str, &'static str> { + let mut m = HashMap::new(); + // nav + m.insert("nav.title", "KSPDeltaVForMods"); + m.insert("nav.bodies", "Daftar Benda Langit"); + // body + m.insert("body.name", "Nama Benda Langit"); + m.insert("body.radius", "Radius"); + m.insert("body.radius_short", "R"); + m.insert("body.mass", "Massa"); + m.insert("body.gravity", "Gravitasi Permukaan"); + m.insert("body.atmosphere", "Atmosfer"); + m.insert("body.has_atmosphere", "Memiliki Atmosfer"); + m.insert("body.no_atmosphere", "Tanpa Atmosfer"); + m.insert("body.has_ocean", "Memiliki Lautan"); + m.insert("body.no_ocean", "Tanpa Lautan"); + // launch + m.insert("launch.title", "\u{0394}V Peluncuran ke Orbit Rendah"); + m.insert("launch.orbital_velocity", "Kecepatan Orbit"); + m.insert("launch.gravity_loss", "Kehilangan Gravitasi"); + m.insert("launch.drag_loss", "Kehilangan Hambatan Udara"); + m.insert("launch.total_ideal", "\u{0394}V Minimum Teoritis"); + m.insert("launch.total_rocket", "\u{0394}V Roket (Praktis)"); + m.insert("launch.jet_savings", "Penghematan Mesin Jet"); + m.insert("launch.total_with_jets", "\u{0394}V dengan Jet"); + m.insert("launch.target_altitude", "Ketinggian Target"); + m.insert("launch.geostationary", "Transfer Geostasioner"); + m.insert("launch.geostationary_altitude", "Ketinggian Geostasioner"); + // hohmann + m.insert("hohmann.title", "Transfer Hohmann"); + m.insert("hohmann.departure_dv", "\u{0394}V Keberangkatan"); + m.insert("hohmann.arrival_dv", "\u{0394}V Kedatangan"); + m.insert("hohmann.total_dv", "\u{0394}V Total"); + m.insert("hohmann.transfer_time", "Waktu Transfer"); + // tsiolkovsky + m.insert("tsiolkovsky.title", "Persamaan Roket Tsiolkovsky"); + m.insert("tsiolkovsky.mass_ratio", "Rasio Massa"); + m.insert("tsiolkovsky.fuel_fraction", "Fraksi Bahan Bakar"); + m.insert("tsiolkovsky.dry_mass", "Massa Kering"); + m.insert("tsiolkovsky.fuel_mass", "Massa Bahan Bakar"); + m.insert("tsiolkovsky.delta_v", "\u{0394}V"); + m.insert("tsiolkovsky.isp", "Impuls Spesifik"); + m.insert("tsiolkovsky.wet_mass", "Massa Basah"); + // atmosphere + m.insert("atmosphere.title", "Profil Atmosfer"); + m.insert("atmosphere.depth", "Batas Ketinggian Atmosfer"); + m.insert("atmosphere.sea_level_pressure", "Tekanan Permukaan Laut"); + m.insert("atmosphere.sea_level_temperature", "Suhu Permukaan Laut"); + m.insert("atmosphere.sea_level_density", "Kepadatan Permukaan Laut"); + m.insert("atmosphere.molar_mass", "Massa Molar"); + m.insert("atmosphere.adiabatic_index", "Indeks Adiabatik"); + // common + m.insert("common.calculate", "Hitung"); + m.insert("common.reset", "Atur Ulang"); + m.insert("common.error", "Kesalahan"); + m.insert("common.warning", "Peringatan"); + m.insert("common.unit_m", "m"); + m.insert("common.unit_ms", "m/s"); + m.insert("common.unit_s", "s"); + m.insert("common.unit_kg", "kg"); + m.insert("common.unit_kgm3", "kg/m\u{b3}"); + m.insert("common.unit_kpa", "kPa"); + m.insert("common.unit_k", "K"); + // route + m.insert("route.launch", "Peluncuran ke Orbit Rendah"); + m.insert("route.escape", "Lepas dari Planet Asal"); + m.insert("route.transfer", "Transfer Antarplanet"); + m.insert("route.orbit_insertion", "Penyisipan Orbit"); + m.insert("route.landing", "Pendaratan"); + m.insert("route.moon_transfer", "Transfer Bulan"); + m.insert("route.moon_landing", "Pendaratan Bulan"); + m.insert("route.system_escape", "Lepas dari Sistem Bintang"); + m.insert("route.third_cosmic", "Kecepatan Kosmis Ketiga"); + m.insert("route.powered_landing", "Pendaratan Berdaya"); + m.insert("route.aerobrake_landing", "Pendaratan Aerobrake"); + m.insert("route.cumulative", "\u{0394}V Kumulatif"); + m.insert("route.step", "Langkah"); + m.insert("route.dv", "\u{0394}V"); + m.insert("route.total", "Total"); + // system + m.insert("system.home_world", "Planet Asal"); + m.insert("system.star", "Bintang"); + m.insert("system.planets", "Planet"); + m.insert("system.moons", "Bulan"); + m.insert("system.select_destination", "Pilih tujuan"); + m.insert("system.select_moon", "Pilih bulan"); + m.insert( + "system.press_enter_escape", + "Tekan Enter untuk lepas dari sistem", + ); + m.insert("system.press_enter_land", "Tekan Enter untuk mendarat"); + m.insert("system.no_bodies", "Tidak ada benda langit ditemukan"); + m.insert("system.scanning", "Memindai GameData..."); + // error + m.insert("error.file_not_found", "Berkas tidak ditemukan"); + m.insert("error.parse_error", "Gagal mengurai berkas konfigurasi"); + m.insert("error.no_bodies", "Tidak ada benda langit ditemukan"); + m.insert("error.invalid_altitude", "Ketinggian harus non-negatif"); + m +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +/// Get translated text by dot-notation key. +/// +/// 翻訳文字列を取得する。要求言語にキーがなければ英語にフォールバックし、 +/// 英語にもなければキー文字列をそのまま返す。 +/// +/// # Arguments +/// * `key` - Dot-notation key (e.g. "launch.title", "common.calculate"). +/// * `lang` - Language code ("ja", "en", or "id"). Falls back to English +/// if the key is missing in the requested language. +/// +/// # Returns +/// Translated string. Returns the key itself if not found in any language. +pub fn get_text(key: &str, lang: &str) -> String { + let effective_lang = if SUPPORTED_LANGUAGES.contains(&lang) { + lang + } else { + DEFAULT_LANGUAGE + }; + + // Key must be "category.name" format + if !key.contains('.') { + return key.to_string(); + } + + // Try requested language first + let translations = build_translations(effective_lang); + if let Some(value) = translations.get(key) { + return (*value).to_string(); + } + + // Fall back to English + if effective_lang != "en" { + let en_translations = build_translations("en"); + if let Some(value) = en_translations.get(key) { + return (*value).to_string(); + } + } + + // Key not found anywhere: return the key itself + key.to_string() +} + +/// Get all translation keys flattened to dot-notation for a language. +/// +/// 全翻訳キーをフラット化して返す。 +/// +/// # Arguments +/// * `lang` - Language code ("ja", "en", or "id"). Falls back to DEFAULT_LANGUAGE +/// if not supported. +/// +/// # Returns +/// HashMap mapping dot-notation keys to translated strings. +pub fn get_all_keys(lang: &str) -> HashMap { + let effective_lang = if SUPPORTED_LANGUAGES.contains(&lang) { + lang + } else { + DEFAULT_LANGUAGE + }; + + build_translations(effective_lang) + .into_iter() + .map(|(k, v)| (k.to_string(), v.to_string())) + .collect() +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_get_text_japanese() { + assert_eq!(get_text("nav.title", "ja"), "KSPDeltaVForMods"); + } + + #[test] + fn test_get_text_english() { + assert_eq!(get_text("nav.bodies", "en"), "Celestial Bodies"); + } + + #[test] + fn test_get_text_indonesian() { + assert_eq!(get_text("nav.bodies", "id"), "Daftar Benda Langit"); + } + + #[test] + fn test_get_text_fallback_to_default_then_english() { + // Unsupported lang falls back to DEFAULT_LANGUAGE ("ja") first + // "nav.title" is "KSPDeltaVForMods" in all languages + assert_eq!(get_text("nav.title", "xx"), "KSPDeltaVForMods"); + } + + #[test] + fn test_get_text_unknown_key_returns_key() { + assert_eq!(get_text("unknown.key", "en"), "unknown.key"); + } + + #[test] + fn test_get_all_keys_has_entries() { + let keys = get_all_keys("en"); + assert!(keys.contains_key("nav.title")); + assert!(keys.contains_key("launch.title")); + } + + #[test] + fn test_get_all_keys_unsupported_lang_uses_default() { + let keys = get_all_keys("xx"); + // Should fall back to Japanese (DEFAULT_LANGUAGE) + assert_eq!(keys.get("nav.bodies").unwrap(), "天体一覧"); + } + + #[test] + fn test_get_text_no_dot_returns_key() { + assert_eq!(get_text("nodotkey", "en"), "nodotkey"); + } + + #[test] + fn test_all_three_languages_have_same_keys() { + let ja_keys: Vec = get_all_keys("ja").keys().cloned().collect(); + let en_keys = get_all_keys("en"); + let id_keys = get_all_keys("id"); + for key in &ja_keys { + assert!( + en_keys.contains_key(key), + "English missing key: {}", + key + ); + assert!( + id_keys.contains_key(key), + "Indonesian missing key: {}", + key + ); + } + } + + #[test] + fn test_japanese_specific_values() { + assert_eq!(get_text("common.calculate", "ja"), "計算"); + assert_eq!(get_text("common.reset", "ja"), "リセット"); + assert_eq!(get_text("hohmann.title", "ja"), "ホーマン遷移"); + } + + #[test] + fn test_english_specific_values() { + assert_eq!(get_text("common.calculate", "en"), "Calculate"); + assert_eq!(get_text("hohmann.title", "en"), "Hohmann Transfer"); + } + + #[test] + fn test_indonesian_specific_values() { + assert_eq!(get_text("common.calculate", "id"), "Hitung"); + assert_eq!(get_text("hohmann.title", "id"), "Transfer Hohmann"); + } +} diff --git a/src-tauri/crates/kopdeltav/src/lib.rs b/src-tauri/crates/kopdeltav/src/lib.rs new file mode 100644 index 0000000..a238ed8 --- /dev/null +++ b/src-tauri/crates/kopdeltav/src/lib.rs @@ -0,0 +1,5 @@ +pub mod calculator; +pub mod i18n; +pub mod models; +pub mod parser; +pub mod system; diff --git a/src-tauri/crates/kopdeltav/src/models.rs b/src-tauri/crates/kopdeltav/src/models.rs new file mode 100644 index 0000000..ae7b93d --- /dev/null +++ b/src-tauri/crates/kopdeltav/src/models.rs @@ -0,0 +1,404 @@ +//! Core domain models for KSP celestial body physics. +//! +//! Provides data structures for celestial bodies, atmospheres, orbital elements, +//! and animation curve interpolation (Cubic Hermite Spline) compatible with +//! KSP's AnimationCurve format. + +use serde::Serialize; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +/// Standard gravitational acceleration at sea level [m/s^2]. +pub const G0: f64 = 9.80665; + +/// Universal gas constant [J/(mol*K)]. +pub const R_GAS: f64 = 8.314_462_618; + +// --------------------------------------------------------------------------- +// Functions +// --------------------------------------------------------------------------- + +/// Compute the standard gravitational parameter (mu) for a celestial body. +/// +/// mu = gee_asl * G0 * radius^2 +/// +/// # Arguments +/// * `gee_asl` - Surface gravity in multiples of g0. +/// * `radius` - Equatorial radius [m]. +/// +/// # Returns +/// Gravitational parameter mu [m^3/s^2]. +pub fn compute_mu(gee_asl: f64, radius: f64) -> f64 { + gee_asl * G0 * radius * radius +} + +// --------------------------------------------------------------------------- +// Structs +// --------------------------------------------------------------------------- + +/// A single keyframe in a KSP AnimationCurve. +/// +/// KSPのAnimationCurveキーフレーム。 +#[derive(Debug, Clone, Serialize)] +pub struct CurveKey { + /// Curve position (x-axis value, e.g. altitude). + pub position: f64, + /// Curve value at this position (y-axis value). + pub value: f64, + /// Incoming tangent (slope on the left side of the key). + pub in_tangent: f64, + /// Outgoing tangent (slope on the right side of the key). + pub out_tangent: f64, +} + +/// Atmospheric model for a celestial body. +/// +/// 天体の大気モデル。 +#[derive(Debug, Clone, Serialize)] +pub struct Atmosphere { + /// Height of the atmosphere above the surface [m]. + pub atmosphere_depth: f64, + /// Pressure curve keyframes (altitude -> pressure in kPa). + pub pressure_curve: Vec, + /// Temperature curve keyframes (altitude -> temperature in K). + pub temperature_curve: Vec, + /// Molar mass of the atmosphere [kg/mol]. + pub molar_mass: f64, + /// Adiabatic index (ratio of specific heats, Cp/Cv). + pub adiabatic_index: f64, + /// Sea-level pressure [kPa]. + pub pressure_at_sea_level: f64, + /// Sea-level temperature [K]. + pub temperature_at_sea_level: f64, +} + +/// Keplerian orbital elements for a celestial body. +/// +/// 天体のケプラー軌道要素。 +#[derive(Debug, Clone, Serialize)] +pub struct OrbitalElements { + /// Semi-major axis [m]. + pub semi_major_axis: f64, + /// Orbital eccentricity (0 = circular, <1 = elliptical). + pub eccentricity: f64, + /// Orbital inclination [degrees]. + pub inclination: f64, + /// Argument of periapsis [degrees]. + pub argument_of_periapsis: f64, + /// Longitude of ascending node [degrees]. + pub longitude_of_ascending_node: f64, + /// Mean anomaly at epoch [radians]. + pub mean_anomaly_at_epoch: f64, + /// Reference epoch [s]. + pub epoch: f64, +} + +/// A celestial body in the KSP system with physical and orbital properties. +/// +/// KSPの天体(物理・軌道パラメータ付き)。 +/// +/// Not `Serialize` because parent/children references form a graph +/// that is resolved externally by name. +#[derive(Debug, Clone)] +pub struct CelestialBody { + /// Internal name (e.g. "Kerbin"). + pub name: String, + /// Equatorial radius [m]. + pub radius: f64, + /// Surface gravity in multiples of g0. + pub gee_asl: f64, + /// Whether the body has an ocean. + pub has_ocean: bool, + /// Atmospheric model, if present. + pub atmosphere: Option, + /// Orbital elements, if the body orbits another body. + pub orbit: Option, + /// Sidereal rotational period [s]. + pub rotational_period: f64, + /// Display name (may differ from internal name). + pub display_name: String, + /// Sphere of influence radius [m]. + pub soi: f64, + /// Whether this is the home world (e.g. Kerbin). + pub is_home_world: bool, + /// Name of the parent body this body orbits. + pub reference_body_name: String, + /// Standard gravitational parameter mu [m^3/s^2] (auto-computed). + pub mu: f64, + /// Parent body name for tree construction. + pub parent_name: Option, + /// Child body names for tree construction. + pub children_names: Vec, +} + +impl CelestialBody { + /// Create a new celestial body with auto-computed mu. + /// + /// 天体を生成し、muを自動計算する。 + /// + /// # Arguments + /// * `name` - Internal name. + /// * `radius` - Equatorial radius [m]. + /// * `gee_asl` - Surface gravity in multiples of g0. + /// * `has_ocean` - Whether the body has an ocean. + /// * `atmosphere` - Atmospheric model, if any. + /// * `orbit` - Orbital elements, if any. + /// * `rotational_period` - Sidereal rotational period [s]. + /// * `display_name` - Display name for UI. + #[allow(clippy::too_many_arguments)] + pub fn new( + name: String, + radius: f64, + gee_asl: f64, + has_ocean: bool, + atmosphere: Option, + orbit: Option, + rotational_period: f64, + display_name: String, + ) -> Self { + let mu = compute_mu(gee_asl, radius); + Self { + name, + radius, + gee_asl, + has_ocean, + atmosphere, + orbit, + rotational_period, + display_name, + soi: 0.0, + is_home_world: false, + reference_body_name: String::new(), + mu, + parent_name: None, + children_names: Vec::new(), + } + } + + /// Returns true if the body has an atmosphere. + /// + /// 大気を持つかどうかを返す。 + pub fn has_atmosphere(&self) -> bool { + self.atmosphere.is_some() + } +} + +// --------------------------------------------------------------------------- +// Hermite interpolation +// --------------------------------------------------------------------------- + +/// Evaluate a Cubic Hermite Spline at position `x`, compatible with KSP AnimationCurve. +/// +/// KSP AnimationCurve互換のCubic Hermite Spline補間。 +/// +/// Values outside the curve range are clamped to the nearest endpoint value. +/// +/// # Arguments +/// * `keys` - Sorted keyframes defining the curve. +/// * `x` - Position to evaluate at. +/// +/// # Returns +/// Interpolated value, or an error if `keys` is empty. +/// +/// # Errors +/// Returns `Err` if the keys slice is empty. +pub fn hermite_interp(keys: &[CurveKey], x: f64) -> Result { + if keys.is_empty() { + return Err("Cannot interpolate with empty keys list".to_string()); + } + if keys.len() == 1 { + return Ok(keys[0].value); + } + if x <= keys[0].position { + return Ok(keys[0].value); + } + if x >= keys[keys.len() - 1].position { + return Ok(keys[keys.len() - 1].value); + } + + // Find the segment containing x + let mut i = 0; + for (j, key) in keys.iter().enumerate().skip(1) { + if key.position >= x { + i = j - 1; + break; + } + } + + let k0 = &keys[i]; + let k1 = &keys[i + 1]; + let dx = k1.position - k0.position; + let t = (x - k0.position) / dx; + + let t2 = t * t; + let t3 = t2 * t; + let h00 = 2.0 * t3 - 3.0 * t2 + 1.0; + let h10 = t3 - 2.0 * t2 + t; + let h01 = -2.0 * t3 + 3.0 * t2; + let h11 = t3 - t2; + + Ok(h00 * k0.value + h10 * dx * k0.out_tangent + h01 * k1.value + h11 * dx * k1.in_tangent) +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + // Constants + #[test] + fn test_g0_constant() { + assert!((G0 - 9.80665).abs() < 1e-10); + } + + // compute_mu + #[test] + fn test_compute_mu_sanctar() { + let mu = compute_mu(1.1, 670_000.0); + let expected = 4.8424e12; + assert!((mu - expected).abs() / expected < 0.001); + } + + #[test] + fn test_compute_mu_kerbin() { + let mu = compute_mu(1.0, 600_000.0); + let expected = 3.5316e12; + assert!((mu - expected).abs() / expected < 0.001); + } + + // CurveKey + #[test] + fn test_curve_key_creation() { + let key = CurveKey { + position: 0.0, + value: 110.444, + in_tangent: 0.0, + out_tangent: -0.01793, + }; + assert!((key.value - 110.444).abs() < 1e-6); + } + + // Hermite interpolation + #[test] + fn test_hermite_interp_at_key_position() { + let keys = vec![ + CurveKey { + position: 0.0, + value: 110.444, + in_tangent: 0.0, + out_tangent: -0.01793, + }, + CurveKey { + position: 3547.0, + value: 62.1074, + in_tangent: -0.01093, + out_tangent: -0.01093, + }, + ]; + let result = hermite_interp(&keys, 0.0).unwrap(); + assert!((result - 110.444).abs() < 1e-6); + } + + #[test] + fn test_hermite_interp_midpoint() { + let keys = vec![ + CurveKey { + position: 0.0, + value: 110.444, + in_tangent: 0.0, + out_tangent: -0.01793, + }, + CurveKey { + position: 3547.0, + value: 62.1074, + in_tangent: -0.01093, + out_tangent: -0.01093, + }, + ]; + let result = hermite_interp(&keys, 1773.5).unwrap(); + assert!(result > 62.0 && result < 111.0); + } + + #[test] + fn test_hermite_interp_clamps_below() { + let keys = vec![ + CurveKey { + position: 0.0, + value: 110.444, + in_tangent: 0.0, + out_tangent: -0.01793, + }, + CurveKey { + position: 3547.0, + value: 62.1074, + in_tangent: -0.01093, + out_tangent: -0.01093, + }, + ]; + let result = hermite_interp(&keys, -100.0).unwrap(); + assert!((result - 110.444).abs() < 1e-6); + } + + #[test] + fn test_hermite_interp_clamps_above() { + let keys = vec![ + CurveKey { + position: 0.0, + value: 110.444, + in_tangent: 0.0, + out_tangent: -0.01793, + }, + CurveKey { + position: 3547.0, + value: 62.1074, + in_tangent: -0.01093, + out_tangent: -0.01093, + }, + ]; + let result = hermite_interp(&keys, 5000.0).unwrap(); + assert!((result - 62.1074).abs() < 1e-6); + } + + #[test] + fn test_hermite_interp_empty_keys() { + let keys: Vec = vec![]; + assert!(hermite_interp(&keys, 0.0).is_err()); + } + + // CelestialBody + #[test] + fn test_celestial_body_mu() { + let body = CelestialBody::new( + "Kerbin".to_string(), + 670_000.0, + 1.1, + true, + None, + None, + 90291.8, + "Sanctar".to_string(), + ); + let expected = 4.8424e12; + assert!((body.mu - expected).abs() / expected < 0.001); + } + + #[test] + fn test_celestial_body_has_atmosphere() { + let body_no_atmo = CelestialBody::new( + "Moon".to_string(), + 200_000.0, + 0.166, + false, + None, + None, + 0.0, + "Moon".to_string(), + ); + assert!(!body_no_atmo.has_atmosphere()); + } +} diff --git a/src-tauri/crates/kopdeltav/src/parser.rs b/src-tauri/crates/kopdeltav/src/parser.rs new file mode 100644 index 0000000..029f316 --- /dev/null +++ b/src-tauri/crates/kopdeltav/src/parser.rs @@ -0,0 +1,856 @@ +//! Kopernicus ConfigNode parser for KSP `.cfg` files. +//! +//! Two-layer design: +//! 1. **Low-level**: `ConfigNode` tree parsed from raw text. +//! 2. **High-level**: `parse_bodies` extracts `CelestialBody` instances from the tree. +//! +//! KSP ConfigNodeパーサー(2層構成)。 + +use crate::models::{Atmosphere, CelestialBody, CurveKey, OrbitalElements}; + +// --------------------------------------------------------------------------- +// Constants +// --------------------------------------------------------------------------- + +/// Characters used as ModuleManager modifier prefixes on node names. +const MODIFIER_CHARS: &[char] = &['@', '!', '+', '-', '%']; + +// --------------------------------------------------------------------------- +// ConfigNode +// --------------------------------------------------------------------------- + +/// A node in the KSP ConfigNode tree. +/// +/// KSP ConfigNodeツリーのノード。 +#[derive(Debug, Clone)] +pub struct ConfigNode { + /// Node name (modifiers stripped). + pub name: String, + /// Key-value pairs declared directly in this node. + pub values: Vec<(String, String)>, + /// Child nodes. + pub children: Vec, +} + +impl ConfigNode { + /// Create a new empty ConfigNode with the given name. + fn new(name: impl Into) -> Self { + Self { + name: name.into(), + values: Vec::new(), + children: Vec::new(), + } + } + + /// Get the first value for a given key, or `None` if not found. + /// + /// 指定キーの最初の値を返す。 + pub fn get_value(&self, key: &str) -> Option<&str> { + self.values + .iter() + .find(|(k, _)| k == key) + .map(|(_, v)| v.as_str()) + } + + /// Get all values for a given key. + /// + /// 指定キーの全値を返す。 + pub fn get_values(&self, key: &str) -> Vec<&str> { + self.values + .iter() + .filter(|(k, _)| k == key) + .map(|(_, v)| v.as_str()) + .collect() + } + + /// Get the first child node with the given name, or `None`. + /// + /// 指定名の最初の子ノードを返す。 + pub fn get_child(&self, name: &str) -> Option<&ConfigNode> { + self.children.iter().find(|c| c.name == name) + } +} + +// --------------------------------------------------------------------------- +// Low-level parser +// --------------------------------------------------------------------------- + +/// Strip `//` comments from a line and trim whitespace. +fn strip_comments(line: &str) -> &str { + match line.find("//") { + Some(idx) => line[..idx].trim(), + None => line.trim(), + } +} + +/// Remove ModuleManager modifier prefixes, colon annotations, and bracket +/// expressions from a raw node name. +fn clean_node_name(raw: &str) -> String { + let mut s = raw.trim(); + + // Strip leading modifier chars + while let Some(first) = s.chars().next() { + if MODIFIER_CHARS.contains(&first) { + s = &s[first.len_utf8()..]; + } else { + break; + } + } + + // Strip :AFTER[...] etc. + if let Some(colon_idx) = s.find(':') { + s = &s[..colon_idx]; + } + + // Strip [Name] bracket expressions + if let Some(bracket_idx) = s.find('[') { + s = &s[..bracket_idx]; + } + + s.trim().to_string() +} + +/// Returns true if the line is a delete directive like `!Body[Kerbin]{}`. +fn is_delete_directive(line: &str) -> bool { + if !line.starts_with('!') { + return false; + } + // Pattern: !Word[...]{ optional whitespace } + // Match: starts with !, has word chars, brackets, then { } with optional whitespace + let rest = &line[1..]; + let Some(bracket_start) = rest.find('[') else { + return false; + }; + // Must have word chars before bracket + if bracket_start == 0 + || !rest[..bracket_start] + .chars() + .all(|c| c.is_alphanumeric() || c == '_') + { + return false; + } + let Some(bracket_end) = rest.find(']') else { + return false; + }; + if bracket_end <= bracket_start { + return false; + } + let after_bracket = rest[bracket_end + 1..].trim(); + // Must end with {} + if after_bracket == "{}" { + return true; + } + // Or { } with whitespace + if after_bracket.starts_with('{') && after_bracket.ends_with('}') { + let inner = &after_bracket[1..after_bracket.len() - 1]; + return inner.trim().is_empty(); + } + false +} + +/// Close the top node on the stack, attaching it to its parent or to top-level. +fn close_node(stack: &mut Vec, top_level: &mut Vec) { + if let Some(closed) = stack.pop() { + if let Some(parent) = stack.last_mut() { + parent.children.push(closed); + } else { + top_level.push(closed); + } + } +} + +/// Process a single logical line fragment (after comment stripping). +/// +/// This is factored out so that content remaining after an opening `{` +/// on the same physical line can be recursively processed. +fn process_fragment( + line: &str, + stack: &mut Vec, + top_level: &mut Vec, + pending_name: &mut Option, +) { + let line = line.trim(); + if line.is_empty() { + return; + } + + // Inline delete directive + if is_delete_directive(line) { + return; + } + + // Closing brace + if line == "}" { + if stack.is_empty() { + eprintln!("parser warning: unmatched closing brace, ignoring"); + return; + } + close_node(stack, top_level); + return; + } + + // Opening brace alone + if line == "{" { + let name = pending_name.take().unwrap_or_default(); + stack.push(ConfigNode::new(name)); + return; + } + + // Line contains `{` + if line.contains('{') { + let brace_idx = line.find('{').unwrap(); + let before = line[..brace_idx].trim(); + let node_name = if before.is_empty() { + pending_name.take().unwrap_or_default() + } else { + *pending_name = None; + clean_node_name(before) + }; + let node = ConfigNode::new(node_name); + let after = line[brace_idx + 1..].trim(); + if after.starts_with('}') { + // Empty inline node like `Node {}` + if let Some(parent) = stack.last_mut() { + parent.children.push(node); + } else { + top_level.push(node); + } + return; + } + stack.push(node); + // Process remaining content after `{` on the same line + if !after.is_empty() { + process_fragment(after, stack, top_level, pending_name); + } + return; + } + + // Check for trailing `}` on a key=value line or bare line + if line.contains('=') { + if pending_name.is_some() { + eprintln!("parser warning: discarding pending name before key=value line"); + *pending_name = None; + } + + // Check if line ends with `}` (inline close after key=value) + let (kv_part, has_close) = if let Some(stripped) = line.strip_suffix('}') { + (stripped, true) + } else { + (line, false) + }; + + let eq_idx = kv_part.find('=').unwrap(); + let key = kv_part[..eq_idx].trim().to_string(); + let value = kv_part[eq_idx + 1..].trim().to_string(); + if let Some(current) = stack.last_mut() { + current.values.push((key, value)); + } + + if has_close { + close_node(stack, top_level); + } + return; + } + + // Check if a bare token ends with `}` (edge case) + if let Some(stripped) = line.strip_suffix('}') { + let before = stripped.trim(); + if !before.is_empty() { + if pending_name.is_some() { + eprintln!("parser warning: discarding previous pending name"); + } + *pending_name = Some(clean_node_name(before)); + } + close_node(stack, top_level); + return; + } + + // Bare identifier (potential node name for next `{`) + if pending_name.is_some() { + eprintln!("parser warning: discarding previous pending name"); + } + *pending_name = Some(clean_node_name(line)); +} + +/// Parse raw KSP ConfigNode text into a list of top-level nodes. +/// +/// Handles comments, modifiers, delete directives, nested braces, +/// and auto-closes unclosed nodes at EOF with a warning. +/// +/// KSP ConfigNodeテキストをパースしてノードツリーを返す。 +pub fn parse_config_text(source: &str) -> Vec { + let mut top_level: Vec = Vec::new(); + let mut stack: Vec = Vec::new(); + let mut pending_name: Option = None; + + for raw_line in source.lines() { + let line = strip_comments(raw_line); + if line.is_empty() { + continue; + } + process_fragment(line, &mut stack, &mut top_level, &mut pending_name); + } + + // Auto-close unclosed nodes + if !stack.is_empty() { + eprintln!( + "parser warning: {} unclosed node(s) at EOF, auto-closing", + stack.len() + ); + while !stack.is_empty() { + close_node(&mut stack, &mut top_level); + } + } + + top_level +} + +// --------------------------------------------------------------------------- +// Helper parsers +// --------------------------------------------------------------------------- + +/// Parse a float from a string, returning `default` on `None` or parse failure. +fn parse_float(value: Option<&str>, default: f64) -> f64 { + match value { + Some(s) => s.trim().parse::().unwrap_or(default), + None => default, + } +} + +/// Parse a boolean from a string ("true" / "True" / "TRUE"), returning `default` +/// on `None` or unrecognized input. +fn parse_bool(value: Option<&str>, default: bool) -> bool { + match value { + Some(s) => s.trim().eq_ignore_ascii_case("true"), + None => default, + } +} + +/// Parse a single curve key line: `position value [inTangent [outTangent]]`. +/// +/// outTangent defaults to inTangent when omitted; both default to 0. +fn parse_curve_key(raw_value: &str) -> Option { + let parts: Vec<&str> = raw_value.split_whitespace().collect(); + if parts.len() < 2 { + return None; + } + let position = parts[0].parse::().ok()?; + let value = parts[1].parse::().ok()?; + let in_tangent = if parts.len() >= 3 { + parts[2].parse::().unwrap_or(0.0) + } else { + 0.0 + }; + let out_tangent = if parts.len() >= 4 { + parts[3].parse::().unwrap_or(in_tangent) + } else { + in_tangent + }; + Some(CurveKey { + position, + value, + in_tangent, + out_tangent, + }) +} + +/// Extract sorted curve keys from a node's `key` values. +fn extract_curve_keys(node: &ConfigNode) -> Vec { + let mut keys: Vec = node + .get_values("key") + .iter() + .filter_map(|raw| parse_curve_key(raw)) + .collect(); + keys.sort_by(|a, b| { + a.position + .partial_cmp(&b.position) + .unwrap_or(std::cmp::Ordering::Equal) + }); + keys +} + +// --------------------------------------------------------------------------- +// Body extraction +// --------------------------------------------------------------------------- + +/// Extract an `Atmosphere` from a body node, if present and enabled. +fn extract_atmosphere(body_node: &ConfigNode) -> Option { + let atmo_node = body_node.get_child("Atmosphere")?; + let enabled = parse_bool(atmo_node.get_value("enabled"), false); + if !enabled { + return None; + } + + let altitude = parse_float(atmo_node.get_value("altitude"), 0.0); + let adiabatic_index = parse_float(atmo_node.get_value("adiabaticIndex"), 1.4); + let molar_mass = parse_float(atmo_node.get_value("atmosphereMolarMass"), 0.02897); + let temperature_sea_level = parse_float(atmo_node.get_value("temperatureSeaLevel"), 0.0); + let pressure_sea_level = parse_float(atmo_node.get_value("staticPressureASL"), 0.0); + + let temperature_curve = atmo_node + .get_child("temperatureCurve") + .map(extract_curve_keys) + .unwrap_or_default(); + let pressure_curve = atmo_node + .get_child("pressureCurve") + .map(extract_curve_keys) + .unwrap_or_default(); + + Some(Atmosphere { + atmosphere_depth: altitude, + pressure_curve, + temperature_curve, + molar_mass, + adiabatic_index, + pressure_at_sea_level: pressure_sea_level, + temperature_at_sea_level: temperature_sea_level, + }) +} + +/// Extract `OrbitalElements` from a body node, if present. +fn extract_orbit(body_node: &ConfigNode) -> Option { + let orbit_node = body_node.get_child("Orbit")?; + Some(OrbitalElements { + semi_major_axis: parse_float(orbit_node.get_value("semiMajorAxis"), 0.0), + eccentricity: parse_float(orbit_node.get_value("eccentricity"), 0.0), + inclination: parse_float(orbit_node.get_value("inclination"), 0.0), + argument_of_periapsis: parse_float(orbit_node.get_value("argumentOfPeriapsis"), 0.0), + longitude_of_ascending_node: parse_float( + orbit_node.get_value("longitudeOfAscendingNode"), + 0.0, + ), + mean_anomaly_at_epoch: parse_float(orbit_node.get_value("meanAnomalyAtEpoch"), 0.0), + epoch: parse_float(orbit_node.get_value("epoch"), 0.0), + }) +} + +/// Check if an Ocean child node exists and has `ocean = True`. +fn extract_has_ocean(body_node: &ConfigNode) -> bool { + match body_node.get_child("Ocean") { + Some(ocean_node) => parse_bool(ocean_node.get_value("ocean"), false), + None => false, + } +} + +/// Resolve display name: prefer Properties/displayName unless it starts with +/// `#LOC_`, in which case fall back to source_filename then body name. +fn resolve_display_name( + properties: Option<&ConfigNode>, + body_name: &str, + source_filename: &str, +) -> String { + let fallback = || -> String { + if source_filename.is_empty() { + body_name.to_string() + } else { + source_filename.to_string() + } + }; + + let Some(props) = properties else { + return fallback(); + }; + + match props.get_value("displayName") { + Some(dn) if !dn.starts_with("#LOC_") => dn.to_string(), + _ => fallback(), + } +} + +/// Extract a single `CelestialBody` from a Body ConfigNode. +fn extract_body(body_node: &ConfigNode, source_filename: &str) -> Option { + let name = body_node.get_value("name")?; + let properties = body_node.get_child("Properties"); + + let radius = parse_float(properties.and_then(|p| p.get_value("radius")), 600_000.0); + let gee_asl = parse_float(properties.and_then(|p| p.get_value("geeASL")), 1.0); + let rotational_period = + parse_float(properties.and_then(|p| p.get_value("rotationPeriod")), 0.0); + let display_name = resolve_display_name(properties, name, source_filename); + let is_home_world = parse_bool(properties.and_then(|p| p.get_value("isHomeWorld")), false); + + let reference_body_name = body_node + .get_child("Orbit") + .and_then(|o| o.get_value("referenceBody")) + .map(|s| s.trim().to_string()) + .unwrap_or_default(); + + let atmosphere = extract_atmosphere(body_node); + let orbit = extract_orbit(body_node); + let has_ocean = extract_has_ocean(body_node); + + let mut body = CelestialBody::new( + name.to_string(), + radius, + gee_asl, + has_ocean, + atmosphere, + orbit, + rotational_period, + display_name, + ); + body.is_home_world = is_home_world; + body.reference_body_name = reference_body_name; + + Some(body) +} + +/// Recursively walk nodes looking for `Body` children and extract them. +fn walk_bodies(nodes: &[ConfigNode], source_filename: &str, bodies: &mut Vec) { + for node in nodes { + if node.name == "Body" { + if let Some(body) = extract_body(node, source_filename) { + bodies.push(body); + } + } else { + walk_bodies(&node.children, source_filename, bodies); + } + } +} + +/// Parse KSP ConfigNode source text and extract all `CelestialBody` instances. +/// +/// This is the main entry point for the parser. +/// +/// メインエントリーポイント。天体を抽出して返す。 +pub fn parse_bodies(source: &str) -> Vec { + parse_bodies_with_filename(source, "") +} + +/// Parse bodies with a source filename used as display name fallback. +/// +/// ファイル名付きでパースする。 +pub fn parse_bodies_with_filename(source: &str, filename: &str) -> Vec { + let top_nodes = parse_config_text(source); + let mut bodies = Vec::new(); + walk_bodies(&top_nodes, filename, &mut bodies); + bodies +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + // ----------------------------------------------------------------------- + // ConfigNode low-level tests + // ----------------------------------------------------------------------- + + #[test] + fn test_empty_input() { + assert!(parse_config_text("").is_empty()); + } + + #[test] + fn test_simple_key_value() { + let nodes = parse_config_text("Node\n{\n name = Kerbin\n radius = 600000\n}"); + assert_eq!(nodes.len(), 1); + assert_eq!(nodes[0].name, "Node"); + assert_eq!(nodes[0].get_value("name"), Some("Kerbin")); + assert_eq!(nodes[0].get_value("radius"), Some("600000")); + } + + #[test] + fn test_nested_nodes() { + let nodes = parse_config_text( + "Outer\n{\n key = val\n Inner\n {\n key = val2\n }\n}", + ); + assert_eq!(nodes.len(), 1); + assert_eq!(nodes[0].children.len(), 1); + assert_eq!(nodes[0].children[0].name, "Inner"); + } + + #[test] + fn test_comment_removal() { + let nodes = parse_config_text("Node\n{\n key = val // comment\n}"); + assert_eq!(nodes[0].get_value("key"), Some("val")); + } + + #[test] + fn test_modifier_stripping() { + for prefix in ["@", "!", "+", "-", "%"] { + let source = format!("{}Node\n{{\n key = val\n}}", prefix); + let nodes = parse_config_text(&source); + assert_eq!(nodes[0].name, "Node", "failed for prefix {}", prefix); + } + } + + #[test] + fn test_delete_directive_skipped() { + let nodes = parse_config_text("!Body[Kerbin]{}\nNode\n{\n key = val\n}"); + assert!(nodes.iter().any(|n| n.name == "Node")); + // The delete directive should not produce a node + assert!(!nodes.iter().any(|n| n.name == "Body")); + } + + #[test] + fn test_unclosed_brace_no_crash() { + let result = parse_config_text("Node\n{\n key = val\n"); + assert!(!result.is_empty()); + assert_eq!(result[0].get_value("key"), Some("val")); + } + + #[test] + fn test_values_with_spaces() { + let nodes = parse_config_text("Node\n{\n name = North Pole\n}"); + assert_eq!(nodes[0].get_value("name"), Some("North Pole")); + } + + #[test] + fn test_inline_node_opening() { + // Node name on the same line as the opening brace + let nodes = parse_config_text("Properties {\n radius = 100000\n}"); + assert_eq!(nodes.len(), 1); + assert_eq!(nodes[0].name, "Properties"); + assert_eq!(nodes[0].get_value("radius"), Some("100000")); + } + + #[test] + fn test_mm_annotation_stripped() { + let nodes = parse_config_text("@Kopernicus:AFTER[Kopernicus]\n{\n key = val\n}"); + assert_eq!(nodes[0].name, "Kopernicus"); + } + + #[test] + fn test_get_values_multiple() { + let nodes = + parse_config_text("Curve\n{\n key = 0 100\n key = 1 200\n key = 2 300\n}"); + let vals = nodes[0].get_values("key"); + assert_eq!(vals.len(), 3); + } + + #[test] + fn test_get_child_not_found() { + let nodes = parse_config_text("Node\n{\n key = val\n}"); + assert!(nodes[0].get_child("Missing").is_none()); + } + + // ----------------------------------------------------------------------- + // Curve key parsing + // ----------------------------------------------------------------------- + + #[test] + fn test_curve_key_full() { + let ck = parse_curve_key("0 101.325 -0.005 -0.01").unwrap(); + assert!((ck.position - 0.0).abs() < 1e-6); + assert!((ck.value - 101.325).abs() < 1e-6); + assert!((ck.in_tangent - (-0.005)).abs() < 1e-6); + assert!((ck.out_tangent - (-0.01)).abs() < 1e-6); + } + + #[test] + fn test_curve_key_out_tangent_defaults_to_in() { + let ck = parse_curve_key("0 101.325 -0.005").unwrap(); + assert!((ck.out_tangent - (-0.005)).abs() < 1e-6); + } + + #[test] + fn test_curve_key_tangents_default_to_zero() { + let ck = parse_curve_key("0 101.325").unwrap(); + assert!((ck.in_tangent - 0.0).abs() < 1e-6); + assert!((ck.out_tangent - 0.0).abs() < 1e-6); + } + + #[test] + fn test_curve_key_too_few_parts() { + assert!(parse_curve_key("0").is_none()); + assert!(parse_curve_key("").is_none()); + } + + // ----------------------------------------------------------------------- + // Body extraction tests + // ----------------------------------------------------------------------- + + #[test] + fn test_parse_simple_body() { + let cfg = r#" + @Kopernicus:AFTER[Kopernicus] + { + Body + { + name = Kerbin + Properties + { + radius = 600000 + geeASL = 1.0 + rotationPeriod = 21549.425 + isHomeWorld = True + } + } + } + "#; + let bodies = parse_bodies(cfg); + assert_eq!(bodies.len(), 1); + assert_eq!(bodies[0].name, "Kerbin"); + assert!((bodies[0].radius - 600_000.0).abs() < 1.0); + assert!((bodies[0].gee_asl - 1.0).abs() < 0.001); + assert!(bodies[0].is_home_world); + } + + #[test] + fn test_parse_sanctar_cfg() { + let cfg = std::fs::read_to_string("../../../sample_configs/Sanctar.cfg").unwrap(); + let bodies = parse_bodies(&cfg); + assert!(!bodies.is_empty()); + let body = &bodies[0]; + + // Basic properties + assert!((body.radius - 670_000.0).abs() < 1.0); + assert!((body.gee_asl - 1.1).abs() < 0.001); + + // Atmosphere + assert!(body.atmosphere.is_some()); + let atmo = body.atmosphere.as_ref().unwrap(); + assert!((atmo.atmosphere_depth - 72_000.0).abs() < 1.0); + assert_eq!(atmo.pressure_curve.len(), 26); + assert_eq!(atmo.temperature_curve.len(), 26); + assert!((atmo.pressure_at_sea_level - 110.444).abs() / 110.444 < 0.001); + assert!((atmo.temperature_at_sea_level - 281.0).abs() < 0.1); + assert!((atmo.molar_mass - 0.02897).abs() < 0.0001); + assert!((atmo.adiabatic_index - 1.4).abs() < 0.001); + + // Orbit + assert!(body.orbit.is_some()); + let orbit = body.orbit.as_ref().unwrap(); + assert!((orbit.semi_major_axis - 13_116_000_574.0).abs() / 13_116_000_574.0 < 0.001); + assert!((orbit.eccentricity - 0.0254528).abs() < 0.001); + assert!((orbit.inclination - 1.38).abs() < 0.01); + + // Other + assert!(body.is_home_world); + assert_eq!(body.reference_body_name, "Sun"); + assert!(body.has_ocean); + } + + #[test] + fn test_curve_key_out_tangent_defaults_to_in_body() { + let cfg = r#" + Body + { + name = Test + Properties { radius = 100000 } + Atmosphere + { + enabled = True + altitude = 50000 + adiabaticIndex = 1.4 + atmosphereMolarMass = 0.029 + temperatureSeaLevel = 288 + staticPressureASL = 101.325 + pressureCurve + { + key = 0 101.325 -0.005 + } + temperatureCurve + { + key = 0 288 0 0 + } + } + } + "#; + let bodies = parse_bodies(cfg); + let atmo = bodies[0].atmosphere.as_ref().unwrap(); + assert!((atmo.pressure_curve[0].out_tangent - (-0.005)).abs() < 1e-6); + } + + #[test] + fn test_atmosphere_disabled_is_none() { + let cfg = "Body\n{\n name = Test\n Properties\n {\n radius = 100000\n geeASL = 1.0\n }\n Atmosphere\n {\n enabled = False\n altitude = 70000\n }\n}"; + let bodies = parse_bodies(cfg); + assert!(bodies[0].atmosphere.is_none()); + } + + #[test] + fn test_no_orbit_is_none() { + let cfg = "Body\n{\n name = Test\n Properties\n {\n radius = 100000\n geeASL = 1.0\n }\n}"; + let bodies = parse_bodies(cfg); + assert!(bodies[0].orbit.is_none()); + } + + #[test] + fn test_reference_body_from_orbit() { + let cfg = "Body\n{\n name = Test\n Properties\n {\n radius = 100000\n geeASL = 1.0\n }\n Orbit\n {\n semiMajorAxis = 1000000\n referenceBody = Sun\n }\n}"; + let bodies = parse_bodies(cfg); + assert_eq!(bodies[0].reference_body_name, "Sun"); + } + + #[test] + fn test_multiple_bodies() { + let cfg = "Body\n{\n name = A\n Properties { radius = 100000\n geeASL = 1.0 }\n}\nBody\n{\n name = B\n Properties { radius = 200000\n geeASL = 0.8 }\n}"; + let bodies = parse_bodies(cfg); + assert_eq!(bodies.len(), 2); + } + + #[test] + fn test_display_name_loc_fallback() { + let cfg = r#" + Body + { + name = Kerbin + Properties + { + displayName = #LOC_Kerbin + radius = 600000 + } + } + "#; + // Without filename, falls back to body name + let bodies = parse_bodies(cfg); + assert_eq!(bodies[0].display_name, "Kerbin"); + + // With filename, falls back to filename + let bodies = parse_bodies_with_filename(cfg, "MyPlanet"); + assert_eq!(bodies[0].display_name, "MyPlanet"); + } + + #[test] + fn test_display_name_real_value() { + let cfg = r#" + Body + { + name = Kerbin + Properties + { + displayName = Earth + radius = 600000 + } + } + "#; + let bodies = parse_bodies(cfg); + assert_eq!(bodies[0].display_name, "Earth"); + } + + #[test] + fn test_no_properties_defaults() { + let cfg = "Body\n{\n name = Test\n}"; + let bodies = parse_bodies(cfg); + assert_eq!(bodies.len(), 1); + assert!((bodies[0].radius - 600_000.0).abs() < 1.0); + assert!((bodies[0].gee_asl - 1.0).abs() < 0.001); + } + + #[test] + fn test_body_without_name_skipped() { + let cfg = "Body\n{\n Properties { radius = 100000 }\n}"; + let bodies = parse_bodies(cfg); + assert!(bodies.is_empty()); + } + + #[test] + fn test_unmatched_closing_brace() { + // Should not crash + let nodes = parse_config_text("}\nNode\n{\n key = val\n}"); + assert_eq!(nodes.len(), 1); + assert_eq!(nodes[0].name, "Node"); + } + + #[test] + fn test_delete_directive_with_spaces() { + let nodes = parse_config_text("!Body[Kerbin]{ }\nNode\n{\n key = val\n}"); + assert!(nodes.iter().any(|n| n.name == "Node")); + assert!(!nodes.iter().any(|n| n.name == "Body")); + } +} diff --git a/src-tauri/crates/kopdeltav/src/system.rs b/src-tauri/crates/kopdeltav/src/system.rs new file mode 100644 index 0000000..1226c12 --- /dev/null +++ b/src-tauri/crates/kopdeltav/src/system.rs @@ -0,0 +1,654 @@ +//! Celestial system tree construction and GameData config scanning. +//! +//! Builds parent/children relationships from a flat list of parsed bodies, +//! identifies root star and home world, computes SOI, and provides +//! transfer-DV sorting and GameData directory scanning. +//! +//! 天体ツリーの構築と GameData/ の .cfg ファイルスキャンを提供する。 + +use std::collections::HashMap; +use std::path::Path; + +use crate::calculator::calculate_hohmann; +use crate::models::CelestialBody; +use crate::parser::parse_bodies_with_filename; + +// --------------------------------------------------------------------------- +// CelestialSystem +// --------------------------------------------------------------------------- + +/// A fully linked tree of celestial bodies parsed from Kopernicus configs. +/// +/// Kopernicus 設定からパースされた天体の完全なツリー構造。 +pub struct CelestialSystem { + /// Internal name of the root star (top of the hierarchy). + pub root_name: String, + /// Flat name -> body lookup for O(1) access. + pub bodies: HashMap, + /// Internal name of the home world body. + pub home_world_name: String, +} + +// --------------------------------------------------------------------------- +// Barycenter detection +// --------------------------------------------------------------------------- + +/// Heuristic: detect if a body is likely a system barycenter. +/// +/// 天体がバリセンタ(重心)かどうかをヒューリスティクスで判定する。 +/// +/// A body is treated as a barycenter when it has children and its +/// radius is smaller than the smallest child's radius. +/// +/// # Arguments +/// * `body` - The body to check. +/// * `bodies` - All bodies in the system, for child lookup. +/// +/// # Returns +/// `true` if the body is likely a barycenter. +pub fn is_barycenter(body: &CelestialBody, bodies: &HashMap) -> bool { + if body.children_names.is_empty() { + return false; + } + let min_child_radius = body + .children_names + .iter() + .filter_map(|name| bodies.get(name)) + .map(|c| c.radius) + .fold(f64::INFINITY, f64::min); + + if min_child_radius == f64::INFINITY { + // No children resolved in the map + return false; + } + body.radius < min_child_radius +} + +// --------------------------------------------------------------------------- +// Body completeness scoring (deduplication) +// --------------------------------------------------------------------------- + +/// Score how complete a body's data is, for deduplication priority. +/// +/// 天体データの完全度をスコア化する(重複排除の優先度判定用)。 +fn body_completeness(body: &CelestialBody) -> i32 { + let mut score = 0; + if body.is_home_world { + score += 100; + } + if body.orbit.is_some() { + score += 10; + } + if !body.reference_body_name.is_empty() { + score += 5; + } + if body.atmosphere.is_some() { + score += 3; + } + if body.radius > 0.0 { + score += 1; + } + score +} + +// --------------------------------------------------------------------------- +// Tree construction +// --------------------------------------------------------------------------- + +/// Build a parent/children tree from a flat list of bodies. +/// +/// フラットな天体リストから親子関係ツリーを構築する。 +/// +/// Steps: +/// 1. Deduplicate by name (prefer more complete: is_home_world > has orbit > has reference_body_name). +/// 2. Link parent_name / children_names using reference_body_name. +/// 3. Find root (no orbit, no reference_body_name, has children). +/// 4. Find home world (is_home_world=true; fallback: Kerbin-like > has ocean > has atmosphere). +/// 5. Compute SOI where soi == 0: `soi = a * (mu_body / mu_parent)^0.4`. +/// +/// # Arguments +/// * `bodies` - Flat list of `CelestialBody` objects (e.g. from `parse_bodies`). +/// +/// # Returns +/// A fully linked `CelestialSystem`, or an error if the list is empty or no root found. +/// +/// # Errors +/// Returns `Err` if `bodies` is empty. +pub fn build_tree(bodies: Vec) -> Result { + if bodies.is_empty() { + return Err("Cannot build tree from an empty body list".to_string()); + } + + // Step 1: deduplicate by name, preferring the most complete version. + let mut index: HashMap = HashMap::new(); + for body in bodies { + let name = body.name.clone(); + if let Some(existing) = index.get(&name) { + if body_completeness(&body) > body_completeness(existing) { + index.insert(name, body); + } + } else { + index.insert(name, body); + } + } + + // Reset parent/children to avoid stale links. + for body in index.values_mut() { + body.parent_name = None; + body.children_names.clear(); + } + + // Step 2: link parent/children using reference_body_name. + // Collect linkage info first to satisfy borrow checker. + let links: Vec<(String, String)> = index + .values() + .filter(|b| !b.reference_body_name.is_empty()) + .map(|b| (b.name.clone(), b.reference_body_name.clone())) + .collect(); + + for (child_name, parent_name) in &links { + if !index.contains_key(parent_name) { + eprintln!( + "system warning: body '{}' references unknown referenceBody '{}'", + child_name, parent_name + ); + continue; + } + // Set parent_name on child + if let Some(child) = index.get_mut(child_name) { + child.parent_name = Some(parent_name.clone()); + } + // Add child to parent's children_names + if let Some(parent) = index.get_mut(parent_name) { + if !parent.children_names.contains(child_name) { + parent.children_names.push(child_name.clone()); + } + } + } + + // Step 3: find root. + // Primary: body with no orbit AND no reference_body_name AND has children. + let mut root_name: Option = None; + + let candidates: Vec = index + .values() + .filter(|b| b.orbit.is_none() && b.reference_body_name.is_empty()) + .map(|b| b.name.clone()) + .collect(); + + if !candidates.is_empty() { + let with_children: Vec<&String> = candidates + .iter() + .filter(|name| { + index + .get(name.as_str()) + .is_some_and(|b| !b.children_names.is_empty()) + }) + .collect(); + root_name = Some(if !with_children.is_empty() { + with_children[0].clone() + } else { + candidates[0].clone() + }); + } + + // Fallback: body with no parent link after tree construction, that has children. + if root_name.is_none() { + let orphans: Vec = index + .values() + .filter(|b| b.parent_name.is_none() && !b.children_names.is_empty()) + .map(|b| b.name.clone()) + .collect(); + if !orphans.is_empty() { + root_name = Some(orphans[0].clone()); + } + } + + // Last resort: first body in the map + let root_name = root_name.unwrap_or_else(|| { + let first = index.keys().next().expect("index is non-empty"); + eprintln!( + "system warning: cannot determine root; defaulting to '{}'", + first + ); + first.clone() + }); + + // Step 4: home world. + let mut home_world_name: Option = None; + for body in index.values() { + if body.is_home_world { + home_world_name = Some(body.name.clone()); + break; + } + } + + if home_world_name.is_none() { + // Fallback: pick the best candidate using a heuristic score. + let best = index + .values() + .max_by_key(|b| { + let mut score: i32 = 0; + if b.name.trim().eq_ignore_ascii_case("kerbin") { + score += 100; + } + if b.has_ocean { + score += 50; + } + if b.atmosphere.is_some() { + score += 30; + } + if b.rotational_period > 0.0 { + score += 10; + } + if b.orbit.is_some() { + score += 5; + } + if b.parent_name.is_some() { + score += 2; + } + score + }) + .expect("index is non-empty"); + + home_world_name = Some(best.name.clone()); + eprintln!( + "system warning: no body declares isHomeWorld=true; falling back to '{}' as home world", + best.name + ); + + // Mark it as home world + if let Some(body) = index.get_mut(&home_world_name.clone().unwrap()) { + body.is_home_world = true; + } + } + + let home_world_name = home_world_name.expect("home world resolved above"); + + // Step 5: compute SOI where soi == 0. + // Collect (name, soi) pairs to assign, to satisfy borrow checker. + let soi_updates: Vec<(String, f64)> = index + .values() + .filter_map(|body| { + if body.soi != 0.0 || body.parent_name.is_none() || body.orbit.is_none() { + return None; + } + let parent_name = body.parent_name.as_ref()?; + let parent = index.get(parent_name)?; + let a = body.orbit.as_ref()?.semi_major_axis; + let mu_body = body.mu; + let mu_parent = parent.mu; + if mu_parent > 0.0 && a > 0.0 { + let soi = a * (mu_body / mu_parent).powf(0.4); + Some((body.name.clone(), soi)) + } else { + None + } + }) + .collect(); + + for (name, soi) in soi_updates { + if let Some(body) = index.get_mut(&name) { + body.soi = soi; + } + } + + Ok(CelestialSystem { + root_name, + bodies: index, + home_world_name, + }) +} + +// --------------------------------------------------------------------------- +// Transfer DV sorting +// --------------------------------------------------------------------------- + +/// Sort sibling bodies by Hohmann transfer DV from origin, ascending. +/// +/// origin からのホーマン遷移 DV 昇順でターゲット天体をソートする。 +/// +/// The origin must orbit a parent body. Siblings of origin (other children of the +/// same parent) are sorted by their Hohmann transfer DV. +/// +/// # Arguments +/// * `origin_name` - Name of the departure body. +/// * `bodies` - All bodies in the system. +/// +/// # Returns +/// List of `(target_name, total_dv)` tuples sorted ascending by total_dv. +/// Bodies that cannot be evaluated are omitted. +pub fn sort_by_transfer_dv( + origin_name: &str, + bodies: &HashMap, +) -> Vec<(String, f64)> { + let origin = match bodies.get(origin_name) { + Some(b) => b, + None => return Vec::new(), + }; + + let origin_orbit = match &origin.orbit { + Some(o) => o, + None => return Vec::new(), + }; + + let parent_name = match &origin.parent_name { + Some(n) => n.clone(), + None => return Vec::new(), + }; + + let parent = match bodies.get(&parent_name) { + Some(p) => p, + None => return Vec::new(), + }; + + // Collect siblings (other children of the same parent) + let siblings: Vec = parent + .children_names + .iter() + .filter(|n| n.as_str() != origin_name) + .cloned() + .collect(); + + let origin_sma = origin_orbit.semi_major_axis; + + let mut results: Vec<(String, f64)> = Vec::new(); + for sibling_name in &siblings { + let sibling = match bodies.get(sibling_name) { + Some(s) => s, + None => continue, + }; + let target_sma = match &sibling.orbit { + Some(o) => o.semi_major_axis, + None => continue, + }; + + let parking_altitude = origin_sma - parent.radius; + if parking_altitude < 0.0 { + continue; + } + + let hohmann = calculate_hohmann(parent, parking_altitude, target_sma); + results.push((sibling_name.clone(), hohmann.total_dv)); + } + + results.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap_or(std::cmp::Ordering::Equal)); + results +} + +// --------------------------------------------------------------------------- +// GameData config scanner +// --------------------------------------------------------------------------- + +/// Recursively scan a GameData directory for Kopernicus `.cfg` files and build a tree. +/// +/// GameData/ ディレクトリを再帰スキャンし、Kopernicus 設定から天体ツリーを構築する。 +/// +/// All `.cfg` files are read. Directories whose lowercase names appear in +/// `exclude_dirs` are skipped entirely (default: `["kopernicus"]`). +/// +/// # Arguments +/// * `gamedata_path` - Path to the `GameData/` directory. +/// * `exclude_dirs` - Directory names (lowercase) to skip during scan. +/// +/// # Returns +/// A `CelestialSystem` built from all bodies found, or an error. +/// +/// # Errors +/// Returns `Err` if the path is not a directory, no bodies are found, or tree construction fails. +pub fn scan_configs( + gamedata_path: &str, + exclude_dirs: &[String], +) -> Result { + let path = Path::new(gamedata_path); + if !path.is_dir() { + return Err(format!( + "gamedata_path is not an existing directory: {}", + gamedata_path + )); + } + + let cfg_files = iter_cfgs(path, exclude_dirs); + let mut all_bodies: Vec = Vec::new(); + + for cfg_path in &cfg_files { + let source = match std::fs::read_to_string(cfg_path) { + Ok(s) => s, + Err(e) => { + eprintln!("system warning: cannot read '{}': {}", cfg_path.display(), e); + continue; + } + }; + + let filename = cfg_path + .file_stem() + .and_then(|s| s.to_str()) + .unwrap_or(""); + let bodies = parse_bodies_with_filename(&source, filename); + if bodies.is_empty() { + continue; + } + + all_bodies.extend(bodies); + } + + if all_bodies.is_empty() { + return Err(format!( + "No celestial bodies found under '{}'", + gamedata_path + )); + } + + build_tree(all_bodies) +} + +/// Recursively collect .cfg files under a directory, skipping excluded dirs. +/// +/// ディレクトリ以下の .cfg ファイルを再帰的に収集する。 +fn iter_cfgs(directory: &Path, exclude_dirs: &[String]) -> Vec { + let mut results = Vec::new(); + + let entries = match std::fs::read_dir(directory) { + Ok(e) => e, + Err(e) => { + eprintln!( + "system warning: cannot list directory '{}': {}", + directory.display(), + e + ); + return results; + } + }; + + let mut sorted_entries: Vec = entries + .filter_map(|e| e.ok()) + .map(|e| e.path()) + .collect(); + sorted_entries.sort(); + + for entry in &sorted_entries { + if entry.is_dir() { + let dir_name = entry + .file_name() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_lowercase(); + if exclude_dirs.iter().any(|ex| ex.to_lowercase() == dir_name) { + continue; + } + results.extend(iter_cfgs(entry, exclude_dirs)); + } else if entry.is_file() { + let ext = entry + .extension() + .and_then(|s| s.to_str()) + .unwrap_or("") + .to_lowercase(); + if ext == "cfg" { + results.push(entry.clone()); + } + } + } + + results +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + use crate::models::*; + + fn make_star() -> CelestialBody { + CelestialBody::new( + "Sun".to_string(), + 261_600_000.0, + 1.75, + false, + None, + None, + 0.0, + "Sun".to_string(), + ) + } + + fn make_planet(name: &str, ref_body: &str) -> CelestialBody { + let mut body = CelestialBody::new( + name.to_string(), + 600_000.0, + 1.0, + true, + None, + Some(OrbitalElements { + semi_major_axis: 13_599_840_256.0, + eccentricity: 0.0, + inclination: 0.0, + argument_of_periapsis: 0.0, + longitude_of_ascending_node: 0.0, + mean_anomaly_at_epoch: 0.0, + epoch: 0.0, + }), + 21549.0, + name.to_string(), + ); + body.reference_body_name = ref_body.to_string(); + body + } + + #[test] + fn test_build_tree_basic() { + let star = make_star(); + let mut planet = make_planet("Kerbin", "Sun"); + planet.is_home_world = true; + let system = build_tree(vec![star, planet]).unwrap(); + assert_eq!(system.root_name, "Sun"); + assert_eq!(system.home_world_name, "Kerbin"); + let kerbin = &system.bodies["Kerbin"]; + assert_eq!(kerbin.parent_name, Some("Sun".to_string())); + let sun = &system.bodies["Sun"]; + assert!(sun.children_names.contains(&"Kerbin".to_string())); + } + + #[test] + fn test_build_tree_empty_fails() { + assert!(build_tree(vec![]).is_err()); + } + + #[test] + fn test_build_tree_soi_computation() { + let star = make_star(); + let mut planet = make_planet("Kerbin", "Sun"); + planet.is_home_world = true; + let system = build_tree(vec![star, planet]).unwrap(); + let kerbin = &system.bodies["Kerbin"]; + assert!(kerbin.soi > 0.0); + } + + #[test] + fn test_build_tree_dedup() { + let star = make_star(); + let p1 = make_planet("Kerbin", "Sun"); + let mut p2 = make_planet("Kerbin", "Sun"); + p2.is_home_world = true; + let system = build_tree(vec![star, p1, p2]).unwrap(); + // p2 should win (is_home_world = true) + assert_eq!(system.home_world_name, "Kerbin"); + } + + #[test] + fn test_is_barycenter() { + let mut parent = make_star(); + parent.radius = 100.0; // tiny + parent.name = "Tiny".to_string(); + parent.children_names = vec!["Big".to_string()]; + let mut child = make_planet("Big", "Tiny"); + child.radius = 600_000.0; + let mut bodies = HashMap::new(); + bodies.insert("Tiny".to_string(), parent); + bodies.insert("Big".to_string(), child); + assert!(is_barycenter(&bodies["Tiny"], &bodies)); + assert!(!is_barycenter(&bodies["Big"], &bodies)); + } + + #[test] + fn test_home_world_fallback() { + // No body has is_home_world = true; the one with ocean/atmosphere should win. + let star = make_star(); + let mut planet = make_planet("Kerbin", "Sun"); + // Don't set is_home_world; the heuristic should still pick Kerbin by name. + planet.is_home_world = false; + let system = build_tree(vec![star, planet]).unwrap(); + assert_eq!(system.home_world_name, "Kerbin"); + assert!(system.bodies["Kerbin"].is_home_world); + } + + #[test] + fn test_sort_by_transfer_dv_basic() { + let mut star = make_star(); + star.children_names = vec!["Inner".to_string(), "Outer".to_string()]; + + let mut inner = make_planet("Inner", "Sun"); + inner.is_home_world = true; + inner.orbit = Some(OrbitalElements { + semi_major_axis: 10_000_000_000.0, + eccentricity: 0.0, + inclination: 0.0, + argument_of_periapsis: 0.0, + longitude_of_ascending_node: 0.0, + mean_anomaly_at_epoch: 0.0, + epoch: 0.0, + }); + inner.parent_name = Some("Sun".to_string()); + + let mut outer = make_planet("Outer", "Sun"); + outer.orbit = Some(OrbitalElements { + semi_major_axis: 20_000_000_000.0, + eccentricity: 0.0, + inclination: 0.0, + argument_of_periapsis: 0.0, + longitude_of_ascending_node: 0.0, + mean_anomaly_at_epoch: 0.0, + epoch: 0.0, + }); + outer.parent_name = Some("Sun".to_string()); + + let mut bodies = HashMap::new(); + bodies.insert("Sun".to_string(), star); + bodies.insert("Inner".to_string(), inner); + bodies.insert("Outer".to_string(), outer); + + let result = sort_by_transfer_dv("Inner", &bodies); + assert_eq!(result.len(), 1); + assert_eq!(result[0].0, "Outer"); + assert!(result[0].1 > 0.0); + } + + #[test] + fn test_sort_by_transfer_dv_no_orbit() { + let bodies: HashMap = HashMap::new(); + let result = sort_by_transfer_dv("Missing", &bodies); + assert!(result.is_empty()); + } +} diff --git a/src-tauri/src/commands.rs b/src-tauri/src/commands.rs new file mode 100644 index 0000000..4b686d6 --- /dev/null +++ b/src-tauri/src/commands.rs @@ -0,0 +1,693 @@ +//! Tauri command handlers that bridge the frontend to the kopdeltav crate. +//! +//! Each command locks the shared `ManagedState`, delegates to kopdeltav functions, +//! and returns `Result` for Tauri IPC compatibility. +//! +//! Tauri コマンドハンドラ。フロントエンドと kopdeltav クレートの橋渡し。 + +use serde::Serialize; +use std::collections::HashMap; + +use kopdeltav::calculator::{ + calculate_hohmann, calculate_launch, calculate_tsiolkovsky, circular_velocity, compute_route, + density_at_altitude, escape_dv_from_low_orbit, geostationary_altitude, geostationary_dv, + landing_dv, low_orbit_altitude, surface_density, +}; +use kopdeltav::models::{hermite_interp, CelestialBody}; +use kopdeltav::parser::parse_bodies; +use kopdeltav::system::{build_tree, scan_configs, sort_by_transfer_dv}; + +use crate::state::ManagedState; + +// --------------------------------------------------------------------------- +// Response types +// --------------------------------------------------------------------------- + +/// Summary representation of a celestial body for list views. +#[derive(Serialize)] +pub struct BodySummary { + pub name: String, + pub display_name: String, + pub radius: f64, + pub gee_asl: f64, + pub has_atmosphere: bool, + pub has_ocean: bool, +} + +/// Orbital elements response matching TypeScript interfaces. +#[derive(Serialize)] +pub struct OrbitResponse { + pub semi_major_axis: f64, + pub eccentricity: f64, + pub inclination: f64, + pub argument_of_periapsis: f64, + pub longitude_of_ascending_node: f64, + pub mean_anomaly_at_epoch: f64, + pub epoch: f64, +} + +/// Atmosphere summary response. +#[derive(Serialize)] +pub struct AtmosphereResponse { + pub atmosphere_depth: f64, + pub pressure_at_sea_level: f64, + pub temperature_at_sea_level: f64, + pub molar_mass: f64, + pub adiabatic_index: f64, + pub sea_level_density: Option, +} + +/// Detailed celestial body response. +#[derive(Serialize)] +pub struct BodyDetail { + pub name: String, + pub display_name: String, + pub radius: f64, + pub gee_asl: f64, + pub mu: f64, + pub has_ocean: bool, + pub rotational_period: f64, + pub soi: f64, + pub atmosphere: Option, + pub orbit: Option, +} + +/// Launch-to-orbit calculation response. +#[derive(Serialize)] +pub struct LaunchResponse { + pub orbital_velocity: f64, + pub gravity_loss: f64, + pub drag_loss: f64, + pub total_ideal: f64, + pub total_rocket: f64, + pub jet_savings: f64, + pub total_with_jets: f64, +} + +/// Hohmann transfer calculation response. +#[derive(Serialize)] +pub struct HohmannResponse { + pub departure_dv: f64, + pub arrival_dv: f64, + pub total_dv: f64, + pub transfer_time: f64, + pub inward: bool, +} + +/// Tsiolkovsky equation response. +#[derive(Serialize)] +pub struct TsiolkovskyResponse { + pub mass_ratio: f64, + pub fuel_fraction: f64, + pub dry_mass: f64, + pub fuel_mass: f64, +} + +/// Config upload/scan result. +#[derive(Serialize)] +pub struct UploadResponse { + pub bodies_added: Vec, + pub count: usize, +} + +/// A node in the celestial body tree for hierarchical display. +#[derive(Serialize)] +pub struct BodyTreeNode { + pub name: String, + pub display_name: String, + pub children: Vec, +} + +/// Full celestial system response. +#[derive(Serialize)] +pub struct SystemResponse { + pub root: BodySummary, + pub home_world: BodyDetail, + pub body_count: usize, + pub tree: Vec, +} + +/// A destination body with its transfer delta-V. +#[derive(Serialize)] +pub struct DestinationEntry { + pub body: BodySummary, + pub transfer_dv: f64, +} + +/// A single step in a delta-V route. +#[derive(Serialize)] +pub struct DvStepResponse { + pub label: String, + pub dv: f64, + pub cumulative: f64, + pub note: String, +} + +/// Full route response. +#[derive(Serialize)] +pub struct RouteResponse { + pub steps: Vec, + pub total_powered: f64, + pub total_aerobrake: Option, +} + +/// Atmosphere profile sampled at regular altitude intervals. +#[derive(Serialize)] +pub struct AtmoProfileResponse { + pub altitude: Vec, + pub pressure: Vec, + pub temperature: Vec, + pub density: Vec, +} + +// --------------------------------------------------------------------------- +// Conversion helpers +// --------------------------------------------------------------------------- + +/// Convert a `CelestialBody` to a `BodySummary`. +fn body_to_summary(body: &CelestialBody) -> BodySummary { + BodySummary { + name: body.name.clone(), + display_name: body.display_name.clone(), + radius: body.radius, + gee_asl: body.gee_asl, + has_atmosphere: body.has_atmosphere(), + has_ocean: body.has_ocean, + } +} + +/// Convert a `CelestialBody` to a `BodyDetail`. +fn body_to_detail(body: &CelestialBody) -> BodyDetail { + let atmosphere = body.atmosphere.as_ref().map(|atmo| { + let sea_level_density = surface_density(body); + AtmosphereResponse { + atmosphere_depth: atmo.atmosphere_depth, + pressure_at_sea_level: atmo.pressure_at_sea_level, + temperature_at_sea_level: atmo.temperature_at_sea_level, + molar_mass: atmo.molar_mass, + adiabatic_index: atmo.adiabatic_index, + sea_level_density, + } + }); + + let orbit = body.orbit.as_ref().map(|o| OrbitResponse { + semi_major_axis: o.semi_major_axis, + eccentricity: o.eccentricity, + inclination: o.inclination, + argument_of_periapsis: o.argument_of_periapsis, + longitude_of_ascending_node: o.longitude_of_ascending_node, + mean_anomaly_at_epoch: o.mean_anomaly_at_epoch, + epoch: o.epoch, + }); + + BodyDetail { + name: body.name.clone(), + display_name: body.display_name.clone(), + radius: body.radius, + gee_asl: body.gee_asl, + mu: body.mu, + has_ocean: body.has_ocean, + rotational_period: body.rotational_period, + soi: body.soi, + atmosphere, + orbit, + } +} + +/// Build a tree node recursively from the body map. +fn build_tree_node(name: &str, bodies: &HashMap) -> Option { + let body = bodies.get(name)?; + let children = body + .children_names + .iter() + .filter_map(|child_name| build_tree_node(child_name, bodies)) + .collect(); + Some(BodyTreeNode { + name: body.name.clone(), + display_name: body.display_name.clone(), + children, + }) +} + +/// Try to rebuild the system tree from current bodies and store it in state. +/// Returns the list of body names added. +fn rebuild_system( + bodies: &HashMap, +) -> Option { + if bodies.is_empty() { + return None; + } + let body_list: Vec = bodies.values().cloned().collect(); + build_tree(body_list).ok() +} + +// --------------------------------------------------------------------------- +// Commands +// --------------------------------------------------------------------------- + +/// Health check endpoint. +#[tauri::command] +pub fn health() -> serde_json::Value { + serde_json::json!({"status": "ok"}) +} + +/// Upload and parse a Kopernicus config string, adding bodies to state. +#[tauri::command] +pub fn upload_config( + file_content: String, + state: tauri::State<'_, ManagedState>, +) -> Result { + let mut app = state.lock().map_err(|e| e.to_string())?; + let parsed = parse_bodies(&file_content); + if parsed.is_empty() { + return Err("No celestial bodies found in config".to_string()); + } + + let mut added: Vec = Vec::new(); + for body in parsed { + added.push(body.name.clone()); + app.bodies.insert(body.name.clone(), body); + } + + // Try rebuilding the system tree + app.system = rebuild_system(&app.bodies); + + let count = added.len(); + Ok(UploadResponse { + bodies_added: added, + count, + }) +} + +/// Scan a GameData directory for Kopernicus configs and replace state entirely. +#[tauri::command] +pub fn scan_gamedata( + path: String, + exclude: Vec, + state: tauri::State<'_, ManagedState>, +) -> Result { + let system = scan_configs(&path, &exclude)?; + + let added: Vec = system.bodies.keys().cloned().collect(); + let count = added.len(); + + let mut app = state.lock().map_err(|e| e.to_string())?; + app.bodies = system.bodies.clone(); + app.system = Some(system); + + Ok(UploadResponse { + bodies_added: added, + count, + }) +} + +/// List all loaded celestial bodies as summaries. +#[tauri::command] +pub fn list_bodies( + _lang: Option, + state: tauri::State<'_, ManagedState>, +) -> Result, String> { + let app = state.lock().map_err(|e| e.to_string())?; + let mut summaries: Vec = app.bodies.values().map(body_to_summary).collect(); + summaries.sort_by(|a, b| a.name.cmp(&b.name)); + Ok(summaries) +} + +/// Get detailed information for a specific celestial body. +#[tauri::command] +pub fn get_body( + name: String, + _lang: Option, + state: tauri::State<'_, ManagedState>, +) -> Result { + let app = state.lock().map_err(|e| e.to_string())?; + let body = app + .bodies + .get(&name) + .ok_or_else(|| format!("Body not found: {}", name))?; + Ok(body_to_detail(body)) +} + +/// Calculate launch-to-orbit delta-V for a body. +#[tauri::command] +pub fn calc_launch( + body_name: String, + target_altitude: f64, + state: tauri::State<'_, ManagedState>, +) -> Result { + let app = state.lock().map_err(|e| e.to_string())?; + let body = app + .bodies + .get(&body_name) + .ok_or_else(|| format!("Body not found: {}", body_name))?; + + if target_altitude < 0.0 { + return Err("Target altitude must be non-negative".to_string()); + } + + let result = calculate_launch(body, target_altitude); + Ok(LaunchResponse { + orbital_velocity: result.orbital_velocity, + gravity_loss: result.gravity_loss, + drag_loss: result.drag_loss, + total_ideal: result.total_ideal, + total_rocket: result.total_rocket, + jet_savings: result.jet_savings, + total_with_jets: result.total_with_jets, + }) +} + +/// Calculate Hohmann transfer delta-V. +#[tauri::command] +pub fn calc_hohmann( + body_name: String, + parking_alt: f64, + target_sma: f64, + state: tauri::State<'_, ManagedState>, +) -> Result { + let app = state.lock().map_err(|e| e.to_string())?; + let body = app + .bodies + .get(&body_name) + .ok_or_else(|| format!("Body not found: {}", body_name))?; + + if parking_alt < 0.0 { + return Err("Parking altitude must be non-negative".to_string()); + } + + let r_parking = body.radius + parking_alt; + if (r_parking - target_sma).abs() / r_parking.max(target_sma) < 1e-12 { + return Err("Parking orbit and target SMA are identical".to_string()); + } + + let result = calculate_hohmann(body, parking_alt, target_sma); + Ok(HohmannResponse { + departure_dv: result.departure_dv, + arrival_dv: result.arrival_dv, + total_dv: result.total_dv, + transfer_time: result.transfer_time, + inward: result.inward, + }) +} + +/// Apply the Tsiolkovsky rocket equation. +#[tauri::command] +pub fn calc_tsiolkovsky( + delta_v: f64, + isp: f64, + wet_mass: f64, +) -> Result { + if delta_v < 0.0 { + return Err("delta_v must be non-negative".to_string()); + } + if isp <= 0.0 { + return Err("Isp must be positive".to_string()); + } + if wet_mass <= 0.0 { + return Err("Wet mass must be positive".to_string()); + } + + let result = calculate_tsiolkovsky(delta_v, isp, wet_mass); + Ok(TsiolkovskyResponse { + mass_ratio: result.mass_ratio, + fuel_fraction: result.fuel_fraction, + dry_mass: result.dry_mass, + fuel_mass: result.fuel_mass, + }) +} + +/// Get the full celestial system tree. +#[tauri::command] +pub fn get_system( + state: tauri::State<'_, ManagedState>, +) -> Result { + let app = state.lock().map_err(|e| e.to_string())?; + let system = app + .system + .as_ref() + .ok_or_else(|| "No system loaded. Upload a config or scan GameData first.".to_string())?; + + let root_body = system + .bodies + .get(&system.root_name) + .ok_or_else(|| format!("Root body '{}' not found in system", system.root_name))?; + + let home_body = system + .bodies + .get(&system.home_world_name) + .ok_or_else(|| { + format!( + "Home world '{}' not found in system", + system.home_world_name + ) + })?; + + let tree = root_body + .children_names + .iter() + .filter_map(|child_name| build_tree_node(child_name, &system.bodies)) + .collect(); + + Ok(SystemResponse { + root: body_to_summary(root_body), + home_world: body_to_detail(home_body), + body_count: system.bodies.len(), + tree, + }) +} + +/// Get sibling bodies sorted by transfer delta-V from the home world. +#[tauri::command] +pub fn get_destinations( + state: tauri::State<'_, ManagedState>, +) -> Result, String> { + let app = state.lock().map_err(|e| e.to_string())?; + let system = app + .system + .as_ref() + .ok_or_else(|| "No system loaded".to_string())?; + + let sorted = sort_by_transfer_dv(&system.home_world_name, &system.bodies); + + let entries = sorted + .into_iter() + .filter_map(|(name, dv)| { + let body = system.bodies.get(&name)?; + Some(DestinationEntry { + body: body_to_summary(body), + transfer_dv: dv, + }) + }) + .collect(); + + Ok(entries) +} + +/// Compute a delta-V route from home to an optional destination and moon. +#[tauri::command] +pub fn calc_route( + destination: Option, + moon: Option, + state: tauri::State<'_, ManagedState>, +) -> Result { + let app = state.lock().map_err(|e| e.to_string())?; + let system = app + .system + .as_ref() + .ok_or_else(|| "No system loaded".to_string())?; + + let home = system + .bodies + .get(&system.home_world_name) + .ok_or_else(|| "Home world not found in system".to_string())?; + + let parent_name = home + .parent_name + .as_ref() + .ok_or_else(|| "Home world has no parent body".to_string())?; + + let parent = system + .bodies + .get(parent_name) + .ok_or_else(|| format!("Parent body '{}' not found", parent_name))?; + + let dest_body = match &destination { + Some(name) => Some( + system + .bodies + .get(name) + .ok_or_else(|| format!("Destination body '{}' not found", name))?, + ), + None => None, + }; + + let moon_body = match &moon { + Some(name) => Some( + system + .bodies + .get(name) + .ok_or_else(|| format!("Moon '{}' not found", name))?, + ), + None => None, + }; + + let steps = compute_route(home, parent, dest_body, moon_body); + + let total_powered = steps.last().map(|s| s.cumulative).unwrap_or(0.0); + + // Check if any step has an aerobrake note + let has_aerobrake = steps.iter().any(|s| s.note.contains("aerobrake")); + let total_aerobrake = if has_aerobrake { + // Aerobrake landing replaces the last powered landing step + let last_landing_dv = steps + .iter() + .rev() + .find(|s| s.note.contains("aerobrake")) + .map(|s| s.dv) + .unwrap_or(0.0); + Some(total_powered - last_landing_dv) + } else { + None + }; + + let step_responses = steps + .into_iter() + .map(|s| DvStepResponse { + label: s.label, + dv: s.dv, + cumulative: s.cumulative, + note: s.note, + }) + .collect(); + + Ok(RouteResponse { + steps: step_responses, + total_powered, + total_aerobrake, + }) +} + +/// Get an atmosphere profile sampled at regular altitude intervals. +#[tauri::command] +pub fn get_atmo_profile( + name: String, + steps: Option, + state: tauri::State<'_, ManagedState>, +) -> Result { + let app = state.lock().map_err(|e| e.to_string())?; + let body = app + .bodies + .get(&name) + .ok_or_else(|| format!("Body not found: {}", name))?; + + let atmo = body + .atmosphere + .as_ref() + .ok_or_else(|| format!("Body '{}' has no atmosphere", name))?; + + let n_steps = steps.unwrap_or(100) as usize; + if n_steps == 0 { + return Err("Steps must be positive".to_string()); + } + + let depth = atmo.atmosphere_depth; + let step_size = depth / n_steps as f64; + + let mut altitudes = Vec::with_capacity(n_steps + 1); + let mut pressures = Vec::with_capacity(n_steps + 1); + let mut temperatures = Vec::with_capacity(n_steps + 1); + let mut densities = Vec::with_capacity(n_steps + 1); + + for i in 0..=n_steps { + let alt = step_size * i as f64; + altitudes.push(alt); + + let pressure = if !atmo.pressure_curve.is_empty() { + hermite_interp(&atmo.pressure_curve, alt).unwrap_or(0.0) + } else if alt == 0.0 { + atmo.pressure_at_sea_level + } else { + 0.0 + }; + pressures.push(pressure); + + let temperature = if !atmo.temperature_curve.is_empty() { + hermite_interp(&atmo.temperature_curve, alt).unwrap_or(0.0) + } else if alt == 0.0 { + atmo.temperature_at_sea_level + } else { + 0.0 + }; + temperatures.push(temperature); + + let density = density_at_altitude(body, alt).unwrap_or(0.0); + densities.push(density); + } + + Ok(AtmoProfileResponse { + altitude: altitudes, + pressure: pressures, + temperature: temperatures, + density: densities, + }) +} + +/// Get moons of a body sorted by transfer delta-V. +#[tauri::command] +pub fn get_body_moons( + name: String, + state: tauri::State<'_, ManagedState>, +) -> Result, String> { + let app = state.lock().map_err(|e| e.to_string())?; + let system = app + .system + .as_ref() + .ok_or_else(|| "No system loaded".to_string())?; + + let body = system + .bodies + .get(&name) + .ok_or_else(|| format!("Body not found: {}", name))?; + + if body.children_names.is_empty() { + return Ok(Vec::new()); + } + + // Use sort_by_transfer_dv from the home world perspective if + // this body is a planet. For moons, we look at children of this body + // and compute transfers from the body's low orbit. + let lo_alt = low_orbit_altitude(body); + + let mut entries: Vec = Vec::new(); + for child_name in &body.children_names { + let child = match system.bodies.get(child_name) { + Some(c) => c, + None => continue, + }; + let child_orbit = match &child.orbit { + Some(o) => o, + None => continue, + }; + let target_sma = child_orbit.semi_major_axis; + let r_parking = body.radius + lo_alt; + + // Skip if radii are too close (would panic in calculate_hohmann) + if (r_parking - target_sma).abs() / r_parking.max(target_sma) < 1e-12 { + continue; + } + + let hohmann = calculate_hohmann(body, lo_alt, target_sma); + entries.push(DestinationEntry { + body: body_to_summary(child), + transfer_dv: hohmann.total_dv, + }); + } + + entries.sort_by(|a, b| { + a.transfer_dv + .partial_cmp(&b.transfer_dv) + .unwrap_or(std::cmp::Ordering::Equal) + }); + + Ok(entries) +} diff --git a/src-tauri/src/main.rs b/src-tauri/src/main.rs index 1baa891..1b48778 100644 --- a/src-tauri/src/main.rs +++ b/src-tauri/src/main.rs @@ -1,78 +1,29 @@ #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] -use std::process::{Command, Stdio}; use std::sync::Mutex; -use tauri::Manager; -struct PythonProcess(Mutex>); - -fn find_python() -> Option { - for cmd in ["python", "py", "python3"] { - if Command::new(cmd) - .arg("--version") - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .status() - .is_ok() - { - return Some(cmd.to_string()); - } - } - None -} +mod commands; +mod state; fn main() { tauri::Builder::default() .plugin(tauri_plugin_dialog::init()) - .setup(|app| { - let resource_dir = app - .path() - .resource_dir() - .expect("Failed to resolve resource directory"); - - let resources = resource_dir.join("resources"); - let launcher_path = resources.join("launcher.py"); - - let python = find_python().expect( - "Python not found. Install Python 3.10+ and ensure it is on PATH.", - ); - - eprintln!("[tauri] Python: {}", python); - eprintln!("[tauri] Launcher: {}", launcher_path.display()); - - // Use Stdio::null — launcher.py writes its own log file. - // IMPORTANT: Do NOT use Stdio::piped() without reading, - // as a full pipe buffer will block the child process. - let child = Command::new(&python) - .arg(&launcher_path) - .current_dir(&resources) - .stdout(Stdio::null()) - .stderr(Stdio::null()) - .spawn(); - - match child { - Ok(proc) => { - app.manage(PythonProcess(Mutex::new(Some(proc)))); - } - Err(e) => { - eprintln!("[tauri] Failed to spawn Python: {}", e); - app.manage(PythonProcess(Mutex::new(None))); - } - } - - Ok(()) - }) - .build(tauri::generate_context!()) - .expect("error while building tauri application") - .run(|app: &tauri::AppHandle, event: tauri::RunEvent| { - if let tauri::RunEvent::Exit = event { - if let Some(state) = app.try_state::() { - if let Ok(mut guard) = state.0.lock() { - if let Some(proc) = guard.as_mut() { - let _ = proc.kill(); - } - } - } - } - }); + .manage(Mutex::new(state::AppState::new())) + .invoke_handler(tauri::generate_handler![ + commands::health, + commands::upload_config, + commands::scan_gamedata, + commands::list_bodies, + commands::get_body, + commands::calc_launch, + commands::calc_hohmann, + commands::calc_tsiolkovsky, + commands::get_system, + commands::get_destinations, + commands::calc_route, + commands::get_atmo_profile, + commands::get_body_moons, + ]) + .run(tauri::generate_context!()) + .expect("error while running tauri application"); } diff --git a/src-tauri/src/state.rs b/src-tauri/src/state.rs new file mode 100644 index 0000000..33003c2 --- /dev/null +++ b/src-tauri/src/state.rs @@ -0,0 +1,32 @@ +//! Application state shared across Tauri commands. +//! +//! Tauri コマンド間で共有するアプリケーション状態。 + +use std::collections::HashMap; +use std::sync::Mutex; + +use kopdeltav::models::CelestialBody; +use kopdeltav::system::CelestialSystem; + +/// Central application state holding parsed celestial bodies and the built system tree. +/// +/// パース済み天体とシステムツリーを保持する中央アプリケーション状態。 +pub struct AppState { + /// All loaded celestial bodies indexed by internal name. + pub bodies: HashMap, + /// The fully linked celestial system tree, built after loading bodies. + pub system: Option, +} + +impl AppState { + /// Create a new empty state with no bodies loaded. + pub fn new() -> Self { + Self { + bodies: HashMap::new(), + system: None, + } + } +} + +/// Thread-safe wrapper around `AppState` for Tauri managed state. +pub type ManagedState = Mutex; diff --git a/src-tauri/tauri.conf.json b/src-tauri/tauri.conf.json index 9d5cd5c..f9fca1c 100644 --- a/src-tauri/tauri.conf.json +++ b/src-tauri/tauri.conf.json @@ -20,14 +20,8 @@ } ], "security": { - "csp": "default-src 'self'; connect-src 'self' http://localhost:8000; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:" + "csp": "default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com; img-src 'self' data:" } }, - "bundle": { - "resources": [ - "resources/*.py", - "resources/*.txt", - "resources/kopdeltav/*" - ] - } + "bundle": {} }