-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathar-engine.js
More file actions
336 lines (279 loc) 路 10.8 KB
/
Copy pathar-engine.js
File metadata and controls
336 lines (279 loc) 路 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
// ArtScape AR Engine
// Handles AR rendering, location tracking, and art placement
// Use same-origin API so it works on Render without hardcoding localhost.
const API_URL = `${window.location.origin}/api`;
class AREngine {
constructor() {
this.scene = null;
this.camera = null;
this.renderer = null;
this.videoElement = null;
this.currentLocation = null;
this.deviceOrientation = { alpha: 0, beta: 0, gamma: 0 };
this.artInstallations = [];
this.loadedArt = new Map();
this.initialized = false;
}
async init() {
try {
// Get camera access
await this.setupCamera();
// Setup Three.js scene
this.setupScene();
// Setup device orientation
this.setupOrientation();
// Start location tracking
this.startLocationTracking();
// Load nearby art
await this.loadNearbyArt();
// Start render loop
this.animate();
this.initialized = true;
document.getElementById('loadingSpinner').classList.add('hidden');
} catch (error) {
console.error('AR Engine initialization failed:', error);
alert('Failed to initialize AR. Please check camera and location permissions.');
}
}
async setupCamera() {
this.videoElement = document.getElementById('camera');
try {
const stream = await navigator.mediaDevices.getUserMedia({
video: {
facingMode: 'environment',
width: { ideal: 1920 },
height: { ideal: 1080 }
}
});
this.videoElement.srcObject = stream;
await this.videoElement.play();
} catch (error) {
throw new Error('Camera access denied: ' + error.message);
}
}
setupScene() {
const canvas = document.getElementById('ar-canvas');
// Scene
this.scene = new THREE.Scene();
// Camera
this.camera = new THREE.PerspectiveCamera(
75,
window.innerWidth / window.innerHeight,
0.1,
1000
);
this.camera.position.set(0, 1.6, 0); // Average human eye height
// Renderer
this.renderer = new THREE.WebGLRenderer({
canvas: canvas,
alpha: true,
antialias: true
});
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.renderer.setPixelRatio(window.devicePixelRatio);
// Lighting
const ambientLight = new THREE.AmbientLight(0xffffff, 0.8);
this.scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(5, 10, 5);
this.scene.add(directionalLight);
// Handle window resize
window.addEventListener('resize', () => {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize(window.innerWidth, window.innerHeight);
});
}
setupOrientation() {
// Request permission for iOS devices
if (typeof DeviceOrientationEvent !== 'undefined' &&
typeof DeviceOrientationEvent.requestPermission === 'function') {
DeviceOrientationEvent.requestPermission()
.then(permissionState => {
if (permissionState === 'granted') {
this.addOrientationListener();
}
})
.catch(console.error);
} else {
this.addOrientationListener();
}
}
addOrientationListener() {
window.addEventListener('deviceorientation', (event) => {
this.deviceOrientation.alpha = event.alpha || 0; // Z-axis (compass)
this.deviceOrientation.beta = event.beta || 0; // X-axis
this.deviceOrientation.gamma = event.gamma || 0; // Y-axis
this.updateCameraOrientation();
});
}
updateCameraOrientation() {
const { alpha, beta, gamma } = this.deviceOrientation;
// Convert device orientation to camera rotation
const alphaRad = THREE.MathUtils.degToRad(alpha);
const betaRad = THREE.MathUtils.degToRad(beta);
const gammaRad = THREE.MathUtils.degToRad(gamma);
this.camera.rotation.set(betaRad, alphaRad, -gammaRad, 'YXZ');
}
startLocationTracking() {
if (!navigator.geolocation) {
alert('Geolocation is not supported by your browser');
return;
}
navigator.geolocation.watchPosition(
(position) => {
this.currentLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude,
accuracy: position.coords.accuracy
};
this.updateLocationDisplay();
this.updateNearbyArt();
},
(error) => {
console.error('Location error:', error);
document.getElementById('locationStatus').textContent =
'馃搷 Location unavailable';
},
{
enableHighAccuracy: true,
maximumAge: 0,
timeout: 5000
}
);
}
updateLocationDisplay() {
const status = document.getElementById('locationStatus');
if (this.currentLocation) {
status.textContent =
`馃搷 ${this.currentLocation.lat.toFixed(6)}, ${this.currentLocation.lng.toFixed(6)}`;
}
}
async loadNearbyArt() {
try {
const token = localStorage.getItem('token');
const response = await fetch(`${API_URL}/art/nearby`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
if (response.ok) {
this.artInstallations = await response.json();
this.updateNearbyArt();
}
} catch (error) {
console.error('Failed to load art installations:', error);
}
}
updateNearbyArt() {
if (!this.currentLocation) return;
const nearbyList = document.getElementById('nearbyArt');
const nearby = this.artInstallations.filter(art => {
const distance = this.calculateDistance(
this.currentLocation.lat,
this.currentLocation.lng,
art.location.coordinates[1],
art.location.coordinates[0]
);
art.distance = distance;
return distance < 1000; // Within 1km
});
if (nearby.length === 0) {
nearbyList.innerHTML = '<p>No art installations nearby</p>';
} else {
nearby.sort((a, b) => a.distance - b.distance);
nearbyList.innerHTML = nearby.map(art =>
`<div class="nearby-item">
<strong>${art.title}</strong> - ${art.distance.toFixed(0)}m away
</div>`
).join('');
// Place art in scene
this.placeArtInScene(nearby);
}
}
placeArtInScene(artworks) {
if (!this.currentLocation) return;
artworks.forEach(art => {
if (!this.loadedArt.has(art._id) && art.distance < 100) {
this.createArtObject(art);
}
});
}
createArtObject(art) {
// Calculate relative position from user
const bearing = this.calculateBearing(
this.currentLocation.lat,
this.currentLocation.lng,
art.location.coordinates[1],
art.location.coordinates[0]
);
const distance = art.distance;
const bearingRad = THREE.MathUtils.degToRad(bearing);
// Convert to Three.js coordinates
const x = Math.sin(bearingRad) * distance;
const z = -Math.cos(bearingRad) * distance;
// Create art object based on type
let artObject;
if (art.artType === 'image') {
// Create image plane
const geometry = new THREE.PlaneGeometry(art.scale, art.scale);
const texture = new THREE.TextureLoader().load(art.fileUrl);
const material = new THREE.MeshBasicMaterial({
map: texture,
side: THREE.DoubleSide,
transparent: true
});
artObject = new THREE.Mesh(geometry, material);
} else {
// For 3D models (placeholder - would use GLTFLoader in production)
const geometry = new THREE.BoxGeometry(art.scale, art.scale, art.scale);
const material = new THREE.MeshStandardMaterial({
color: 0x6366f1,
metalness: 0.5,
roughness: 0.5
});
artObject = new THREE.Mesh(geometry, material);
}
artObject.position.set(x, art.scale / 2, z);
artObject.userData = art;
this.scene.add(artObject);
this.loadedArt.set(art._id, artObject);
}
calculateDistance(lat1, lon1, lat2, lon2) {
const R = 6371000; // Earth's radius in meters
const 蠁1 = lat1 * Math.PI / 180;
const 蠁2 = lat2 * Math.PI / 180;
const 螖蠁 = (lat2 - lat1) * Math.PI / 180;
const 螖位 = (lon2 - lon1) * Math.PI / 180;
const a = Math.sin(螖蠁 / 2) * Math.sin(螖蠁 / 2) +
Math.cos(蠁1) * Math.cos(蠁2) *
Math.sin(螖位 / 2) * Math.sin(螖位 / 2);
const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return R * c;
}
calculateBearing(lat1, lon1, lat2, lon2) {
const 蠁1 = lat1 * Math.PI / 180;
const 蠁2 = lat2 * Math.PI / 180;
const 螖位 = (lon2 - lon1) * Math.PI / 180;
const y = Math.sin(螖位) * Math.cos(蠁2);
const x = Math.cos(蠁1) * Math.sin(蠁2) -
Math.sin(蠁1) * Math.cos(蠁2) * Math.cos(螖位);
const 胃 = Math.atan2(y, x);
return (胃 * 180 / Math.PI + 360) % 360;
}
animate() {
requestAnimationFrame(() => this.animate());
// Render scene
this.renderer.render(this.scene, this.camera);
}
}
// Initialize AR Engine when page loads
let arEngine;
window.addEventListener('load', async () => {
arEngine = new AREngine();
await arEngine.init();
});
// Helper functions
function closeArtInfo() {
document.getElementById('artInfoPanel').classList.add('hidden');
}