Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
1940 lines (1409 loc) · 52.5 KB
/
Copy pathmain.py
File metadata and controls
1940 lines (1409 loc) · 52.5 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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
UNIVERSE SIMULATOR
==================
A to-scale, physically grounded model of the universe from the Big
Bang to a billion years beyond the present day, flown in real time.
What is actually simulated
--------------------------
- Flat LambdaCDM expansion, integrated numerically from the Friedmann
equation. Scale factor, redshift, comoving distance, horizon size
and CMB temperature all come out of that one integration.
- The thermal history of the early universe, from the Planck epoch
through nucleosynthesis and recombination to reionisation.
- A galaxy catalogue drawn from a cold dark matter halo mass function,
with morphologies, sizes, black holes and formation epochs set by
the scaling relations they obey in surveys, laid out along a cosmic
web of filaments and voids.
- Stellar populations sampled from the Kroupa initial mass function
with formation times following the cosmic star formation history.
Luminosities, radii and temperatures are mutually consistent through
the Stefan-Boltzmann law, and star colours are the true CIE colours
of their Planck spectra.
- Stellar evolution: main sequence lifetimes from the nuclear
timescale, the giant branch, and remnants - white dwarfs cooling by
Mestel's law, neutron stars, and black holes.
- Supernovae: Types Ia, II and Ib/c, hypernovae and pair-instability
explosions, with light curves powered by the Ni-56 to Co-56 to Fe-56
decay chain.
- Quasars: Eddington-limited accretion onto supermassive black holes,
with a duty cycle that peaks at cosmic noon and has faded by two
orders of magnitude today.
- Planetary systems by core accretion, with Keplerian orbits solved
exactly, including the relativistic precession of the perihelion.
Running it
----------
pip install ursina numpy
python3 main.py
Controls are listed on screen; press H to hide them.
"""
import argparse
import sys
import time as wallclock
import numpy as np
from ursina import (
Ursina,
Entity,
Text,
Vec2,
Vec3,
application,
camera,
color,
held_keys,
mouse,
window,
)
import panda3d.core as p3d
from simulation_constants import (
C,
SUN_RADIUS,
T_RECOMBINATION,
RANDOM_SEED,
STAR_COUNT,
GALAXY_COUNT,
YEAR,
MYR,
GYR,
AU,
PARSEC,
MPC,
SUN_RADIUS,
EARTH_RADIUS,
)
from simulation_kernel import SimulationKernel
from cosmology.expansion.scale_factor import describe_epoch
from cosmology.bigbang import (
radiation_temperature,
cmb_glow_intensity,
)
from renderer import (
format_distance,
make_point_shader,
LIGHT_YEAR,
)
from renderer.star_field import StarField
from renderer.galaxy_lod import GalaxyField
from renderer.nearby_objects import NearbyObjects, DETAIL_RANGE_METRES
from renderer.black_holes import jet_length_metres
from renderer.lensing import LensingPass, make_overlay_camera
from stellar_pop.stellar_evolution.blackbody import temperature_to_rgb, spectral_class
from stellar_pop.stellar_evolution.population import (
PHASE_MAIN_SEQUENCE,
PHASE_GIANT,
PHASE_REMNANT,
PHASE_NAMES,
)
from stellar_pop.stellar_evolution.relations import (
FATE_NAMES,
FATE_BLACK_HOLE,
FATE_DIRECT_COLLAPSE,
)
from compact_objects.black_holes import shadow_radius, gravitational_radius
from compact_objects.quasars import jet_power
PARSEC_PER_MPC = 1.0e6
# How often the HUD text is rebuilt. Reformatting a dozen strings every
# frame is pure waste; ten times a second is smoother than the eye.
HUD_INTERVAL = 0.1
# Galaxies evolve on hundred-million-year timescales, so their vertex
# buffer does not need rebuilding at frame rate.
GALAXY_REFRESH_INTERVAL = 20.0 * MYR
# ============================================================
# Command line
# ============================================================
def parse_arguments(argv=None):
parser = argparse.ArgumentParser(
prog="main.py",
description="A to-scale simulation of the universe, from the Big Bang on.",
)
parser.add_argument(
"--stars",
type=int,
default=STAR_COUNT,
help="stars rendered for the host galaxy (default: %(default)s)",
)
parser.add_argument(
"--galaxies",
type=int,
default=GALAXY_COUNT,
help="galaxies in the catalogue (default: %(default)s)",
)
parser.add_argument(
"--seed", type=int, default=RANDOM_SEED, help="random seed"
)
parser.add_argument(
"--benchmark",
type=int,
metavar="FRAMES",
default=0,
help="fly a fixed path for FRAMES frames, report the frame rate, and exit",
)
parser.add_argument(
"--screenshot",
metavar="PATH",
default=None,
help="render a few frames, save an image, and exit",
)
parser.add_argument(
"--view",
choices=(
"disc",
"galaxy",
"cosmic",
"system",
"star",
"blackhole",
"quasar",
"planet",
),
default=None,
help=(
"start from a particular vantage point: inside the galactic "
"disc, outside the whole galaxy, far enough out to see the "
"cosmic web, or beside a planetary system"
),
)
parser.add_argument(
"--standoff",
type=float,
metavar="RADII",
default=3.0,
help=(
"how far to stand off in --view star (stellar radii) or "
"--view blackhole / --view quasar (gravitational radii, "
"default 120)"
),
)
parser.add_argument(
"--age",
type=float,
metavar="GYR",
default=None,
help="start at this cosmic age in billions of years (0 is the Big Bang)",
)
parser.add_argument(
"--memory-limit",
type=float,
metavar="MB",
default=3072.0,
help=(
"abort if resident memory exceeds this (default: %(default)s MB; "
"normal use is well under 600). 0 disables the check."
),
)
parser.add_argument(
"--stress",
type=float,
metavar="SECONDS",
default=0.0,
help=(
"hold full-boost travel for this long while logging memory, "
"threads and frame time; for finding runaway behaviour"
),
)
parser.add_argument(
"--selftest",
action="store_true",
help="press every control in turn, report any failures, and exit",
)
parser.add_argument(
"--no-vsync",
action="store_true",
help="uncap the frame rate (use with --benchmark)",
)
parser.add_argument(
"--windowed",
type=str,
metavar="WxH",
default=None,
help="window size, for example 1600x900",
)
return parser.parse_args(argv)
options = parse_arguments()
# ============================================================
# Startup
# ============================================================
def banner():
print()
print("=" * 62)
print(" UNIVERSE SIMULATOR")
print("=" * 62)
print()
banner()
kernel = SimulationKernel(
seed=options.seed,
galaxy_count=options.galaxies,
star_count=options.stars,
)
_start = wallclock.perf_counter()
kernel.initialize(progress=lambda message: print(f" {message}"))
print(f"\n Built in {wallclock.perf_counter() - _start:.2f} s")
report = kernel.population_report()
for name, value in report.items():
print(f" {name:>16}: {value:,}")
print()
# ============================================================
# Window
# ============================================================
_window_size = None
if options.windowed:
try:
width, height = (int(v) for v in options.windowed.lower().split("x"))
_window_size = (width, height)
except ValueError:
print(f" Ignoring unreadable window size {options.windowed!r}")
_headless = bool(
options.benchmark or options.screenshot or options.selftest or options.stress
)
app = Ursina(
title="Universe Simulator",
borderless=False,
fullscreen=False,
vsync=not (options.no_vsync or options.benchmark),
development_mode=False,
**({"size": _window_size} if _window_size else {}),
)
window.color = color.black
window.exit_button.visible = False
window.fps_counter.enabled = False
camera.fov = 70
camera.position = Vec3(0, 0, 0)
camera.rotation = Vec3(0, 0, 0)
# The compression puts the edge of the observable universe at about
# 107 render units, so the far plane only has to clear that.
#
# The near plane cannot simply be made tiny to match. Past a near/far
# ratio of roughly a million the projection matrix loses the
# precision to separate the two and *everything* silently vanishes -
# which is what a near plane of 1e-5 against a far plane of 300 was
# doing to every solid body in the scene.
#
# 1.6e-4 keeps the ratio safe and corresponds to about fifty metres
# in front of the camera, which is closer than anything here is ever
# looked at. Depth precision itself does not matter: the star fields
# blend additively and the near-field bodies are drawn back to front,
# so depth testing is off throughout.
camera.clip_plane_near = 1.6e-4
camera.clip_plane_far = 160.0
# ============================================================
# Renderers
# ============================================================
point_shader = make_point_shader()
galaxy_field = GalaxyField(kernel.catalogue, kernel.expansion, shader=point_shader)
star_field = StarField(kernel.population, shader=point_shader)
nearby = NearbyObjects(overlay_discs=True)
# Gravitational lensing needs the scene in a texture before it can
# bend it, so this reroutes the whole 3D render through an offscreen
# buffer. The HUD is drawn separately and is unaffected.
lensing = LensingPass(
application.base, application.base.cam, application.base.render
)
# Accretion discs bend themselves, in their own vertex shaders, and so
# are drawn over the finished frame instead of through the filter.
overlay_camera = make_overlay_camera(application.base)
# The primordial fireball, painted over the whole sky before the
# universe turns transparent.
fireball = Entity(
parent=camera.ui,
model="quad",
scale=(4, 4),
# Behind every HUD panel: before recombination the sky really is
# an opaque wall of light, and the readout explaining why is the
# one thing that still has to be legible through it.
z=1.0,
color=color.rgba32(0, 0, 0, 0),
enabled=False,
)
# Ursina's UI layer ignores z ordering between siblings, so draw
# order is set explicitly by bin: the fireball first, every readable
# panel after it.
fireball.setBin("fixed", 0)
fireball.setDepthWrite(False)
fireball.setDepthTest(False)
# ============================================================
# Observer control
# ============================================================
class Flight:
"""
A six-degree-of-freedom camera.
The camera never actually moves: it sits at the origin and only
turns. Travel changes the observer's position in the simulation,
which the point shaders read as a uniform. That is what makes
crossing a billion light years cost the same as standing still.
"""
def __init__(self, kernel, capture_mouse=True):
self.kernel = kernel
self.yaw = 0.0
self.pitch = 0.0
self.roll = 0.0
self.sensitivity = 40.0
self.boost = 1.0
mouse.locked = capture_mouse
def basis(self):
forward = camera.forward
right = camera.right
up = camera.up
return (
np.array([forward.x, forward.y, forward.z]),
np.array([right.x, right.y, right.z]),
np.array([up.x, up.y, up.z]),
)
def update(self, dt):
if mouse.locked:
self.yaw += mouse.velocity[0] * self.sensitivity * 25.0
self.pitch -= mouse.velocity[1] * self.sensitivity * 25.0
self.pitch = max(-89.5, min(89.5, self.pitch))
roll_input = held_keys["e"] - held_keys["q"]
self.roll += roll_input * 60.0 * dt
camera.rotation = Vec3(self.pitch, self.yaw, self.roll)
forward, right, up = self.basis()
direction = (
forward * (held_keys["w"] - held_keys["s"])
+ right * (held_keys["d"] - held_keys["a"])
+ up * (held_keys["r"] - held_keys["f"])
)
magnitude = float(np.linalg.norm(direction))
if magnitude < 1.0e-6:
self.kernel.observer.velocity_c = 0.0
return
direction = direction / magnitude
boost = 10.0 if held_keys["shift"] else 1.0
boost *= 0.08 if held_keys["control"] else 1.0
self.kernel.move_observer(direction, dt, boost=boost)
def look_at_universe_point(self, offset):
"""
Aim at something, given its offset from the observer in
universe axes.
"""
offset = np.asarray(offset, dtype=np.float64)
norm = float(np.linalg.norm(offset))
if norm < 1.0e-12:
return
d = offset / norm
self.yaw = float(np.degrees(np.arctan2(d[0], d[2])))
self.pitch = float(np.degrees(np.arcsin(-np.clip(d[1], -1.0, 1.0))))
flight = Flight(kernel, capture_mouse=not _headless)
# ============================================================
# Heads-up display
# ============================================================
# Ursina's UI space runs from -0.5 to 0.5 vertically and from
# -aspect/2 to +aspect/2 horizontally, so the horizontal edges move
# with the window shape and have to be computed rather than guessed.
HUD_MARGIN = 0.015
def ui_edges():
half_width = window.aspect_ratio * 0.5 - HUD_MARGIN
return -half_width, half_width, 0.5 - HUD_MARGIN, -0.5 + HUD_MARGIN
def make_text(corner, size=0.7, shade=(236, 243, 255, 255)):
"""
corner is one of "top left", "top right", "bottom left",
"bottom right" or "mid right". Bottom-anchored panels grow upward,
so a long block never runs off the screen.
"""
left, right, top, bottom = ui_edges()
origin_x = -0.5 if "left" in corner else 0.5
x = left if "left" in corner else right
if corner.startswith("bottom"):
origin_y, y = -0.5, bottom
elif corner.startswith("mid"):
origin_y, y = 0.5, -0.05
else:
origin_y, y = 0.5, top
element = Text(
text="",
parent=camera.ui,
x=x,
y=y,
origin=(origin_x, origin_y),
scale=size,
color=color.rgba32(*shade),
font="VeraMono.ttf",
)
element.hud_corner = corner
return element
hud_left = make_text("top left")
hud_right = make_text("top right")
hud_target = make_text("bottom left")
hud_events = make_text("mid right", shade=(255, 196, 110, 255))
help_text = make_text("bottom right", size=0.62, shade=(160, 178, 208, 235))
HUD_PANELS = (hud_left, hud_right, hud_target, hud_events, help_text)
def layout_hud():
"""
Reposition every panel. Called on startup and whenever the window
changes shape.
"""
left, right, top, bottom = ui_edges()
for element in HUD_PANELS:
corner = element.hud_corner
element.x = left if "left" in corner else right
if corner.startswith("bottom"):
element.y = bottom
elif corner.startswith("mid"):
element.y = -0.05
else:
element.y = top
HELP_TEXT = (
"W A S D fly R / F up / down Q / E roll\n"
"SHIFT faster CTRL slower MOUSE look\n"
"1 2 3 4 jump +1 / +10 / +100 Myr, +1 Gyr\n"
"SHIFT + 1 2 3 4 the same, backwards\n"
"B Big Bang P present day SPACE pause\n"
"T / G time rate X detonate a star N next star\n"
"C go to a star V go to a galaxy TAB hide HUD\n"
"M go to a black hole K go to a quasar\n"
"H hide this ESC release mouse F10 quit"
)
help_text.text = HELP_TEXT
reticle = Text(
text="+",
parent=camera.ui,
origin=(0, 0),
scale=0.9,
color=color.rgba32(160, 190, 230, 120),
)
# Colours below are 0-255 per channel, so they go through
# color.rgba32; Ursina's color.rgba takes 0-1 floats and silently
# clips anything larger to white.
#
# Panel colours for a dark sky and for a bright one. Before
# recombination the sky is a solid wall of light - correctly so, the
# universe was opaque - and that is exactly the moment the readout
# explaining why has to stay legible, so the HUD inverts.
HUD_DARK_SKY = {
id(hud_left): (236, 243, 255, 255),
id(hud_right): (236, 243, 255, 255),
id(hud_target): (226, 236, 252, 255),
id(hud_events): (255, 196, 110, 255),
id(help_text): (160, 178, 208, 235),
}
HUD_BRIGHT_SKY = {
id(hud_left): (20, 22, 30, 245),
id(hud_right): (20, 22, 30, 245),
id(hud_target): (20, 22, 30, 245),
id(hud_events): (90, 30, 0, 245),
id(help_text): (55, 60, 75, 225),
}
# Ursina's UI layer does not order siblings by z, so draw order is set
# explicitly by bin: the fireball first, every panel after it.
for _panel in HUD_PANELS:
_panel.setBin("fixed", 100)
reticle.setBin("fixed", 100)
_hud_palette = {"current": HUD_DARK_SKY}
def set_hud_contrast(bright_sky):
_hud_palette["current"] = HUD_BRIGHT_SKY if bright_sky else HUD_DARK_SKY
for element in HUD_PANELS:
write_panel(element, element.text)
reticle.color = (
color.rgba32(40, 40, 50, 160) if bright_sky else color.rgba32(160, 190, 230, 120)
)
def write_panel(element, text):
"""
Set a panel's text and its colour together.
Ursina rebuilds a Text's geometry when its string changes, so the
colour has to be reapplied alongside it or the panel reverts to
whatever it was built with.
"""
element.text = text
element.color = color.rgba32(*_hud_palette["current"][id(element)])
layout_hud()
# ============================================================
# Selection and travel
# ============================================================
class Selection:
def __init__(self):
self.star_index = None
self.system = None
def select(self, index):
self.star_index = None if index is None else int(index)
self.system = (
None if self.star_index is None else kernel.planetary_system(self.star_index)
)
def clear(self):
self.star_index = None
self.system = None
selection = Selection()
def observer_offset_to_star_m(index):
"""
Vector from the observer to a star, in metres.
"""
delta = kernel.population.position_pc[index].astype(np.float64)
return (delta - kernel.observer.position_pc) * PARSEC
def match_time_rate_to_system(index):
"""
Set the clock so the innermost planet takes about half a minute
to go round.
A million years a second is the right rate for watching stars
live and die, and hopeless for watching a planet orbit: at that
speed an inner world completes twenty million orbits a second
and is simply a blur. Arriving somewhere should set a clock that
suits what is there.
"""
system = kernel.planetary_system(int(index))
if not system.planets:
return
shortest = min(planet.period_seconds for planet in system.planets)
kernel.time_rate = max(shortest / YEAR / 30.0, 1.0e-6)
def travel_to_star(index, standoff_au=800.0):
"""
Place the observer just outside a star system and look at it.
"""
index = int(index)
target_pc = kernel.population.position_pc[index].astype(np.float64)
standoff_pc = standoff_au * AU / PARSEC
direction = np.array([0.6, 0.35, 0.72])
direction /= np.linalg.norm(direction)
kernel.observer.position_pc = target_pc - direction * standoff_pc
selection.select(index)
match_time_rate_to_system(index)
flight.look_at_universe_point(direction)
def travel_to_galaxy(index=None):
"""
Cross intergalactic space to another galaxy.
"""
catalogue = kernel.catalogue
if index is None:
alive = np.flatnonzero(
(catalogue["halo_mass"] > 0)
& (catalogue["formation_time"] <= kernel.cosmic_time)
)
if alive.size == 0:
return
index = int(kernel.rng.choice(alive))
kernel.observer.galaxy_index = int(index)
radius_pc = float(catalogue["radius"][index]) / PARSEC
kernel.observer.position_pc = np.array([0.0, 0.6, -3.0]) * max(radius_pc, 1.0e3)
kernel.population = kernel._build_population_at(int(index), kernel.cosmic_time)
rebuild_star_field()
selection.clear()
flight.look_at_universe_point(-kernel.observer.position_pc)
def rebuild_star_field():
"""
Point the star field at a new host galaxy.
"""
star_field.rebind(kernel.population)
def black_hole_standoff():
"""
Viewing distance from a black hole, in gravitational radii.
Scale-invariant: the same number frames a ten-solar-mass hole and
a billion-solar-mass one identically, because every feature of a
black hole scales with its mass.
"""
if options.standoff and options.standoff != 3.0:
return float(options.standoff)
return 120.0
def go_to_planet():
"""
Park a few planetary radii from the largest world of a nearby
system, off to one side of the star so the terminator shows.
"""
population = kernel.population
for candidate in population.massive_living_stars(0.6)[:600]:
system = kernel.planetary_system(int(candidate))
if not system.planets:
continue
planet = max(system.planets, key=lambda p: p.radius_earth)
slot = system.planets.index(planet)
star_pc = population.position_pc[int(candidate)].astype(np.float64)
local = system.positions_at(kernel.cosmic_time)[slot]
planet_pc = star_pc + local / PARSEC
radius_m = planet.radius_earth * EARTH_RADIUS
# Stand off across the star-planet line, so roughly half the
# disc is in daylight and half in shadow.
away = local / max(float(np.linalg.norm(local)), 1.0e-9)
side = np.cross(away, np.array([0.0, 1.0, 0.0]))
side /= max(float(np.linalg.norm(side)), 1.0e-9)
approach = away * 0.5 + side * 0.87
approach /= np.linalg.norm(approach)
# Same convention as travel_to_star: sit back along the
# approach vector and look forward down it.
kernel.observer.position_pc = planet_pc - approach * (
4.0 * radius_m / PARSEC
)
selection.select(int(candidate))
match_time_rate_to_system(int(candidate))
# Standing four planetary radii off a world, the world itself
# is moving tens of kilometres a second along its orbit: at
# any rate fast enough to watch the orbit, it leaves the frame
# before it can be looked at. Close inspection means a stopped
# clock, until the observer can be put in the planet's own
# frame of reference.
kernel.paused = True
flight.look_at_universe_point(approach)
return
def go_to_black_hole():
"""
Travel to the nearest feeding stellar-mass black hole, or failing
that the nearest one of any kind.
"""
target = kernel.nearest_feeding_black_hole()
if target is None:
holes = kernel.nearby_black_holes(limit=1, max_distance_m=1.0e22)
if not holes:
return
target = holes[0]["index"]
population = kernel.population
mass = float(population.remnant_mass[target])
# Far enough out that the disc and the inner jets both fit.
standoff_m = black_hole_standoff() * float(gravitational_radius(mass))
target_pc = population.position_pc[target].astype(np.float64)
direction = np.array([0.35, 0.62, 0.70])
direction /= np.linalg.norm(direction)
kernel.observer.position_pc = target_pc - direction * (standoff_m / PARSEC)
selection.select(int(target))
flight.look_at_universe_point(direction)
def go_to_quasar():
"""
Travel to the brightest active galactic nucleus in the catalogue.
"""
index = kernel.brightest_active_nucleus()
if index is None:
return
travel_to_galaxy(index)
mass = float(kernel.catalogue["smbh_mass"][index])
standoff_m = black_hole_standoff() * float(gravitational_radius(mass))
direction = np.array([0.3, 0.55, 0.78])
direction /= np.linalg.norm(direction)
kernel.observer.position_pc = direction * (standoff_m / PARSEC) * -1.0
flight.look_at_universe_point(-kernel.observer.position_pc)
def cycle_interesting_star():
"""
Step through the most luminous stars nearby.
"""
population = kernel.population
alive = (population.phase == PHASE_MAIN_SEQUENCE) | (
population.phase == PHASE_GIANT
)
candidates = np.flatnonzero(alive & (population.luminosity > 1_000.0))
if candidates.size == 0:
candidates = np.flatnonzero(alive)
if candidates.size == 0:
return
delta = population.position_pc[candidates] - kernel.observer.position_pc.astype(
np.float32
)
order = np.argsort(np.einsum("ij,ij->i", delta, delta))
ranked = candidates[order[:64]]
if selection.star_index is None or selection.star_index not in ranked:
selection.select(int(ranked[0]))
else:
position = int(np.flatnonzero(ranked == selection.star_index)[0])
selection.select(int(ranked[(position + 1) % len(ranked)]))
flight.look_at_universe_point(observer_offset_to_star_m(selection.star_index))
# ============================================================
# Input
# ============================================================
show_hud = True
show_help = True
TIME_JUMPS = {
"1": 1.0 * MYR,
"2": 10.0 * MYR,
"3": 100.0 * MYR,
"4": 1.0 * GYR,
}
def apply_time_jump(seconds):
kernel.jump_to(kernel.cosmic_time + seconds)
on_universe_changed(full=True)
def on_universe_changed(full=False):
"""
Called after anything that invalidates the whole render state.
"""
star_field.refresh_all()
galaxy_field.update(kernel.cosmic_time, kernel.quasar_luminosity)
_galaxy_clock["last"] = kernel.cosmic_time
_galaxy_clock["real"] = now_seconds()
def input(key):
global show_hud, show_help
back = held_keys["shift"]
if key in TIME_JUMPS:
apply_time_jump(-TIME_JUMPS[key] if back else TIME_JUMPS[key])
elif key == "space":
kernel.paused = not kernel.paused
elif key == "b":
kernel.go_to_big_bang()
on_universe_changed(full=True)
elif key == "p":
kernel.go_to_present()
on_universe_changed(full=True)
elif key == "t":
kernel.cycle_time_rate(10.0)
elif key == "g":
kernel.cycle_time_rate(0.1)
elif key == "x":
result = kernel.force_supernova(selection.star_index)
if result is None and selection.star_index is not None:
# The selected star cannot explode; fall back to the