Repository navigation
Expand file tree
/
Copy pathSourcebox.py
More file actions
executable file
·666 lines (539 loc) · 25.3 KB
/
Copy pathSourcebox.py
File metadata and controls
executable file
·666 lines (539 loc) · 25.3 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
import sys
# The demo-detection worker is this same program relaunched with a flag. Handle
# it before the heavy graphics imports so the worker starts fast and stays small.
if "--demo-scan-worker" in sys.argv:
from sourcebox.demo_watcher import WORKER_FLAG, run_scan_worker, _lower_priority
_lower_priority()
run_scan_worker(int(sys.argv[sys.argv.index(WORKER_FLAG) + 1]), sys.stdout)
sys.exit(0)
# The cleanup guard is also this program relaunched: it waits for SourceBox to
# exit, however it exits, then removes the files SourceBox installed into games.
if "--cleanup-guard" in sys.argv:
from sourcebox.install_manifest import GUARD_FLAG, run_cleanup_guard
run_cleanup_guard(int(sys.argv[sys.argv.index(GUARD_FLAG) + 1]))
sys.exit(0)
import pygame
import os
import sys
import time
from pygame.locals import *
from OpenGL.GL import *
from OpenGL.GLU import *
import platform
from cone_scene import ConeScene
from rendering_helpers import PIL_AVAILABLE, pil_load_image_rgba
from sourcebox.audio import SoundManager
from sourcebox.bridges import BridgeManager
from sourcebox.cursor import CursorRenderer
from sourcebox.demo_watcher import DemoWatcher
from sourcebox.diagnostics import configure_runtime_diagnostics
from sourcebox.install_manifest import start_cleanup_guard
from sourcebox.raycast import RayCaster
from sourcebox.rendering.antialias import MultisampleTarget
from sourcebox.rendering.picking import pick
from sourcebox.rendering.main_scene import (
Camera,
Checkerboard,
Light,
Object3D,
SPIN_COLOR,
apply_main_projection,
draw_sphere_shadow,
)
from sourcebox.resources import find_resource
from sourcebox.scenes.missing_texture import MissingTextureScene
# platform detection
OPERATING_SYSTEM = platform.system()
# hide console window on windows
if OPERATING_SYSTEM == 'Windows':
try:
import ctypes
ctypes.windll.user32.ShowWindow(ctypes.windll.kernel32.GetConsoleWindow(), 0)
except:
pass
# import source_bridge conditionally
try:
from source_bridge import SourceBridge, WINDOWS_API_AVAILABLE
BRIDGE_AVAILABLE = True
except ImportError:
BRIDGE_AVAILABLE = False
WINDOWS_API_AVAILABLE = False
print("Warning: source_bridge not available")
try:
from gmod_bridge import GModBridge
GMOD_BRIDGE_AVAILABLE = True
except ImportError:
GMOD_BRIDGE_AVAILABLE = False
print("Warning: gmod_bridge not available")
def get_display_scale(display_width, display_height):
"""calculate scale factor based on display resolution, base: 1920x1080"""
base_width = 1920.0
base_height = 1080.0
width_scale = display_width / base_width
height_scale = display_height / base_height
scale = min(width_scale, height_scale)
return scale
MULTISAMPLE_SAMPLES = 4
# every frame is drawn here and shown with frame_target.present()
frame_target = MultisampleTarget(MULTISAMPLE_SAMPLES)
def set_display_mode(size, flags=DOUBLEBUF | OPENGL):
"""Open the OpenGL window with multisample anti-aliasing.
Asks for a multisampled window first; if the driver refuses or silently
ignores that, frame_target draws through an offscreen multisampled buffer
instead. Call this for every mode change so the buffer follows the size.
"""
try:
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 1)
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, MULTISAMPLE_SAMPLES)
screen = pygame.display.set_mode(size, flags)
except pygame.error as error:
print(f"Anti-aliasing unavailable ({error}), continuing without it")
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS, 0)
pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES, 0)
screen = pygame.display.set_mode(size, flags)
frame_target.setup(size)
try:
glEnable(GL_MULTISAMPLE)
except Exception:
pass
return screen
def init_pygame():
try:
pygame.init()
# get_desktop_sizes() is more reliable than display.Info() on Linux/Wayland,
# especially after screen lock/unlock where display.Info() can return wrong values
if hasattr(pygame.display, 'get_desktop_sizes'):
desktop_sizes = pygame.display.get_desktop_sizes()
if desktop_sizes:
screen_width, screen_height = desktop_sizes[0]
else:
display_info = pygame.display.Info()
screen_width = display_info.current_w
screen_height = display_info.current_h
else:
display_info = pygame.display.Info()
screen_width = display_info.current_w
screen_height = display_info.current_h
print(f"Detected screen resolution: {screen_width}x{screen_height}")
if screen_width <= 1366 or screen_height <= 768:
display = (int(screen_width * 0.8), int(screen_height * 0.8))
elif screen_width <= 1920 or screen_height <= 1080:
display = (1280, 720)
else:
display = (1600, 900)
print(f"Using display resolution: {display[0]}x{display[1]}")
icon_candidates = [
'assets/images/sourcebox.png',
'assets/images/icon.png',
'assets/images/icon.ico',
'sourcebox.png',
'icon.png'
]
icon_path = find_resource(icon_candidates)
if icon_path:
try:
icon = pygame.image.load(icon_path)
pygame.display.set_icon(icon)
print(f"Icon loaded: {icon_path}")
except Exception as error:
fallback_loaded = False
if PIL_AVAILABLE:
pil_result = pil_load_image_rgba(icon_path, flip_y=False)
if pil_result:
icon_data, width, height = pil_result
try:
icon = pygame.image.frombuffer(icon_data, (width, height), "RGBA")
pygame.display.set_icon(icon)
print(f"Icon loaded: {icon_path}")
fallback_loaded = True
except Exception:
pass
if not fallback_loaded:
print(f"Failed to load icon: {error}")
flags = DOUBLEBUF | OPENGL
screen = set_display_mode(display, flags)
pygame.display.set_caption('SourceBox')
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
glShadeModel(GL_SMOOTH)
glEnable(GL_NORMALIZE)
try:
pygame.display.gl_set_attribute(pygame.GL_SWAP_CONTROL, 1)
except:
pass
glMatrixMode(GL_PROJECTION)
aspect_ratio = display[0] / display[1]
apply_main_projection(aspect_ratio)
glMatrixMode(GL_MODELVIEW)
glClearColor(0.0, 0.0, 0.0, 1.0)
return display, screen
except Exception as e:
print(f"Failed to initialize Pygame/OpenGL: {e}")
sys.exit(1)
def update_object_animation(obj, dt):
if dt <= 0 or dt > 1.0:
return
if obj.is_hovered and not obj.was_hovered:
obj.hover_timer = 0.0
obj.was_hovered = True
elif not obj.is_hovered and obj.was_hovered:
obj.hover_timer = 0.0
obj.scale = obj.base_scale
obj.was_hovered = False
return
if obj.is_hovered:
obj.hover_timer += dt
if obj.hover_timer <= obj.hover_animation_duration:
progress = obj.hover_timer / obj.hover_animation_duration
if progress <= 0.5:
scale_progress = progress * 5.0
obj.scale = obj.base_scale * (1.0 + obj.hover_scale_amount * scale_progress)
else:
scale_progress = (progress - 0.5) * 3.0
obj.scale = obj.base_scale * (1.0 + obj.hover_scale_amount * (1.0 - scale_progress))
else:
obj.scale = obj.base_scale
def draw_object(obj):
if obj.display_list is None:
return
glPushMatrix()
glTranslatef(*obj.position)
if obj.base_rotation[0]:
glRotatef(obj.base_rotation[0], 1, 0, 0)
if obj.base_rotation[1]:
glRotatef(obj.base_rotation[1], 0, 1, 0)
if obj.base_rotation[2]:
glRotatef(obj.base_rotation[2], 0, 0, 1)
lighting_disabled = False
if obj.is_rotating or obj.is_hovered:
glDisable(GL_LIGHTING)
lighting_disabled = True
if obj.is_rotating:
glRotatef(obj.rotation_angle, 0, 0, 1)
sx = obj.scale * obj.scale_xyz[0]
sy = obj.scale * obj.scale_xyz[1]
sz = obj.scale * obj.scale_xyz[2]
glScalef(sx, sy, sz)
if obj.is_rotating:
glColor3f(*SPIN_COLOR)
elif obj.is_hovered:
glColor3f(0.8, 0.0, 0.0)
else:
b = obj.shade()
glColor3f(b, b, b)
if obj.is_rotating:
# the spinning cube leaves no depth, so objects drawn after it (the
# sphere) always show in front of it, as in the reference
glDepthMask(GL_FALSE)
glCallList(obj.display_list)
if obj.is_rotating:
glDepthMask(GL_TRUE)
if lighting_disabled:
glEnable(GL_LIGHTING)
glPopMatrix()
def update_object_rotation(obj, dt):
if dt > 0 and dt <= 1.0 and obj.is_rotating:
obj.rotation_angle = (obj.rotation_angle + 45.0 * dt) % 360.0
def _pick_object(mouse_pos, ray_caster, objects, include_rotating=True):
"""Return the object under the mouse, testing each shape exactly."""
if not objects:
return None
mouse_x, mouse_y = mouse_pos
ray_origin, ray_dir = ray_caster.get_ray_from_mouse(mouse_x, mouse_y)
if ray_origin is None or ray_dir is None:
return None
candidates = [
(obj, obj.type, obj.model_matrix(), obj.is_rotating)
for obj in objects
if include_rotating or not obj.is_rotating
]
return pick(candidates, ray_origin, ray_dir)
def check_object_hover(mouse_pos, ray_caster, objects, sound_manager):
if not objects:
return None
hovered_obj = _pick_object(mouse_pos, ray_caster, objects, include_rotating=False)
for obj in objects:
new_hover_state = (obj == hovered_obj)
if new_hover_state and not obj.is_hovered:
sound_manager.play_sound('hover')
obj.is_hovered = new_hover_state
return hovered_obj
def check_object_click(mouse_pos, ray_caster, objects):
return _pick_object(mouse_pos, ray_caster, objects)
def main():
configure_runtime_diagnostics()
print(f"Running on: {OPERATING_SYSTEM}")
display, _screen = init_pygame()
original_display = display
display_scale = get_display_scale(display[0], display[1])
print(f"Display scale factor: {display_scale:.2f}")
sound_manager = SoundManager()
sound_manager.load_sound('hover', 'assets/sounds/click.wav')
sound_manager.load_sound('cube_click', 'assets/sounds/friend_join.wav')
sound_manager.load_sound('cone_click', 'assets/sounds/cone.wav')
sound_manager.load_sound('cone_back', 'assets/sounds/coneback.wav')
sound_manager.load_music('assets/sounds/sourcebox.dll.mp3')
# sourcebox album version don't start until like 2 sec for some reason but i am keeping it
# until like when person go to voidside tracker or person go back to main menu
# when song restarts, it will start 2 sec later so lol
sound_manager.play_music(loops=-1, volume=0.3)
# before anything is installed, so even a killed SourceBox gets cleaned up
start_cleanup_guard(os.path.abspath(__file__))
bridge_manager = BridgeManager(
SourceBridge if BRIDGE_AVAILABLE else None,
GModBridge if GMOD_BRIDGE_AVAILABLE else None,
platform_name=OPERATING_SYSTEM,
windows_api_available=WINDOWS_API_AVAILABLE,
).initialize()
cursor_renderer = CursorRenderer('assets/images/cursor.png')
cursor_renderer.set_scale(display_scale)
if cursor_renderer.enabled:
pygame.mouse.set_visible(False)
pygame.event.set_grab(False)
objects = [
Object3D("cube",
position=[0.0, 2.059, 0.0],
rotation=[-63.63, -41.49, 9.39],
scale=1.306,
scale_xyz=[1.0, 1.0, 1.0],
brightness=0.796),
Object3D("sphere",
position=[1.274, 2.684, -0.035],
rotation=[0.0, 0.0, 0.0],
scale=1.746,
scale_xyz=[1.0, 1.0, 1.0],
brightness=0.712),
Object3D("cone",
position=[5.691, 5.717, 1.575],
rotation=[156.62, 7.95, 160.26],
scale=1.0,
scale_xyz=[1.0, 1.0, 0.99],
brightness=0.774)
]
camera = Camera()
light = Light()
board = Checkerboard()
ray_caster = RayCaster()
missing_texture_scene = MissingTextureScene(sound_manager, display_scale)
cone_scene = ConeScene(sound_manager, display_scale)
current_scene = "main"
board.create_display_list()
for obj in objects:
obj.create_display_list()
missing_texture_scene.create_display_list()
cone_scene.create_display_list()
demo_watcher = DemoWatcher(main_script=os.path.abspath(__file__))
demo_watcher.start()
last_demo_playing = False
clock = pygame.time.Clock()
running = True
frame_count = 0
fps_timer = time.time()
try:
while running:
dt = clock.tick(60) / 1000.0
dt = min(dt, 0.1)
# hold the cone scene (PULL) when a demo starts or stops in-game
demo_playing = demo_watcher.demo_playing
if demo_playing != last_demo_playing:
last_demo_playing = demo_playing
if current_scene == "cone":
cone_scene.set_pull(demo_playing)
mouse_pos = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
running = False
if current_scene == "cone":
if event.key == pygame.K_p:
cone_scene.toggle_pull()
cone_scene.handle_event(event)
elif event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1:
if current_scene == "main":
clicked_obj = check_object_click(mouse_pos, ray_caster, objects)
if clicked_obj and clicked_obj.type == "sphere":
current_scene = "error"
sound_manager.stop_music()
pygame.mouse.set_visible(False)
cursor_renderer.enabled = False
elif clicked_obj and clicked_obj.type == "cone":
sound_manager.play_sound('cone_click')
# clear hover so cone shows normal color between flashes
clicked_obj.is_hovered = False
# red -> normal -> red -> normal -> red (fast)
flash_pattern = [True, False, True, False, True]
for is_red in flash_pattern:
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
camera.apply()
light.apply()
board.draw(display[0], display[1])
glDisable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, 0)
glEnable(GL_LIGHTING)
glEnable(GL_DEPTH_TEST)
glEnable(GL_COLOR_MATERIAL)
glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE)
for o in objects:
if o == clicked_obj:
glPushMatrix()
glTranslatef(*o.position)
if o.base_rotation[0]: glRotatef(o.base_rotation[0], 1, 0, 0)
if o.base_rotation[1]: glRotatef(o.base_rotation[1], 0, 1, 0)
if o.base_rotation[2]: glRotatef(o.base_rotation[2], 0, 0, 1)
sx = o.scale * o.scale_xyz[0]
sy = o.scale * o.scale_xyz[1]
sz = o.scale * o.scale_xyz[2]
glScalef(sx, sy, sz)
if is_red:
glDisable(GL_LIGHTING)
glColor3f(1.0, 0.0, 0.0)
glCallList(o.display_list)
glEnable(GL_LIGHTING)
else:
b = o.shade()
glColor3f(b, b, b)
glCallList(o.display_list)
glPopMatrix()
else:
draw_object(o)
draw_sphere_shadow(objects, light)
light.release()
cursor_renderer.draw(mouse_pos, display[0], display[1])
frame_target.present()
pygame.time.wait(80)
cone_duration = sound_manager.get_sound_duration('cone_click')
remaining = int(cone_duration * 1000) - 400 if cone_duration > 0 else 100
if remaining > 0:
pygame.time.wait(remaining)
if hasattr(pygame.display, 'get_desktop_sizes'):
desktop_sizes = pygame.display.get_desktop_sizes()
screen_width, screen_height = desktop_sizes[0] if desktop_sizes else (1920, 1080)
else:
_di = pygame.display.Info()
screen_width, screen_height = _di.current_w, _di.current_h
new_width = 548
new_height = 525
os.environ['SDL_VIDEO_WINDOW_POS'] = f"{(screen_width - new_width) // 2},{(screen_height - new_height) // 2}"
set_display_mode((new_width, new_height))
display = (new_width, new_height)
glViewport(0, 0, new_width, new_height)
current_scene = "cone"
sound_manager.play_music(loops=-1, volume=0.3, start=1.0)
if demo_watcher.demo_playing:
cone_scene.set_pull(True)
elif clicked_obj and clicked_obj.type == "cube":
sound_manager.play_sound('cube_click')
bridge_manager.spawn_default_cube()
if clicked_obj.is_rotating:
clicked_obj.rotation_angle = 0.0
else:
clicked_obj.rotation_angle = 0.0
clicked_obj.is_rotating = True
clicked_obj.position = [0.151, 2.675, -0.66]
clicked_obj.base_rotation = [-15.3, -22.34, -95.37]
elif current_scene == "cone":
# check triangle click in cone scene (LEFT-CLICK ONLY)
if cone_scene.check_triangle_click(mouse_pos, display[0], display[1]):
sound_manager.play_sound('cone_back')
# clear hover so triangle shows normal color between flashes
cone_scene.triangle_hovered = False
# red -> grey -> red -> grey -> red
flash_pattern = ["red", "grey", "red", "grey", "red"]
for state in flash_pattern:
cone_scene.triangle_flash_red = state
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
cone_scene.draw(display[0], display[1])
cursor_renderer.draw(mouse_pos, display[0], display[1])
frame_target.present()
pygame.time.wait(80)
cone_scene.triangle_flash_red = False
# 3 second delay (minus flash time)
pygame.time.wait(2600)
# return to main menu
current_scene = "main"
cone_scene.pull_active = False
# restore to ORIGINAL display size
if hasattr(pygame.display, 'get_desktop_sizes'):
desktop_sizes = pygame.display.get_desktop_sizes()
screen_width, screen_height = desktop_sizes[0] if desktop_sizes else (1920, 1080)
else:
_di = pygame.display.Info()
screen_width, screen_height = _di.current_w, _di.current_h
# center the window with original size
os.environ['SDL_VIDEO_WINDOW_POS'] = f"{(screen_width - original_display[0]) // 2},{(screen_height - original_display[1]) // 2}"
set_display_mode(original_display)
display = original_display
# restore OpenGL viewport and perspective
glViewport(0, 0, display[0], display[1])
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
aspect_ratio = display[0] / display[1]
apply_main_projection(aspect_ratio)
glMatrixMode(GL_MODELVIEW)
# restore cursor
cursor_renderer.enabled = True
pygame.mouse.set_visible(False)
# restart music
sound_manager.stop_music()
sound_manager.play_music(loops=-1, volume=0.3, start=1.0)
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
if current_scene == "main":
for obj in objects:
update_object_rotation(obj, dt)
update_object_animation(obj, dt)
camera.apply()
light.apply()
ray_caster.update_matrices()
check_object_hover(mouse_pos, ray_caster, objects, sound_manager)
board.draw(display[0], display[1])
glDisable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, 0)
for obj in objects:
draw_object(obj)
draw_sphere_shadow(objects, light)
light.release()
cursor_renderer.draw(mouse_pos, display[0], display[1])
elif current_scene == "error":
missing_texture_scene.update(dt)
missing_texture_scene.draw(display[0], display[1])
elif current_scene == "cone":
cone_scene.update(dt)
cone_scene.check_triangle_hover(mouse_pos, display[0], display[1])
cone_scene.draw(display[0], display[1])
cursor_renderer.draw(mouse_pos, display[0], display[1])
frame_target.present()
frame_count += 1
if time.time() - fps_timer >= 1.0:
frame_count = 0
fps_timer = time.time()
except KeyboardInterrupt:
print("\nShutting down...")
except Exception as e:
print(f"Runtime error: {e}")
import traceback
traceback.print_exc()
finally:
print("Cleaning up...")
demo_watcher.stop()
cursor_renderer.cleanup()
sound_manager.stop_music()
board.cleanup()
frame_target.cleanup()
for obj in objects:
obj.cleanup()
missing_texture_scene.cleanup()
cone_scene.cleanup()
bridge_manager.cleanup()
try:
pygame.quit()
except:
pass
print("Goodbye!")
if __name__ == "__main__":
main()