1
0

Compare commits

...

3 Commits

Author SHA1 Message Date
0e70a06e05 add tokyo 2025-11-21 13:08:09 +09:00
f706e9a14e gh-actions 2025-11-21 13:07:54 +09:00
11d667c65e ignore 2025-11-21 13:07:42 +09:00
5 changed files with 219 additions and 26 deletions

View File

@@ -4,6 +4,7 @@ on:
push: push:
branches: branches:
- main - main
environment: gh-pages
jobs: jobs:
build-deploy: build-deploy:
@@ -23,6 +24,7 @@ jobs:
- name: Build - name: Build
env: env:
TZ: "Asia/Tokyo" TZ: "Asia/Tokyo"
VITE_GOOGLE_MAP_API_KEY: ${{ secrets.VITE_GOOGLE_MAP_API_KEY }}
run: | run: |
cd atmosphere/ cd atmosphere/
npm run build npm run build

2
.gitignore vendored
View File

@@ -9,3 +9,5 @@ dist/*.js
*/dist/models */dist/models
dist dist
three-geospatial three-geospatial
**.env
.env

View File

@@ -15,6 +15,7 @@
"@react-three/postprocessing": "^3.0.4", "@react-three/postprocessing": "^3.0.4",
"@takram/three-atmosphere": "^0.15.1", "@takram/three-atmosphere": "^0.15.1",
"@takram/three-clouds": "^0.5.2", "@takram/three-clouds": "^0.5.2",
"3d-tiles-renderer": "^0.4.18",
"react": "^19.0.0-rc.1", "react": "^19.0.0-rc.1",
"react-dom": "^19.0.0-rc.1", "react-dom": "^19.0.0-rc.1",
"three": "^0.181.2" "three": "^0.181.2"

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@@ -12,9 +12,20 @@ import * as THREE from 'three';
// Takram Libraries // Takram Libraries
import { AerialPerspective, Atmosphere } from '@takram/three-atmosphere/r3f'; import { AerialPerspective, Atmosphere } from '@takram/three-atmosphere/r3f';
import { Clouds, CloudLayer } from '@takram/three-clouds/r3f'; import { Clouds, CloudLayer } from '@takram/three-clouds/r3f';
import { Geodetic, PointOfView, radians } from '@takram/three-geospatial';
// 3D Tiles Renderer
import { TilesPlugin, TilesRenderer } from '3d-tiles-renderer/r3f';
import {
GLTFExtensionsPlugin,
GoogleCloudAuthPlugin,
TileCompressionPlugin,
TilesFadePlugin,
UpdateOnChangePlugin,
} from '3d-tiles-renderer/plugins';
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader';
const BASE_URL = import.meta.env.BASE_URL; const BASE_URL = import.meta.env.BASE_URL;
const VRM_URL = `${BASE_URL}ai.vrm`; const VRM_URL = `${BASE_URL}ai.vrm`;
const VRMA_URL = `${BASE_URL}fly.vrma`; const VRMA_URL = `${BASE_URL}fly.vrma`;
const EARTH_RADIUS = 6378137; const EARTH_RADIUS = 6378137;
@@ -59,23 +70,101 @@ const WEATHER_PRESETS = [
} }
]; ];
// --- Locations ---
// --- Locations ---
const LOCATIONS = [
{ name: 'Tokyo', longitude: 139.7671, latitude: 35.6812, heading: 180, pitch: -5, distance: 300 },
{ name: 'Fuji', longitude: 138.7278, latitude: 35.3606, heading: 0, pitch: -10, distance: 4000 },
{ name: 'Space', longitude: 139.7671, latitude: 35.6812, heading: 0, pitch: -90, distance: 10000000 },
];
// --- Shared State for Synchronization --- // --- Shared State for Synchronization ---
// 複数のCanvas間で状態を共有するための簡易ストア // 複数のCanvas間で状態を共有するための簡易ストア
const worldState = { const worldState = {
// 世界座標 (Atmosphere内での位置) // 世界座標 (Atmosphere内での位置 - ECEF)
position: new Vector3(0, EARTH_RADIUS + 2000, 0), position: new Vector3(0, EARTH_RADIUS + 2000, 0),
// カメラの回転 (AvatarLayerのカメラ回転をAtmosphereに同期) // ローカル回転 (AvatarLayerでの回転 - Y-up)
// Note: This is treated as the "Local" quaternion.
quaternion: new Quaternion(), quaternion: new Quaternion(),
// 移動速度 (m/s) // 移動速度 (m/s)
speed: 5000.0, speed: 1000.0,
}; };
// Helper: Calculate Basis Rotation (Alignment to Surface Normal)
function getSurfaceBasis(position) {
if (!position) return new Quaternion();
// Debug Geodetic API
if (!window.geodeticLogged) {
console.log('Geodetic prototype:', Geodetic.prototype);
window.geodeticLogged = true;
}
const up = position.clone().normalize();
if (up.lengthSq() < 0.1) return new Quaternion(); // Safety check
const basis = new Quaternion().setFromUnitVectors(new Vector3(0, 1, 0), up);
return basis;
}
// Helper: Calculate Ellipsoid Radius at current position (WGS84)
function getEllipsoidRadius(position) {
const a = 6378137.0;
const b = 6356752.314245;
const r = position.length();
if (r < 100) return a; // Fallback
// Assuming Z is North in ECEF (Standard)
const z = position.z;
const sinPhi = z / r;
const cosPhi = Math.sqrt(1 - sinPhi * sinPhi);
const aCos = a * cosPhi;
const bSin = b * sinPhi;
const num = (a * aCos) * (a * aCos) + (b * bSin) * (b * bSin);
const den = (aCos * aCos) + (bSin * bSin);
return Math.sqrt(num / den);
}
// Teleport Function
function teleportTo(location) {
const { longitude, latitude, heading, pitch, distance } = location;
const position = new Vector3();
const globalQuaternion = new Quaternion(); // Global rotation
const up = new Vector3(0, 1, 0);
// 1. Calculate True Position (at target lat/lon and altitude)
// Treat 'distance' as altitude in meters
const truePosition = new Geodetic(radians(longitude), radians(latitude), distance).toECEF();
// 2. Calculate Rotation using PointOfView
// We use PointOfView to get the correct orientation (looking at the target).
// We ignore the position calculated by PointOfView because it assumes an orbit/look-at constraint.
new PointOfView(distance, radians(heading), radians(pitch)).decompose(
new Geodetic(radians(longitude), radians(latitude)).toECEF(),
position, // Dummy position (ignored)
globalQuaternion,
up
);
console.log(`[Teleport] ${location.name} -> Altitude: ${distance}, TruePosLength: ${truePosition.length()}`);
// 3. Apply True Position
worldState.position.copy(truePosition);
// 4. Apply Rotation (Global -> Local)
// GlobalQ = BasisQ * LocalQ => LocalQ = BasisQ^-1 * GlobalQ
const basis = getSurfaceBasis(truePosition);
const basisInv = basis.clone().invert();
worldState.quaternion.copy(basisInv.multiply(globalQuaternion));
}
// キー入力管理 // キー入力管理
const keys = { const keys = {
w: false, w: false,
a: false, a: false,
s: false, s: false,
d: false, d: false,
q: false,
e: false,
Shift: false, Shift: false,
Space: false, Space: false,
}; };
@@ -100,6 +189,25 @@ if (typeof window !== 'undefined') {
// Scene Components (Inside Canvas) // Scene Components (Inside Canvas)
// --------------------------------------------------------- // ---------------------------------------------------------
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://www.gstatic.com/draco/v1/decoders/');
function GoogleMaps3DTiles() {
const apiKey = import.meta.env.VITE_GOOGLE_MAP_API_KEY;
if (!apiKey) return null;
return (
<TilesRenderer url={`https://tile.googleapis.com/v1/3dtiles/root.json?key=${apiKey}`}>
<TilesPlugin plugin={GoogleCloudAuthPlugin} args={{ apiToken: apiKey }} />
<TilesPlugin plugin={GLTFExtensionsPlugin} dracoLoader={dracoLoader} />
<TilesPlugin plugin={TileCompressionPlugin} />
<TilesPlugin plugin={UpdateOnChangePlugin} />
<TilesPlugin plugin={TilesFadePlugin} />
</TilesRenderer>
);
}
// Canvasの内側で動作するメインシーンコンポーネント // Canvasの内側で動作するメインシーンコンポーネント
function AtmosphereScene() { function AtmosphereScene() {
const { gl } = useThree(); const { gl } = useThree();
@@ -175,6 +283,7 @@ function AtmosphereScene() {
/> />
<Atmosphere ref={atmosphereRef}> <Atmosphere ref={atmosphereRef}>
<GoogleMaps3DTiles />
<EffectComposer multisampling={0} disableNormalPass={false}> <EffectComposer multisampling={0} disableNormalPass={false}>
<Clouds disableDefaultLayers coverage={weather.coverage}> <Clouds disableDefaultLayers coverage={weather.coverage}>
{weather.layers.map((layer, index) => ( {weather.layers.map((layer, index) => (
@@ -199,9 +308,17 @@ function AtmosphereScene() {
// Atmosphere側のカメラをShared Stateに同期させる // Atmosphere側のカメラをShared Stateに同期させる
function FollowCamera() { function FollowCamera() {
useFrame((state) => { useFrame((state) => {
// Shared Stateの位置と回転を適用 if (!worldState.position) return;
// 1. Calculate Basis Rotation based on current position
const basis = getSurfaceBasis(worldState.position);
// 2. Apply Position
state.camera.position.copy(worldState.position); state.camera.position.copy(worldState.position);
state.camera.quaternion.copy(worldState.quaternion);
// 3. Apply Rotation: GlobalQ = BasisQ * LocalQ
// worldState.quaternion is treated as Local Quaternion here
state.camera.quaternion.copy(basis).multiply(worldState.quaternion);
}); });
return null; return null;
} }
@@ -362,7 +479,6 @@ function VrmCharacter() {
function CameraSync() { function CameraSync() {
const { camera } = useThree(); const { camera } = useThree();
const vec = new Vector3(); const vec = new Vector3();
const euler = new Euler(0, 0, 0, 'YXZ');
// Dynamic Zoom State // Dynamic Zoom State
const zoomOffset = useRef(0); const zoomOffset = useRef(0);
@@ -370,34 +486,64 @@ function CameraSync() {
const ZOOM_SPEED = 2.0; const ZOOM_SPEED = 2.0;
useFrame((state, delta) => { useFrame((state, delta) => {
// 1. カメラの回転をShared Stateに同期 // 1. カメラの回転をShared State (Local) に同期
worldState.quaternion.copy(camera.quaternion); worldState.quaternion.copy(camera.quaternion);
// 2. WASD移動ロジック // 2. Calculate Basis Rotation
const isMoving = keys.w || keys.s || keys.a || keys.d; const basis = getSurfaceBasis(worldState.position);
// 3. WASD移動ロジック (Local -> Global)
const isMoving = keys.w || keys.s || keys.a || keys.d || keys.q || keys.e;
const speed = worldState.speed * (keys.Shift ? 2.0 : 1.0) * delta; const speed = worldState.speed * (keys.Shift ? 2.0 : 1.0) * delta;
// 前後 (W/S) // Local Movement Vector
if (keys.w) { const moveDir = new Vector3();
vec.set(0, 0, -1).applyQuaternion(camera.quaternion); if (keys.w) moveDir.z -= 1;
worldState.position.addScaledVector(vec, speed); if (keys.s) moveDir.z += 1;
if (keys.a) moveDir.x -= 1;
if (keys.d) moveDir.x += 1;
// Altitude Control (Global Up/Down relative to surface)
// We apply this directly to worldState.position along the up vector
const upVector = worldState.position.clone().normalize();
if (keys.e) {
worldState.position.addScaledVector(upVector, speed);
} }
if (keys.s) { if (keys.q) {
vec.set(0, 0, 1).applyQuaternion(camera.quaternion); worldState.position.addScaledVector(upVector, -speed);
worldState.position.addScaledVector(vec, speed);
} }
// 左右 (A/D) if (moveDir.lengthSq() > 0) {
if (keys.a) { moveDir.normalize();
vec.set(-1, 0, 0).applyQuaternion(camera.quaternion); // Apply Camera Rotation (Local)
worldState.position.addScaledVector(vec, speed); moveDir.applyQuaternion(camera.quaternion);
}
if (keys.d) { // Apply Basis Rotation (Local -> Global)
vec.set(1, 0, 0).applyQuaternion(camera.quaternion); moveDir.applyQuaternion(basis);
worldState.position.addScaledVector(vec, speed);
// Apply to Global Position
worldState.position.addScaledVector(moveDir, speed);
} }
// 3. Dynamic Zoom Logic // 4. Minimum Altitude Safety Check
const currentDist = worldState.position.length();
// Calculate local ellipsoid radius
const localRadius = getEllipsoidRadius(worldState.position);
const minAltitude = localRadius + 10; // Minimum 10m above ellipsoid
// Debug Log
if (state.clock.elapsedTime % 1.0 < 0.02) {
console.log(`[CameraSync] Dist: ${currentDist.toFixed(1)}, LocalR: ${localRadius.toFixed(1)}, Alt: ${(currentDist - localRadius).toFixed(1)}`);
}
if (currentDist < minAltitude) {
// console.log(`[CameraSync] Safety Check Triggered! Pushing up to ${minAltitude}`);
worldState.position.setLength(minAltitude);
}
// 5. Dynamic Zoom Logic
const targetZoom = isMoving ? MAX_ZOOM_OFFSET : 0; const targetZoom = isMoving ? MAX_ZOOM_OFFSET : 0;
// Smoothly interpolate current zoom offset towards target // Smoothly interpolate current zoom offset towards target
const diff = targetZoom - zoomOffset.current; const diff = targetZoom - zoomOffset.current;
@@ -429,6 +575,45 @@ function AvatarLayer() {
); );
} }
// ---------------------------------------------------------
// UI Components
// ---------------------------------------------------------
function LocationUI() {
return (
<div style={{
position: 'absolute',
top: '20px',
left: '20px',
zIndex: 100,
display: 'flex',
gap: '10px',
flexWrap: 'wrap'
}}>
{LOCATIONS.map((loc) => (
<button
key={loc.name}
onClick={() => teleportTo(loc)}
style={{
padding: '10px 20px',
background: 'rgba(0, 0, 0, 0.6)',
color: 'white',
border: '1px solid rgba(255, 255, 255, 0.3)',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '14px',
backdropFilter: 'blur(4px)',
transition: 'background 0.2s'
}}
onMouseOver={(e) => e.currentTarget.style.background = 'rgba(0, 0, 0, 0.8)'}
onMouseOut={(e) => e.currentTarget.style.background = 'rgba(0, 0, 0, 0.6)'}
>
{loc.name}
</button>
))}
</div>
);
}
// --------------------------------------------------------- // ---------------------------------------------------------
// Main App // Main App
// --------------------------------------------------------- // ---------------------------------------------------------
@@ -453,6 +638,9 @@ export default function App() {
return ( return (
<div style={{ position: 'relative', width: '100vw', height: '100vh', background: '#000' }}> <div style={{ position: 'relative', width: '100vw', height: '100vh', background: '#000' }}>
{/* UI Layer */}
<LocationUI />
{/* Layer 0: Atmosphere */} {/* Layer 0: Atmosphere */}
<div style={{ ...layerStyle, zIndex: 0 }}> <div style={{ ...layerStyle, zIndex: 0 }}>
<AtmosphereLayer /> <AtmosphereLayer />