-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
541 lines (461 loc) · 21.1 KB
/
main.cpp
File metadata and controls
541 lines (461 loc) · 21.1 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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
// main.cpp
// Simulação interativa de paralaxe estelar com Raylib (C++)
// Compile: g++ -std=c++17 -O2 main.cpp -o parallax_app -lraylib -lGL -lm -lpthread -ldl -lrt -lX11
#include "raylib.h"
#include <cmath>
#include <string>
#include <optional>
#include <vector>
#include <sstream>
#include <iomanip>
// -------------------- constantes físicas / conversões --------------------
constexpr double AU = 1.0;
constexpr double PC_TO_AU = 206265.0;
constexpr double RAD_TO_ARCSEC = 180.0 / M_PI * 3600.0;
constexpr double LIGHT_YEAR_TO_PC = 0.306601;
// Escala de renderização: 1 unidade de renderização = 1 AU
constexpr double RENDER_SCALE = 1.0;
// -------------------- estruturas de dados --------------------
struct Observation {
Vector3 earthPos;
double timeAngle;
double timestamp;
Color color;
};
struct Star {
double distance_pc;
double lon_deg;
double lat_deg;
Color color;
float size;
std::string name;
};
// -------------------- utilitários vetoriais --------------------
static double clampd(double v, double a, double b) {
if (v < a) return a;
if (v > b) return b;
return v;
}
static double magnitude(const Vector3 &v) {
return sqrt(v.x*v.x + v.y*v.y + v.z*v.z);
}
static Vector3 normalized(const Vector3 &v) {
float mag = magnitude(v);
if (mag == 0) return {0,0,0};
return { v.x/mag, v.y/mag, v.z/mag };
}
// Converter posição da estrela de coordenadas esféricas (pc) para cartesianas (AU)
static Vector3 starPositionInAU(const Star &star) {
double dist_au = star.distance_pc * PC_TO_AU;
double lon_rad = star.lon_deg * M_PI / 180.0;
double lat_rad = star.lat_deg * M_PI / 180.0;
return {
(float)(dist_au * cos(lat_rad) * cos(lon_rad)),
(float)(dist_au * sin(lat_rad)),
(float)(dist_au * cos(lat_rad) * sin(lon_rad))
};
}
// Converter posição em AU para posição de renderização (com escala ajustável)
static Vector3 auToRender(const Vector3 &posAU, double visualScale) {
return {
(float)(posAU.x / visualScale),
(float)(posAU.y / visualScale),
(float)(posAU.z / visualScale)
};
}
// -------------------- aplicação --------------------
int main() {
// Janela
const int screenWidth = 1400;
const int screenHeight = 900;
InitWindow(screenWidth, screenHeight, "Laboratório de Paralaxe Estelar - Simulação Interativa");
SetTargetFPS(60);
// Câmera orbital
Vector3 cameraTarget = {0.0f, 0.0f, 0.0f};
float camYaw = 45.0f;
float camPitch = -20.0f;
float camDistance = 25.0f;
// Física/Simulação
double orbitRadius = 5.0; // 1 AU = 5 unidades de renderização
double timeAngle = 0.0;
double autoSpeed = 0.6;
bool autoRunning = true;
double simulationTime = 0.0;
// Múltiplas estrelas com distâncias realistas
std::vector<Star> stars = {
{4.0, 30.0, 6.0, Color{255,100,100,255}, 0.45f, "Alpha (Proxima)"},
{10.0, 120.0, -15.0, Color{100,255,100,255}, 0.40f, "Beta (Epsilon Eri)"},
{2.5, 210.0, 20.0, Color{100,150,255,255}, 0.50f, "Gamma (Barnard)"},
};
int selectedStar = 0;
// Escala de visualização - divide as distâncias AU para caber na tela
// Estrelas ficam visualmente mais próximas mas cálculos usam distâncias reais
double visualScale = 100000.0; // 1 unidade render = 100000 AU
// Observações
std::vector<Observation> observations;
int maxObservations = 6;
// Estados de visualização
bool showOrbit = true;
bool showGrid = true;
bool showLabels = true;
bool showTrajectory = false;
bool showMeasurement = false;
std::vector<Vector3> earthTrajectory;
// Modos de visualização
enum ViewMode { VIEW_3D, VIEW_TOP, VIEW_SIDE };
ViewMode viewMode = VIEW_3D;
// Medições
double measuredParallax = 0.0;
double estimatedDistance = 0.0;
double errorPercent = 0.0;
bool measurementValid = false;
// Interface
bool showHelp = true;
bool showStats = true;
// loop principal
while (!WindowShouldClose()) {
float dt = GetFrameTime();
// Input
if (IsKeyPressed(KEY_ESCAPE)) break;
if (IsKeyPressed(KEY_SPACE)) autoRunning = !autoRunning;
if (IsKeyPressed(KEY_H)) showHelp = !showHelp;
if (IsKeyPressed(KEY_T)) showStats = !showStats;
if (IsKeyPressed(KEY_G)) showGrid = !showGrid;
if (IsKeyPressed(KEY_O)) showOrbit = !showOrbit;
if (IsKeyPressed(KEY_L)) showLabels = !showLabels;
if (IsKeyPressed(KEY_P)) showTrajectory = !showTrajectory;
// Trocar entre estrelas
if (IsKeyPressed(KEY_ONE)) selectedStar = 0;
if (IsKeyPressed(KEY_TWO)) selectedStar = 1;
if (IsKeyPressed(KEY_THREE)) selectedStar = 2;
// Modos de visualização
if (IsKeyPressed(KEY_F1)) viewMode = VIEW_3D;
if (IsKeyPressed(KEY_F2)) viewMode = VIEW_TOP;
if (IsKeyPressed(KEY_F3)) viewMode = VIEW_SIDE;
// Reset
if (IsKeyPressed(KEY_R)) {
observations.clear();
earthTrajectory.clear();
stars[0].distance_pc = 4.0;
stars[1].distance_pc = 10.0;
stars[2].distance_pc = 2.5;
timeAngle = 0.0;
autoRunning = true;
measurementValid = false;
simulationTime = 0.0;
}
// Capturar observação
if (IsKeyPressed(KEY_C)) {
if (observations.size() < maxObservations) {
Vector3 earthPos = {
(float)(orbitRadius * cos(timeAngle)),
0.0f,
(float)(orbitRadius * sin(timeAngle))
};
Color colors[] = {
YELLOW,
Color{0,255,255,255},
MAGENTA,
Color{0,255,0,255},
ORANGE,
Color{255,192,203,255}
};
observations.push_back({
earthPos,
timeAngle,
simulationTime,
colors[observations.size() % 6]
});
}
}
// Limpar última observação
if (IsKeyPressed(KEY_X) && !observations.empty()) {
observations.pop_back();
measurementValid = false;
}
// Medir paralaxe
if (IsKeyPressed(KEY_M) && observations.size() >= 2) {
showMeasurement = !showMeasurement;
Observation &obsA = observations.front();
Observation &obsB = observations.back();
Star &star = stars[selectedStar];
// Posições da Terra em AU (órbita tem raio de 1 AU)
double earthA_x = cos(obsA.timeAngle);
double earthA_y = 0.0;
double earthA_z = sin(obsA.timeAngle);
double earthB_x = cos(obsB.timeAngle);
double earthB_y = 0.0;
double earthB_z = sin(obsB.timeAngle);
// Posição real da estrela em AU
Vector3 starPosAU = starPositionInAU(star);
// Vetores de observação (da Terra para a estrela)
double v1x = starPosAU.x - earthA_x;
double v1y = starPosAU.y - earthA_y;
double v1z = starPosAU.z - earthA_z;
double v2x = starPosAU.x - earthB_x;
double v2y = starPosAU.y - earthB_y;
double v2z = starPosAU.z - earthB_z;
// Normalizar vetores
double mag1 = sqrt(v1x*v1x + v1y*v1y + v1z*v1z);
double mag2 = sqrt(v2x*v2x + v2y*v2y + v2z*v2z);
v1x /= mag1; v1y /= mag1; v1z /= mag1;
v2x /= mag2; v2y /= mag2; v2z /= mag2;
// Calcular ângulo entre os dois vetores de observação
double dot = (v1x*v2x + v1y*v2y + v1z*v2z);
double cosang = clampd(dot, -1.0, 1.0);
double total_angle_rad = acos(cosang);
// A paralaxe é metade do ângulo total (ângulo de deslocamento máximo)
double p_rad = total_angle_rad / 2.0;
// Converter para arcsegundos
measuredParallax = p_rad * RAD_TO_ARCSEC;
// Calcular distância usando a fórmula: d(pc) = 1 / p(arcsec)
if (measuredParallax > 1e-10) {
estimatedDistance = 1.0 / measuredParallax;
} else {
estimatedDistance = INFINITY;
}
// Calcular erro percentual
if (std::isfinite(estimatedDistance)) {
errorPercent = fabs(estimatedDistance - star.distance_pc) / star.distance_pc * 100.0;
measurementValid = true;
} else {
errorPercent = 100.0;
measurementValid = false;
}
}
// Controles contínuos
if (IsKeyDown(KEY_LEFT)) timeAngle -= 0.02;
if (IsKeyDown(KEY_RIGHT)) timeAngle += 0.02;
if (IsKeyDown(KEY_UP)) stars[selectedStar].distance_pc += 0.05;
if (IsKeyDown(KEY_DOWN)) stars[selectedStar].distance_pc = std::max(0.1, stars[selectedStar].distance_pc - 0.05);
if (IsKeyDown(KEY_A)) visualScale = std::max(10000.0, visualScale - 5000.0);
if (IsKeyDown(KEY_D)) visualScale = std::min(500000.0, visualScale + 5000.0);
if (autoRunning) {
timeAngle += autoSpeed * dt;
simulationTime += dt;
Vector3 pos = {
(float)(orbitRadius * cos(timeAngle)),
0.0f,
(float)(orbitRadius * sin(timeAngle))
};
if (earthTrajectory.empty() || magnitude(Vector3{
earthTrajectory.back().x - pos.x,
earthTrajectory.back().y - pos.y,
earthTrajectory.back().z - pos.z
}) > 0.1f) {
earthTrajectory.push_back(pos);
if (earthTrajectory.size() > 200) earthTrajectory.erase(earthTrajectory.begin());
}
}
// Câmera com mouse
static bool dragging = false;
static int lastMouseX = 0, lastMouseY = 0;
if (IsMouseButtonDown(MOUSE_LEFT_BUTTON)) {
int mx = GetMouseX(), my = GetMouseY();
if (!dragging) { dragging = true; lastMouseX = mx; lastMouseY = my; }
int dx = mx - lastMouseX;
int dy = my - lastMouseY;
camYaw += dx * 0.1f;
camPitch += dy * 0.08f;
camPitch = (float)clampd(camPitch, -89.0, 89.0);
lastMouseX = mx; lastMouseY = my;
} else {
dragging = false;
}
float wheel = GetMouseWheelMove();
if (wheel != 0.0f) {
camDistance -= wheel * 1.5f;
camDistance = (float)clampd(camDistance, 5.0, 300.0);
}
// Ajustar câmera por modo de visualização
if (viewMode == VIEW_TOP) {
camPitch = -89.0f;
camYaw = 0.0f;
} else if (viewMode == VIEW_SIDE) {
camPitch = 0.0f;
camYaw = 90.0f;
}
// Posição da câmera
float yawRad = camYaw * DEG2RAD;
float pitchRad = camPitch * DEG2RAD;
Vector3 camPos;
camPos.x = cameraTarget.x + camDistance * cosf(pitchRad) * cosf(yawRad);
camPos.y = cameraTarget.y + camDistance * sinf(pitchRad);
camPos.z = cameraTarget.z + camDistance * cosf(pitchRad) * sinf(yawRad);
Camera3D camera = {};
camera.position = camPos;
camera.target = cameraTarget;
camera.up = {0.0f, 1.0f, 0.0f};
camera.fovy = 45.0f;
camera.projection = CAMERA_PERSPECTIVE;
// Cálculos de posição
Star ¤tStar = stars[selectedStar];
Vector3 starPosAU = starPositionInAU(currentStar);
Vector3 starRenderPos = auToRender(starPosAU, visualScale);
Vector3 earthPos = {
(float)(orbitRadius * cos(timeAngle)),
0.0f,
(float)(orbitRadius * sin(timeAngle))
};
// Desenho
BeginDrawing();
ClearBackground(Color{10, 10, 30, 255});
BeginMode3D(camera);
// Grid de referência
if (showGrid) {
for (int i = -10; i <= 10; i++) {
float pos = i * 2.0f;
DrawLine3D({pos, 0, -20.0f},
{pos, 0, 20.0f},
Color{40, 40, 60, 150});
DrawLine3D({-20.0f, 0, pos},
{20.0f, 0, pos},
Color{40, 40, 60, 150});
}
}
// Sol
DrawSphere({0,0,0}, 0.9f, Color{255,220,0,255});
DrawSphereWires({0,0,0}, 0.91f, 8, 8, Color{255,200,0,100});
// Terra
DrawSphere(earthPos, 0.4f, Color{80,120,255,255});
DrawSphereWires(earthPos, 0.41f, 6, 6, Color{100,150,255,150});
// Linha da Terra ao Sol
DrawLine3D({0,0,0}, earthPos, Color{255,255,255,80});
// Órbita
if (showOrbit) {
const int ORBIT_SEGMENTS = 128;
for (int i=0; i<ORBIT_SEGMENTS; i++) {
float a1 = (float)i/ORBIT_SEGMENTS * 2.0f * M_PI;
float a2 = (float)(i+1)/ORBIT_SEGMENTS * 2.0f * M_PI;
Vector3 p1 = {
(float)(orbitRadius * cos(a1)),
0.0f,
(float)(orbitRadius * sin(a1))
};
Vector3 p2 = {
(float)(orbitRadius * cos(a2)),
0.0f,
(float)(orbitRadius * sin(a2))
};
DrawLine3D(p1, p2, Color{100,100,150,150});
}
}
// Trajetória da Terra
if (showTrajectory && earthTrajectory.size() > 1) {
for (size_t i = 0; i < earthTrajectory.size() - 1; i++) {
DrawLine3D(earthTrajectory[i], earthTrajectory[i+1], Color{255,255,0,120});
}
}
// Todas as estrelas
for (size_t i = 0; i < stars.size(); i++) {
Star &s = stars[i];
Vector3 sPosAU = starPositionInAU(s);
Vector3 sRenderPos = auToRender(sPosAU, visualScale);
Color col = s.color;
if (i != selectedStar) {
col.a = 80;
}
DrawSphere(sRenderPos, s.size, col);
if (showLabels && i == selectedStar) {
DrawLine3D(earthPos, sRenderPos, Color{255,255,255,60});
}
}
// Observações capturadas
for (size_t i = 0; i < observations.size(); i++) {
Observation &obs = observations[i];
DrawSphere(obs.earthPos, 0.25f, obs.color);
DrawLine3D(obs.earthPos, starRenderPos, Color{obs.color.r, obs.color.g, obs.color.b, 80});
}
// Triângulo de medição
if (showMeasurement && observations.size() >= 2) {
Observation &obsA = observations.front();
Observation &obsB = observations.back();
DrawLine3D(obsA.earthPos, obsB.earthPos, Color{255,0,255,200});
DrawLine3D(obsA.earthPos, starRenderPos, Color{255,100,255,200});
DrawLine3D(obsB.earthPos, starRenderPos, Color{255,100,255,200});
}
EndMode3D();
// Interface 2D
int yPos = 10;
// Painel de ajuda
if (showHelp) {
DrawRectangle(10, yPos, 320, 460, Color{0, 0, 0, 180});
DrawRectangleLines(10, yPos, 320, 460, Color{100, 100, 150, 255});
yPos += 10;
DrawText("CONTROLES (H: toggle)", 20, yPos, 16, YELLOW); yPos += 25;
DrawText("Setas: Mover Terra na orbita", 20, yPos, 14, WHITE); yPos += 20;
DrawText("Up/Down: Dist. estrela (pc)", 20, yPos, 14, WHITE); yPos += 20;
DrawText("A/D: Escala visual", 20, yPos, 14, WHITE); yPos += 20;
DrawText("Space: Pausar/Retomar", 20, yPos, 14, WHITE); yPos += 20;
DrawText("C: Capturar observacao", 20, yPos, 14, LIME); yPos += 20;
DrawText("X: Remover ultima obs.", 20, yPos, 14, ORANGE); yPos += 20;
DrawText("M: Calcular paralaxe", 20, yPos, 14, MAGENTA); yPos += 20;
DrawText("R: Reset", 20, yPos, 14, RED); yPos += 25;
DrawText("1/2/3: Selecionar estrela", 20, yPos, 14, WHITE); yPos += 20;
DrawText("F1/F2/F3: Modo 3D/Top/Side", 20, yPos, 14, WHITE); yPos += 20;
DrawText("G: Toggle grid", 20, yPos, 14, WHITE); yPos += 20;
DrawText("O: Toggle orbita", 20, yPos, 14, WHITE); yPos += 20;
DrawText("L: Toggle labels", 20, yPos, 14, WHITE); yPos += 20;
DrawText("P: Toggle trajetoria", 20, yPos, 14, WHITE); yPos += 20;
DrawText("T: Toggle stats", 20, yPos, 14, WHITE); yPos += 25;
DrawText("Mouse: Rotacionar camera", 20, yPos, 14, SKYBLUE); yPos += 20;
DrawText("Scroll: Zoom", 20, yPos, 14, SKYBLUE); yPos += 25;
DrawText("DICA: Capture observacoes", 20, yPos, 12, YELLOW); yPos += 17;
DrawText("em posicoes opostas da", 20, yPos, 12, YELLOW); yPos += 17;
DrawText("orbita para melhor precisao!", 20, yPos, 12, YELLOW);
}
// Painel de estatísticas
if (showStats) {
int statX = screenWidth - 360;
int statY = 10;
DrawRectangle(statX, statY, 350, 340, Color{0, 0, 0, 180});
DrawRectangleLines(statX, statY, 350, 340, Color{100, 100, 150, 255});
statY += 10;
DrawText("ESTATISTICAS (T: toggle)", statX + 10, statY, 16, YELLOW); statY += 25;
DrawText(TextFormat("Estrela: %s", currentStar.name.c_str()), statX + 10, statY, 14, currentStar.color); statY += 20;
DrawText(TextFormat("Dist. real: %.3f pc", currentStar.distance_pc), statX + 10, statY, 14, WHITE); statY += 20;
DrawText(TextFormat(" %.2f anos-luz", currentStar.distance_pc / LIGHT_YEAR_TO_PC), statX + 10, statY, 14, GRAY); statY += 20;
DrawText(TextFormat("Escala: %.0f AU/unid", visualScale), statX + 10, statY, 14, WHITE); statY += 20;
DrawText(TextFormat("Tempo: %.1fs", simulationTime), statX + 10, statY, 14, WHITE); statY += 20;
DrawText(TextFormat("Auto: %s", autoRunning ? "SIM" : "NAO"), statX + 10, statY, 14, autoRunning ? LIME : RED); statY += 20;
DrawText(TextFormat("Observacoes: %d/%d", (int)observations.size(), maxObservations), statX + 10, statY, 14, YELLOW); statY += 25;
if (measurementValid) {
DrawText("MEDICAO:", statX + 10, statY, 16, MAGENTA); statY += 25;
DrawText(TextFormat("Paralaxe: %.6f\"", measuredParallax), statX + 10, statY, 14, WHITE); statY += 20;
DrawText(TextFormat("Dist. calc.: %.3f pc", estimatedDistance), statX + 10, statY, 14, WHITE); statY += 20;
DrawText(TextFormat(" %.2f anos-luz", estimatedDistance / LIGHT_YEAR_TO_PC), statX + 10, statY, 14, GRAY); statY += 20;
Color errorColor = errorPercent < 5 ? LIME : errorPercent < 15 ? YELLOW : errorPercent < 30 ? ORANGE : RED;
DrawText(TextFormat("Erro: %.2f%%", errorPercent), statX + 10, statY, 14, errorColor); statY += 25;
if (errorPercent < 5) {
DrawText("Excelente precisao!", statX + 10, statY, 12, LIME);
} else if (errorPercent < 15) {
DrawText("Boa precisao!", statX + 10, statY, 12, YELLOW);
} else {
DrawText("Tente observacoes opostas", statX + 10, statY, 12, ORANGE);
}
}
}
// Barra de status inferior
DrawRectangle(0, screenHeight - 30, screenWidth, 30, Color{0, 0, 0, 200});
std::ostringstream status;
status << "Angulo orbital: " << std::fixed << std::setprecision(1) << (timeAngle * 180.0 / M_PI) << "°";
status << " | Camera: " << (viewMode == VIEW_3D ? "3D" : viewMode == VIEW_TOP ? "TOP" : "SIDE");
status << " | Zoom: " << std::setprecision(0) << camDistance;
DrawText(status.str().c_str(), 10, screenHeight - 25, 14, LIGHTGRAY);
// Instruções contextuais
if (observations.empty()) {
DrawText("Pressione C para capturar a primeira observacao!", screenWidth/2 - 220, screenHeight - 60, 16, YELLOW);
} else if (observations.size() == 1) {
DrawText("Mova a Terra (180° oposto) e pressione C para segunda observacao!", screenWidth/2 - 300, screenHeight - 60, 16, YELLOW);
} else if (!measurementValid) {
DrawText("Pressione M para calcular a paralaxe!", screenWidth/2 - 180, screenHeight - 60, 16, LIME);
} else {
DrawText(TextFormat("Paralaxe medida: %.6f\" | Dist: %.3f pc (Erro: %.1f%%)",
measuredParallax, estimatedDistance, errorPercent),
screenWidth/2 - 300, screenHeight - 60, 14, LIME);
}
EndDrawing();
}
CloseWindow();
return 0;
}