-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
2467 lines (2045 loc) · 110 KB
/
Copy pathclient.py
File metadata and controls
2467 lines (2045 loc) · 110 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
# client.py
import json
import os
from pathlib import Path
_cfg_path = Path('launch_config.json')
if _cfg_path.exists():
try:
_cfg = json.loads(_cfg_path.read_text())
os.environ['TOKENTORCH_SEED'] = str(_cfg.get('seed', 876567))
os.environ['TOKENTORCH_WORLD_SIZE'] = str(_cfg.get('world_size', 32768))
except Exception:
pass
import uuid
import time
import math
import numpy as np
from concurrent.futures import ThreadPoolExecutor
import threading
import asyncio
import moderngl
import moderngl_window
import pyrr
from moderngl_window import BaseWindow
from cave_generation import scan_and_remove_floaters
from client_state import ClientState, WaterData
from constants import ClientConstants, GenerationConstants
from fluid_simulator import ChunkFluidSimulator, _NEIGHBOR_OFFSETS
from graphics_resources import GraphicsResources
from network import NetworkClient
from player_commands import PlayerController
from profiler import FrameProfiler
from shaders import ShaderLibrary
from skybox import ProceduralSky
from world_generation import (finished_chunks_queue, fetch_chunk_threaded,
mesh_volume, save_chunk_to_disk_threaded,
set_active_database, find_shoreline_spawn)
from entity_manager import (SkinnedCharacter, LaserBeam,
HeldItemModel, ItemDropRenderer,
ArachnoidModel)
class TokenTorchClient(moderngl_window.WindowConfig, ClientState):
gl_version = (3, 3)
title = "TokenTorch Client"
window_size = (1600, 900)
aspect_ratio = 16 / 9
fullscreen = False
resizable = True
resource_dir = os.path.normpath(os.path.dirname(__file__))
ctx = moderngl.create_context(standalone=True)
wnd: BaseWindow
def __init__(self, **kwargs):
super().__init__(**kwargs)
ClientState.__init__(self)
self._strand_pool = ThreadPoolExecutor(
max_workers=2,
thread_name_prefix='strand'
)
self.ctx: moderngl.Context
self.texture_array: moderngl.TextureArray | None = None
self.shaders = ShaderLibrary(ctx=self.ctx)
self.assets = GraphicsResources(self.ctx)
self.assets.bind_textures(self.shaders.chunk)
self.const = ClientConstants
self.con = GenerationConstants
self.show_profiler = False
self.profiler = FrameProfiler()
self.current_engine_time = 0.0
self.last_seen_network_time = 0.0
self.last_server_time_update = 0.0
self.wnd.mouse_exclusivity = False
self.show_inventory = False
self.engine_started = False
self.camera_mode = 'TPS'
self.torch_on = True
# ── Load launch config written by main_menu.py ─────────────────────
_cfg: dict = {}
_cfg_path = Path('launch_config.json')
if _cfg_path.exists():
try:
_cfg = json.loads(_cfg_path.read_text())
except Exception:
pass
_host = _cfg.get('host_ip', '')
if _host and _host != '127.0.0.1':
os.environ['TOKENTORCH_SERVER_HOST'] = _host
self.my_player_id = str(uuid.uuid4())[:8]
self.world_name = _cfg.get('world_name', 'World')
self.server_host = _cfg.get('host_ip', '127.0.0.1')
self.server_port = int(_cfg.get('port', 5555))
_mode = _cfg.get('mode', 'singleplayer')
self.is_multiplayer = _mode in ('singleplayer', 'multiplayer', 'host', 'host_creative')
# ==========================================
# CONNECTION & ROUTING LOGIC
# ==========================================
if self.is_multiplayer:
# 1. Determine the cache name based on the server IP
self.network = NetworkClient(host=self.server_host, port=self.server_port)
safe_ip = self.network.server_addr[0].replace('.', '_')
cache_name = f"mp_cache_{safe_ip}.db"
# 2. Anti-Cheat: The Pre-Emptive Strike
if os.path.exists(cache_name):
try:
os.remove(cache_name)
print("[Security] Purged compromised cache file from previous session.")
except Exception:
pass
# 3. Route the background threads!
set_active_database(cache_name)
self.active_cache_file = cache_name
print(f"[Network] Connected! Spun up secure temp cache: {cache_name}")
else:
# Singleplayer — named world save
set_active_database(f'worlds/sp_{self.world_name}.db')
# --- PREFAB EXPORTER ---
self.prefab_pos_a = None
self.prefab_pos_b = None
os.makedirs('prefabs', exist_ok=True)
# --- FIRST-SPAWN: Land the player on a shoreline beach (hashed) ---
spawn_x, spawn_y, spawn_z = find_shoreline_spawn()
print(f"[Spawn] Surface beach spawn → ({spawn_x:.0f}, {spawn_y:.0f}, {spawn_z:.0f})")
if self.is_multiplayer:
self._pending_spawn_request = (spawn_x, spawn_y, spawn_z)
self._spawn_request_sent = False
self.last_safe_position = (spawn_x, spawn_y, spawn_z)
self._clip_frames = 0
self.controller = PlayerController(spawn_x, spawn_y, spawn_z)
self.last_mouse_pos = (self.window_size[0] // 2, self.window_size[1] // 2)
self.assets.load_textures()
self.skybox = ProceduralSky(self.ctx)
self.active_tasks = set()
# --- UI SYSTEM INITIALIZATION ---
from ui_renderer import UIRenderer
self.ui_renderer = UIRenderer(self.ctx)
base_ui_path = 'art/textures/ui/'
self._frame_hit = None
self._frame_empty = None
# Load Crosshair and Inventory Background
self.ui_renderer.load_texture('crosshair', base_ui_path + 'crosshair.png')
self.ui_renderer.load_texture('slot_bg', base_ui_path + 'slot_bg.png')
self._view_proj_cache = np.eye(4, dtype='f4')
# Load block icons for the inventory (Matching your client.py texture array order)
block_filenames = [
'obsidian_bedrock.png', # ID 1
'stone_granite.png', # ID 2
'dirt.png', # ID 3
'grass_top.png', # ID 4
'snow.png', # ID 5
'log_oak.png', # ID 6
'leaves_oak.png', # ID 7
'mahogany_crate.png', # ID 8
'log_birch.png', # ID 9
'leaves_birch.png', # ID 10
'grass_long.png', # ID 11
'red_sandstone_top.png', # ID 12
'cut_bricks.png', # ID 13
'red_cut_bricks.png', # ID 14
'planks_oak.png', # ID 15
'sand.png' # ID 16
]
# TODO: ADD ITEM FILENAMES FOR INVENTORY DISPLAY
for i, filename in enumerate(block_filenames):
block_id = i + 1 # 0-index list to 1-based Block ID
self.ui_renderer.load_texture(f'block_{block_id}', f'art/textures/blocks/{filename}')
# Load Health Hearts
for state in ['full', 'three_quarters', 'half', 'quarter', 'empty']:
self.ui_renderer.load_texture(f'heart_{state}', f'{base_ui_path}heart_{state}.png')
# Load Stamina Hearts
for state in ['full', 'three_quarters', 'half', 'quarter', 'empty']:
self.ui_renderer.load_texture(f'stamina_{state}', f'{base_ui_path}stamina_{state}.png')
self.last_fluid_tick = 0.0
self.last_physics_tick = 0.0
self.requested_chunks = set()
self.last_chunk_pos = None
self.last_chunk_upload_time = 0.0
self.pending_chunk_requests = []
self.last_chunk_request_time = 0.0
# --- CHARACTER SYSTEM ---
self.active_character_id = 'blockman' # The one we are currently playing as
self.last_pvp_tick = 0.0
self.last_water_heartbeat = 0.0
self._charge_threat: float = 0.0
# Load the models into the dictionary
try:
self.characters['blockman'] = SkinnedCharacter(
self, 'art/models/entities/players/blockman.glb'
)
self.characters['blockman'].scale = 1.0
except Exception as e:
print(f"WARNING: Could not load character model: {e}")
self.monster_models: dict = {}
# --- WEAPON SYSTEM ---
from entity_manager import WeaponModel
# Scale 0.02 makes it 50x smaller!
self.blaster = WeaponModel(self, 'art/models/entities/mining_blaster_alpha.obj',
'art/textures/colors/mining_blaster_alpha.png', scale=0.25)
self.laser_effect = LaserBeam(self)
self.bucket_model = HeldItemModel(
self,
model_path='art/models/items/bucket01.obj',
texture_path='art/textures/items/colors/castletexture.png',
scale=0.5, # Adjust if it's too huge/tiny
offset=(0.6, -0.4, -1.2), # Bottom right of the screen
rotation=(0.0, math.radians(-45), 0.0) # Angled slightly inward
)
self.mining_target = None # Coordinates of the block we are currently beaming
self.mining_start_time = 0.0 # When did we start shooting this block?
# --- INVENTORY SYSTEM ---
# 50 slots total. Indices 0-9 are the hotbar.
self.inventory = [{'id': 0, 'count': 0} for _ in range(50)]
# Some starter items!
self.inventory[0] = {'id': 14, 'count': 64} # Oak Planks
self.inventory[1] = {'id': 12, 'count': 32} # Cut Bricks
self.inventory[2] = {'id': 7, 'count': 16} # Mahogany Crate
# --- NEW: THE BUCKETS ---
self.ITEM_WOODEN_BUCKET_EMPTY = 1000
self.ITEM_WOODEN_BUCKET_WATER = 1001
self.inventory[3] = {'id': self.ITEM_WOODEN_BUCKET_EMPTY, 'count': 1} # Starter bucket!
self.active_hotbar_slot = 0
self.item_renderer = ItemDropRenderer(self)
self.chat_history = []
self.is_typing = False
self.input_text = ""
self.player_name = f"Player_{self.my_player_id[:4]}"
self.model_matrix = pyrr.Matrix44.identity()
self.proj_matrix = pyrr.matrix44.create_perspective_projection(
fovy=60.0, aspect=self.aspect_ratio, near=0.1, far=500.0
)
self.shaders.chunk['m_proj'].write(self.proj_matrix.astype('f4').tobytes())
# Cache the orthographic UI projection — rebuilt only on resize
self._ui_proj = pyrr.matrix44.create_orthogonal_projection(
0, self.window_size[0], 0, self.window_size[1], -1, 1
).astype('f4')
# Cache view*proj — updated every frame in _calculate_camera_and_environment
self._view_proj_cache = np.eye(4, dtype=np.float32)
self.ctx.enable(moderngl.DEPTH_TEST | moderngl.CULL_FACE)
self._gatherer_running = True
self._gatherer_thread = threading.Thread(
target=self._water_gatherer_worker, daemon=True
)
self._gatherer_thread.start()
def _check_clip_through_terrain(self, current_time):
pos = self.controller.get_position()
passable = getattr(self.controller, 'passable_blocks', {0, 11})
# Sample the block occupying the player's torso and feet
torso_id = self.get_block_at(pos[0], pos[1], pos[2])
foot_id = self.get_block_at(pos[0], pos[1] - 0.5, pos[2])
clipping = (torso_id not in passable) or (foot_id not in passable)
if clipping:
self._clip_frames += 1
# 3-frame debounce — ignores single-frame edge grazes
if self._clip_frames >= 3:
lsp = self.last_safe_position
self.controller.position = pyrr.Vector3([lsp[0], lsp[1], lsp[2]])
self.controller.velocity_y = 0.0
self._clip_frames = 0
print(f"[Safety] Clip detected — returned to ({lsp[0]:.1f}, {lsp[1]:.1f}, {lsp[2]:.1f})")
else:
self._clip_frames = 0
# Only checkpoint when solidly grounded, not mid-air
ground_id = self.get_block_at(pos[0], pos[1] - 1.1, pos[2])
if ground_id not in passable:
self.last_safe_position = (float(pos[0]), float(pos[1]), float(pos[2]))
def _water_gatherer_worker(self):
while self._gatherer_running:
pending = list(self.water_gather_needed)
for chunk_coord in pending:
water_data = self.water_state.get(chunk_coord)
if water_data is None:
self.water_gather_needed.discard(chunk_coord)
continue
arr = water_data.vol
wx, wy, wz = np.nonzero(arr > 0.0)
if len(wx) == 0:
self.water_gather_needed.discard(chunk_coord)
continue
cx, cy, cz = chunk_coord
# Optional: validate against heightmap seeding math
# world_ys = wy + cy * 16
# valid = world_ys <= GenerationConstants.SEA_LEVEL
# wx, wy, wz = wx[valid], wy[valid], wz[valid]
# if len(wx) == 0: ...
instance_data = np.column_stack((
wx + cx * 16,
wy + cy * 16,
wz + cz * 16,
arr[wx, wy, wz]
)).astype('f4')
self.water_upload_queue.append((chunk_coord, instance_data))
self.water_gather_needed.discard(chunk_coord)
time.sleep(0.008)
@staticmethod
async def _gather_chunk_prep(batch):
"""
Gather any remaining CPU prep across 4 strands concurrently.
Each coroutine is initialized cheaply upfront, then the event
loop runs their parts without sequential frame overhead.
"""
loop = asyncio.get_running_loop()
async def _prep(item):
cx, cy, cz, serialized, volume, water_vol = item
cube_bytes, sprite_bytes, water_bytes, nc, ns, nw = serialized
return cx, cy, cz, cube_bytes, sprite_bytes, water_bytes, nc, ns, nw, volume, water_vol
return await asyncio.gather(*[_prep(item) for item in batch])
def _drain_water_upload_queue(self):
"""Main thread only — GPU uploads from gatherer output."""
while self.water_upload_queue:
chunk_coord, instance_data = self.water_upload_queue.popleft()
if chunk_coord not in self.chunk_data:
continue
# Release old
if 'water' in self.chunk_data[chunk_coord]:
self.chunk_data[chunk_coord]['water'][0].release()
del self.chunk_data[chunk_coord]['water']
if 'water_vbo_obj' in self.chunk_data[chunk_coord]:
self.chunk_data[chunk_coord]['water_vbo_obj'].release()
del self.chunk_data[chunk_coord]['water_vbo_obj']
# Upload
water_vbo = self.ctx.buffer(instance_data.tobytes())
water_vao = self.ctx.vertex_array(
self.shaders.water,
[(self.assets.vbo, '3f 8x', 'in_position'),
(water_vbo, '4f /i', 'in_instance')],
index_buffer=self.assets.ibo
)
self.chunk_data[chunk_coord]['water'] = (water_vao, len(instance_data))
self.chunk_data[chunk_coord]['water_vbo_obj'] = water_vbo
def _drain_boundary_remesh(self, budget: int = 2):
"""
Re-meshes up to `budget` chunks per frame whose boundary faces may
have been occluded by a newly loaded neighbor. Runs after
process_finished_chunks so world_state is already updated.
"""
processed = 0
while self.pending_boundary_remesh and processed < budget:
chunk_coord = self.pending_boundary_remesh.pop()
cx, cy, cz = chunk_coord
# Skip if the chunk was unloaded between enqueue and drain
if chunk_coord not in self.world_state or chunk_coord not in self.chunk_data:
continue
volume = self.world_state[chunk_coord]
water_data = self.water_state.get(chunk_coord)
water_vol = water_data.vol if water_data is not None else \
np.zeros((self.con.CHUNK_SIZE,) * 3, dtype=np.float32)
ghost_solid, ghost_water = self.build_ghosted_arrays(
chunk_coord, self.world_state, self.water_state
)
cube_data, sprite_data, water_mesh = mesh_volume(
volume, water_vol, cx, cy, cz,
ghost_water=ghost_water, ghost_solid=ghost_solid
)
old = self.chunk_data[chunk_coord]
# Release stale GPU memory
for key in ('cube', 'sprite', 'water'):
if key in old: old[key][0].release()
if f'{key}_vbo_obj' in old: old[f'{key}_vbo_obj'].release()
chunk_render_data = {}
if len(cube_data) > 0:
cube_vbo = self.ctx.buffer(cube_data.tobytes())
cube_vao = self.ctx.vertex_array(
self.shaders.chunk,
[(self.assets.vbo, '3f 2f', 'in_position', 'in_uv'),
(cube_vbo, '4f 1f 1f /i', 'in_instance', 'in_ao_1', 'in_ao_2')],
index_buffer=self.assets.ibo
)
chunk_render_data['cube'] = (cube_vao, len(cube_data))
chunk_render_data['cube_vbo_obj'] = cube_vbo
if len(sprite_data) > 0:
sprite_vbo = self.ctx.buffer(sprite_data.tobytes())
sprite_vao = self.ctx.vertex_array(
self.shaders.chunk,
[(self.assets.sprite_vbo, '3f 2f', 'in_position', 'in_uv'),
(sprite_vbo, '4f 1f 1f /i', 'in_instance', 'in_ao_1', 'in_ao_2')],
index_buffer=self.assets.sprite_ibo
)
chunk_render_data['sprite'] = (sprite_vao, len(sprite_data))
chunk_render_data['sprite_vbo_obj'] = sprite_vbo
if len(water_mesh) > 0:
water_vbo = self.ctx.buffer(water_mesh.tobytes())
water_vao = self.ctx.vertex_array(
self.shaders.water,
[(self.assets.vbo, '3f 8x', 'in_position'),
(water_vbo, '4f /i', 'in_instance')],
index_buffer=self.assets.ibo
)
chunk_render_data['water'] = (water_vao, len(water_mesh))
chunk_render_data['water_vbo_obj'] = water_vbo
# Preserve fluid bookkeeping keys — the mesh changed, not the sim state
for key in ('water_dirty', 'water_settle_time'):
if key in old:
chunk_render_data[key] = old[key]
self.chunk_data[chunk_coord] = chunk_render_data
processed += 1
def on_resize(self, width: int, height: int):
self._ui_proj = pyrr.matrix44.create_orthogonal_projection(
0, width, 0, height, -1, 1
).astype('f4')
def get_specific_block_at(self, x, y, z):
"""Helper to get a block ID from the raw world state array safely."""
x, y, z = int(math.floor(x)), int(math.floor(y)), int(math.floor(z))
cx, cy, cz = x // self.con.CHUNK_SIZE, y // self.con.CHUNK_SIZE, z // self.con.CHUNK_SIZE
lx, ly, lz = x % self.con.CHUNK_SIZE, y % self.con.CHUNK_SIZE, z % self.con.CHUNK_SIZE
chunk_coord = (cx, cy, cz)
if chunk_coord in self.world_state:
return self.world_state[chunk_coord][lx, ly, lz]
return 0
def get_block_at(self, x, y, z):
"""Helper to read the voxel array at a specific world coordinate."""
# Because geometry is drawn from -0.5 to 0.5, the true center of block (0,0,0) is at 0.0.
# To map a floating point position to the correct integer voxel bucket,
# we must add 0.5 before taking the floor.
bx = int(math.floor(x + 0.5))
by = int(math.floor(y + 0.5))
bz = int(math.floor(z + 0.5))
cx, cy, cz = bx // self.con.CHUNK_SIZE, by // self.con.CHUNK_SIZE, bz // self.con.CHUNK_SIZE
chunk_coord = (cx, cy, cz)
if chunk_coord in self.world_state:
lx, ly, lz = bx % self.con.CHUNK_SIZE, by % self.con.CHUNK_SIZE, bz % self.con.CHUNK_SIZE
try:
return self.world_state[chunk_coord][lx, ly, lz]
except IndexError:
return 0
return 0
def raycast(self, max_dist=10.0, step=0.05):
"""
Fires a ray from the camera.
Returns (hit_block_coord, previous_empty_coord) or (None, None).
"""
pos = self.controller.get_position().copy()
if not self.controller.is_flying:
pos[1] += 0.0 # Eye level is origin
front = self.controller.front
traveled = 0.0
last_empty = None
while traveled < max_dist:
# Shift by +0.5 to match the visual geometry center!
bx = int(math.floor(pos[0] + 0.5))
by = int(math.floor(pos[1] + 0.5))
bz = int(math.floor(pos[2] + 0.5))
# get_block_at will internally do the +0.5 shift, so we pass the raw float pos
block_id = self.get_block_at(pos[0], pos[1], pos[2])
if block_id > 0 and block_id not in self.controller.passable_blocks:
return (bx, by, bz), last_empty
last_empty = (bx, by, bz)
pos += front * step
traveled += step
return None, None
def set_block_at(self, x, y, z, block_id):
"""Modifies the voxel array and instantly rebuilds the chunk mesh."""
if self.ctx is None:
return
bx, by, bz = int(math.floor(x)), int(math.floor(y)), int(math.floor(z))
cx, cy, cz = bx // self.con.CHUNK_SIZE, by // self.con.CHUNK_SIZE, bz // self.con.CHUNK_SIZE
lx, ly, lz = bx % self.con.CHUNK_SIZE, by % self.con.CHUNK_SIZE, bz % self.con.CHUNK_SIZE
chunk_coord = (cx, cy, cz)
# 1. Update the local data
self.world_state[chunk_coord][lx, ly, lz] = block_id
# Pre-fill broken position with water if any face neighbor has water
if block_id == 0:
water_data = self.water_state.get(chunk_coord)
if water_data is not None:
arr = water_data.vol
for dlx, dly, dlz in [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]:
nlx, nly, nlz = lx + dlx, ly + dly, lz + dlz
if 0 <= nlx < self.con.CHUNK_SIZE and \
0 <= nly < self.con.CHUNK_SIZE and \
0 <= nlz < self.con.CHUNK_SIZE and \
arr[nlx, nly, nlz] > 0.0:
arr[lx, ly, lz] = 1.0
break
# 2. Update fluid simulator first so water adapts to the new geometry
if chunk_coord in self.fluid_simulators:
ghost_solid, ghost_water = self.build_ghosted_arrays(chunk_coord, self.world_state, self.water_state)
sim = self.fluid_simulators[chunk_coord]
sim.update_solid_geometry(ghost_solid)
sim.step_simulation(cx, cy, cz)
vol_np = sim.get_render_arrays()
self.water_state[chunk_coord] = WaterData(vol=vol_np)
else:
# Wake up the simulator if we interact with a dormant water chunk!
water_data = self.water_state.get(chunk_coord)
if water_data is not None and bool(np.any(water_data.vol > 0.0)):
ghost_solid, ghost_water = self.build_ghosted_arrays(chunk_coord, self.world_state, self.water_state)
sim = ChunkFluidSimulator()
sim.initialize_gpu_memory(ghost_water, ghost_solid)
self.fluid_simulators[chunk_coord] = sim
if chunk_coord not in self.chunk_data:
self.chunk_data[chunk_coord] = {}
self.chunk_data[chunk_coord]['water_dirty'] = True
# 3. Fetch water volume (may have just been updated above)
water_data = self.water_state.get(chunk_coord)
water_volume = water_data.vol if water_data is not None else np.zeros(
(self.con.CHUNK_SIZE,) * 3, dtype=np.float32
)
# 4. Build ghost for seam-free water meshing
ghost_solid, ghost_water = self.build_ghosted_arrays(chunk_coord, self.world_state, self.water_state)
# 5. Mesh the chunk
cube_data, sprite_data, water_mesh = mesh_volume(
self.world_state[chunk_coord], water_volume, cx, cy, cz,
ghost_water=ghost_water, ghost_solid=ghost_solid
)
# 6. Release old GPU memory
if chunk_coord in self.chunk_data:
old = self.chunk_data[chunk_coord]
for key in ('cube', 'sprite', 'water'):
if key in old:
old[key][0].release()
if f'{key}_vbo_obj' in old:
old[f'{key}_vbo_obj'].release()
# 7. Upload new geometry
chunk_render_data = {}
if len(cube_data) > 0:
cube_vbo = self.ctx.buffer(cube_data.tobytes())
cube_vao = self.ctx.vertex_array(
self.shaders.chunk,
[(self.assets.vbo, '3f 2f', 'in_position', 'in_uv'),
(cube_vbo, '4f 1f 1f /i', 'in_instance', 'in_ao_1', 'in_ao_2')],
index_buffer=self.assets.ibo
)
chunk_render_data['cube'] = (cube_vao, len(cube_data))
chunk_render_data['cube_vbo_obj'] = cube_vbo
if len(sprite_data) > 0:
sprite_instance_vbo = self.ctx.buffer(sprite_data.tobytes())
sprite_vao = self.ctx.vertex_array(
self.shaders.chunk,
[(self.assets.sprite_vbo, '3f 2f', 'in_position', 'in_uv'),
(sprite_instance_vbo, '4f 1f 1f /i', 'in_instance', 'in_ao_1', 'in_ao_2')],
index_buffer=self.assets.sprite_ibo
)
chunk_render_data['sprite'] = (sprite_vao, len(sprite_data))
chunk_render_data['sprite_vbo_obj'] = sprite_instance_vbo
if len(water_mesh) > 0:
water_vbo = self.ctx.buffer(water_mesh.tobytes())
water_vao = self.ctx.vertex_array(
self.shaders.water,
[(self.assets.vbo, '3f 8x', 'in_position'),
(water_vbo, '4f /i', 'in_instance')],
index_buffer=self.assets.ibo
)
chunk_render_data['water'] = (water_vao, len(water_mesh))
chunk_render_data['water_vbo_obj'] = water_vbo
self.chunk_data[chunk_coord] = chunk_render_data
def on_mouse_press_event(self, x, y, button):
if self.camera_mode != 'FPS':
return
hit_coord, empty_coord = self.raycast(max_dist=15.0)
if button == 1 and hasattr(self, 'blaster'):
# Just read it directly! Clean and safe.
current_time = self.current_engine_time
self.blaster.fire(current_time)
cam_pos = self.controller.get_position()
start_pos = cam_pos + pyrr.Vector3([0.0, -0.2, 0.0]) + (self.controller.front * 0.5)
if hit_coord:
end_pos = pyrr.Vector3([hit_coord[0], hit_coord[1], hit_coord[2]])
else:
end_pos = start_pos + (self.controller.front * 15.0)
self.laser_effect.shoot(start_pos, end_pos, current_time)
if hit_coord:
if button == 2 and empty_coord:
active_slot = self.inventory[self.active_hotbar_slot]
if active_slot['count'] > 0:
selected_id = active_slot['id']
# ==========================================
# INTERACTIVE TOOL: EMPTY BUCKET (SCOOP)
# ==========================================
if selected_id == self.ITEM_WOODEN_BUCKET_EMPTY:
wx, wy, wz = hit_coord
cx, cy, cz = (wx // self.con.CHUNK_SIZE,
wy // self.con.CHUNK_SIZE,
wz // self.con.CHUNK_SIZE)
lx, ly, lz = wx % self.con.CHUNK_SIZE, wy % self.con.CHUNK_SIZE, wz % self.con.CHUNK_SIZE
chunk = (cx, cy, cz)
if chunk in self.water_state:
# THE FIX: Extract the actual volume array from the tuple
water_data = self.water_state[chunk]
water_array = water_data.vol
if water_array[lx, ly, lz] > 0.05:
new_vol = max(0.0, water_array[lx, ly, lz] - 0.1)
water_array[lx, ly, lz] = new_vol
active_slot['id'] = self.ITEM_WOODEN_BUCKET_WATER
# Sync to Server
if hasattr(self, 'network') and getattr(self, 'is_multiplayer', True):
self.network.send_water_update(self.my_player_id, wx, wy, wz, new_vol)
print("Scooped water!")
# THE GPU FIX: Surgically inject the 1 block change into the 18x18x18 boundary!
if chunk in self.fluid_simulators:
self.fluid_simulators[chunk].inject_server_state({(lx, ly, lz): new_vol})
# Wake up the mesh builder!
if chunk in self.chunk_data:
self.chunk_data[chunk]['water_dirty'] = True
self.chunk_data[chunk]['water_settle_time'] = self.current_engine_time
# ==========================================
# INTERACTIVE TOOL: WATER BUCKET (POUR)
# ==========================================
elif selected_id == self.ITEM_WOODEN_BUCKET_WATER:
wx, wy, wz = empty_coord
cx, cy, cz = (wx // self.con.CHUNK_SIZE, wy // self.con.CHUNK_SIZE, wz // self.con.CHUNK_SIZE)
lx, ly, lz = (wx % self.con.CHUNK_SIZE, wy % self.con.CHUNK_SIZE, wz % self.con.CHUNK_SIZE)
chunk = (cx, cy, cz)
if chunk not in self.water_state:
empty = np.zeros((self.con.CHUNK_SIZE,) * 3, dtype=np.float32)
self.water_state[chunk] = WaterData(
vol=empty
)
water_array = self.water_state[chunk].vol
new_vol = min(1.0, water_array[lx, ly, lz] + 0.1)
water_array[lx, ly, lz] = new_vol
active_slot['id'] = self.ITEM_WOODEN_BUCKET_EMPTY
# Sync to Server
if hasattr(self, 'network') and getattr(self, 'is_multiplayer', True):
self.network.send_water_update(self.my_player_id, wx, wy, wz, new_vol)
print("Poured water!")
if chunk not in self.fluid_simulators:
ghost_solid, ghost_water = self.build_ghosted_arrays(
chunk, self.world_state, self.water_state
)
sim = ChunkFluidSimulator()
sim.initialize_gpu_memory(ghost_water, ghost_solid)
self.fluid_simulators[chunk] = sim
else:
# Safely inject the new water directly into the GPU
self.fluid_simulators[chunk].inject_server_state({(lx, ly, lz): new_vol})
if chunk in self.chunk_data:
self.chunk_data[chunk]['water_dirty'] = True
self.chunk_data[chunk]['water_settle_time'] = self.current_engine_time
# ==========================================
# STANDARD SOLID BLOCK PLACEMENT
# ==========================================
elif selected_id < 1000: # Ensure it's a solid block ID
self.set_block_at(empty_coord[0], empty_coord[1], empty_coord[2], selected_id)
active_slot['count'] -= 1
if active_slot['count'] == 0:
active_slot['id'] = 0
if hasattr(self, 'network') and getattr(self, 'is_multiplayer', True):
self.network.send_block_update(
self.my_player_id,
empty_coord[0], empty_coord[1], empty_coord[2],
selected_id
)
def break_block(self, bx, by, bz, is_player_action=True):
"""Centralized block breaking logic."""
block_id = self.get_block_at(bx, by, bz)
if block_id == 0: return
# 1. Set to air locally
self.set_block_at(bx, by, bz, 0)
# 2. Spawn the 3D item drop!
if hasattr(self, 'item_renderer'):
self.item_renderer.add_drop(bx, by, bz, block_id)
# 3. Network Sync
if hasattr(self, 'network') and getattr(self, 'is_multiplayer', True) and is_player_action:
self.network.send_block_update(self.my_player_id, bx, by, bz, 0)
# 4. Tree Felling Chain Reaction (Only if initiated by the player)
# 6=Oak Log, 9=Birch Log
if is_player_action and block_id in [6, 9]:
self._felling_check(bx, by, bz)
def add_to_inventory(self, block_id, amount=1):
"""Attempts to add an item to the inventory. Returns True if successful."""
# 1. Try to stack with existing items
for slot in self.inventory:
if slot['id'] == block_id and slot['count'] < 64:
space = 64 - slot['count']
add = min(space, amount)
slot['count'] += add
amount -= add
if amount <= 0:
return True
# 2. If we still have items, find an empty slot
for slot in self.inventory:
if slot['id'] == 0:
slot['id'] = block_id
slot['count'] = amount
return True
return False # Inventory is full!
def process_finished_chunks(self, current_time):
if self.ctx is None:
return
batch = []
budget_start = time.perf_counter()
while not finished_chunks_queue.empty():
if time.perf_counter() - budget_start > self.const.chunk_upload_budget:
break
batch.append(finished_chunks_queue.get())
for item in batch:
cx, cy, cz, serialized, volume, water_vol = item
cube_b, sprite_b, water_b, nc, ns, nw = serialized
self._upload_chunk_to_gpu(cx, cy, cz, cube_b, sprite_b, water_b, nc, ns, nw, volume, water_vol)
def _upload_chunk_to_gpu(
self, cx, cy, cz,
cube_b, sprite_b, water_b,
nc, ns, nw,
volume, water_vol
):
"""Pure GPU calls only — no CPU work here."""
chunk_coord = (cx, cy, cz)
self.world_state[chunk_coord] = volume
self.water_state[chunk_coord] = WaterData(vol=water_vol)
# Release old
if chunk_coord in self.chunk_data:
old = self.chunk_data[chunk_coord]
for key in ('cube', 'sprite', 'water'):
if key in old: old[key][0].release()
if f'{key}_vbo_obj' in old: old[f'{key}_vbo_obj'].release()
chunk_render_data = {}
if nc > 0:
cube_vbo = self.ctx.buffer(cube_b)
cube_vao = self.ctx.vertex_array(
self.shaders.chunk,
[(self.assets.vbo, '3f 2f', 'in_position', 'in_uv'),
(cube_vbo, '4f 1f 1f /i', 'in_instance', 'in_ao_1', 'in_ao_2')],
index_buffer=self.assets.ibo
)
chunk_render_data['cube'] = (cube_vao, nc)
chunk_render_data['cube_vbo_obj'] = cube_vbo
if ns > 0:
sprite_vbo = self.ctx.buffer(sprite_b)
sprite_vao = self.ctx.vertex_array(
self.shaders.chunk,
[(self.assets.sprite_vbo, '3f 2f', 'in_position', 'in_uv'),
(sprite_vbo, '4f 1f 1f /i', 'in_instance', 'in_ao_1', 'in_ao_2')],
index_buffer=self.assets.sprite_ibo
)
chunk_render_data['sprite'] = (sprite_vao, ns)
chunk_render_data['sprite_vbo_obj'] = sprite_vbo
if nw > 0:
water_vbo = self.ctx.buffer(water_b)
water_vao = self.ctx.vertex_array(
self.shaders.water,
[(self.assets.vbo, '3f 8x', 'in_position'),
(water_vbo, '4f /i', 'in_instance')],
index_buffer=self.assets.ibo
)
chunk_render_data['water'] = (water_vao, nw)
chunk_render_data['water_vbo_obj'] = water_vbo
self.chunk_data[chunk_coord] = chunk_render_data
# ONLY spawn fluid sim if the chunk is actively flowing/dirty!
# Deep ocean chunks will stay completely dormant until disturbed.
is_dirty = self.chunk_data.get(chunk_coord, {}).get('water_dirty', False)
if is_dirty and bool(np.any(water_vol > 0.0)) and chunk_coord not in self.fluid_simulators:
ghost_solid, ghost_water = self.build_ghosted_arrays(chunk_coord, self.world_state, self.water_state)
sim = ChunkFluidSimulator()
sim.initialize_gpu_memory(ghost_water, ghost_solid)
self.fluid_simulators[chunk_coord] = sim
# Flag face-adjacent loaded neighbors for boundary re-mesh.
# Their outward-facing boundary faces are now potentially occluded
# by the chunk that just arrived.
for ddx, ddy, ddz in [(1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0), (0, 0, 1), (0, 0, -1)]:
neighbor = (cx + ddx, cy + ddy, cz + ddz)
if neighbor in self.world_state and neighbor in self.chunk_data:
self.pending_boundary_remesh.add(neighbor)
self._frustum_dirty = True
if hasattr(self, 'network') and getattr(self, 'is_multiplayer', True):
try:
packet = {"type": "chunk_loaded", "id": self.my_player_id, "chunk": [cx, cy, cz]}
self.network.sock.sendto(json.dumps(packet).encode('utf-8'), self.network.server_addr)
except Exception:
pass
def block_physics_tick(self, current_time):
if self.ctx is None:
return
if current_time - self.last_physics_tick < 1.0:
return
self.last_physics_tick = current_time
pos = self.controller.get_position()
cx, cy, cz = int(pos.x // self.con.CHUNK_SIZE), int(pos.y // self.con.CHUNK_SIZE), int(
pos.z // self.con.CHUNK_SIZE)
for nx in range(cx - 1, cx + 2):
for ny in range(cy - 1, cy + 2):
for nz in range(cz - 1, cz + 2):
chunk_coord = (nx, ny, nz)
if chunk_coord not in self.world_state:
continue
volume = self.world_state[chunk_coord]
changed = scan_and_remove_floaters(volume)
if not changed:
continue
water_data = self.water_state.get(chunk_coord)
water_volume = water_data.vol if water_data is not None else np.zeros(
(self.con.CHUNK_SIZE,) * 3, dtype=np.float32
)
# Release old GPU memory
if chunk_coord in self.chunk_data:
old = self.chunk_data[chunk_coord]
for key in ('cube', 'sprite', 'water'):
if key in old:
old[key][0].release()
if f'{key}_vbo_obj' in old:
old[f'{key}_vbo_obj'].release()
# Ghost for seam-free water
ghost_solid, ghost_water = self.build_ghosted_arrays(chunk_coord, self.world_state,
self.water_state)
cube_data, sprite_data, water_mesh = mesh_volume(
volume, water_volume, nx, ny, nz,
ghost_water=ghost_water, ghost_solid=ghost_solid
)
chunk_render_data = {}
if len(cube_data) > 0:
cube_vbo = self.ctx.buffer(cube_data.tobytes())
cube_vao = self.ctx.vertex_array(
self.shaders.chunk,
[(self.assets.vbo, '3f 2f', 'in_position', 'in_uv'),
(cube_vbo, '4f 1f 1f /i', 'in_instance', 'in_ao_1', 'in_ao_2')],
index_buffer=self.assets.ibo
)
chunk_render_data['cube'] = (cube_vao, len(cube_data))
chunk_render_data['cube_vbo_obj'] = cube_vbo
if len(sprite_data) > 0:
sprite_instance_vbo = self.ctx.buffer(sprite_data.tobytes())
sprite_vao = self.ctx.vertex_array(
self.shaders.chunk,
[(self.assets.sprite_vbo, '3f 2f', 'in_position', 'in_uv'),
(sprite_instance_vbo, '4f 1f 1f /i', 'in_instance', 'in_ao_1', 'in_ao_2')],
index_buffer=self.assets.sprite_ibo
)
chunk_render_data['sprite'] = (sprite_vao, len(sprite_data))
chunk_render_data['sprite_vbo_obj'] = sprite_instance_vbo
if len(water_mesh) > 0:
water_vbo = self.ctx.buffer(water_mesh.tobytes())
water_vao = self.ctx.vertex_array(
self.shaders.water,
[(self.assets.vbo, '3f 8x', 'in_position'),
(water_vbo, '4f /i', 'in_instance')],
index_buffer=self.assets.ibo
)
chunk_render_data['water'] = (water_vao, len(water_mesh))
chunk_render_data['water_vbo_obj'] = water_vbo
self.chunk_data[chunk_coord] = chunk_render_data
def _sync_settled_water_to_server(self, chunk_coord, water_volume):
"""Extracts non-zero water blocks and sends them as a single batch update."""
if not hasattr(self, 'network'): return