Skip to main content

yog_api/
registry.rs

1//! Registration hub and mod entry-point trait.
2//!
3//! [`Registry`] wraps the [`YogApi`] C table passed to `yog_mod_register` and
4//! provides an ergonomic Rust API over it.  All closures registered here are
5//! boxed on the heap and their raw pointers handed to the runtime; the runtime
6//! then drives them via C function-pointer calls.  Closures are intentionally
7//! leaked (never freed) — they live for the entire process lifetime, which is
8//! correct for a game server.
9
10use std::os::raw::c_void;
11
12use yog_abi::{
13    YogAdvancementEvent, YogApi, YogAttackEntityEvent, YogBlockBreakEvent, YogBlockDef,
14    YogChatEvent, YogCommandEvent, YogContainerCloseEvent, YogContainerOpenEvent, YogCraftEvent,
15    YogEntityDamageEvent, YogEntityDeathEvent, YogEntityInteractEvent, YogEntitySpawnEvent,
16    YogExplosionEvent, YogGfxApi, YogInventoryDef, YogItemDef, YogItemPickupEvent,
17    YogKeyPressEvent, YogPacketEvent, YogPlaceBlockEvent, YogPlayerDeathEvent, YogPlayerEvent,
18    YogPlayerMoveEvent, YogPlayerRespawnEvent, YogProjectileHitEvent, YogServer,
19    YogStartupGrantDef, YogStr, YogUseBlockEvent, YogUseItemEvent,
20};
21use yog_book::Book;
22use yog_command::CommandContext;
23use yog_core::Server;
24use yog_dimensions::{ChunkWriter, YogDimensionDef};
25use yog_event::{
26    AdvancementEvent, AttackEntityEvent, BlockBreakEvent, ChatEvent, ClientTickEvent,
27    ContainerCloseEvent, ContainerOpenEvent, CraftEvent, EntityDamageEvent, EntityDeathEvent,
28    EntityInteractEvent, EntitySpawnEvent, EventPhase, ExplosionEvent, ItemPickupEvent,
29    KeyPressEvent, PlaceBlockEvent, PlayerDeathEvent, PlayerJoinEvent, PlayerLeaveEvent,
30    PlayerMoveEvent, PlayerRespawnEvent, ProjectileHitEvent, ScreenEvent, UseBlockEvent,
31    UseItemEvent,
32};
33use yog_gfx::GfxContext;
34use yog_network::{Packet, PacketEvent};
35use yog_registry::{BlockDef, FurnaceRecipe, ItemDef, ShapedRecipe, ShapelessRecipe, StartupGrant};
36
37// ── CServer — implements Server via the YogServer function table ──────────────
38
39/// A handle to the runtime's server actions, backed by [`YogServer`] fn pointers.
40/// Given to every handler as `&dyn Server`.
41pub struct CServer(pub *const YogServer);
42
43unsafe impl Send for CServer {}
44unsafe impl Sync for CServer {}
45
46macro_rules! srv {
47    ($self:ident) => {
48        unsafe { &*$self.0 }
49    };
50}
51
52impl Server for CServer {
53    fn broadcast(&self, message: &str) {
54        let s = srv!(self);
55        unsafe { (s.broadcast)(s.ctx, YogStr::from_str(message)) }
56    }
57
58    fn get_block(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<String> {
59        let s = srv!(self);
60        let owned = unsafe {
61            (s.get_block)(
62                s.ctx,
63                YogStr::from_str(dimension),
64                yog_abi::YogBlockPos {
65                    x: pos.x,
66                    y: pos.y,
67                    z: pos.z,
68                },
69            )
70        };
71        if owned.is_none() {
72            return None;
73        }
74        let result = unsafe {
75            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
76                .ok()
77        };
78        unsafe { (s.free_str)(owned.ptr, owned.len) };
79        result
80    }
81
82    fn set_block(&self, dimension: &str, pos: yog_core::BlockPos, block_id: &str) -> bool {
83        let s = srv!(self);
84        unsafe {
85            (s.set_block)(
86                s.ctx,
87                YogStr::from_str(dimension),
88                yog_abi::YogBlockPos {
89                    x: pos.x,
90                    y: pos.y,
91                    z: pos.z,
92                },
93                YogStr::from_str(block_id),
94            )
95        }
96    }
97
98    fn give_item(&self, player: &str, item_id: &str, count: u32) -> bool {
99        let s = srv!(self);
100        unsafe {
101            (s.give_item)(
102                s.ctx,
103                YogStr::from_str(player),
104                YogStr::from_str(item_id),
105                count,
106            )
107        }
108    }
109
110    fn teleport(&self, player: &str, x: f64, y: f64, z: f64) -> bool {
111        let s = srv!(self);
112        unsafe {
113            (s.player_teleport)(
114                s.ctx,
115                YogStr::from_str(player),
116                yog_abi::YogVec3 { x, y, z },
117            )
118        }
119    }
120
121    fn send_to_player(&self, player: &str, channel: &str, payload: &[u8]) -> bool {
122        let s = srv!(self);
123        unsafe {
124            (s.send_to_player)(
125                s.ctx,
126                YogStr::from_str(player),
127                YogStr::from_str(channel),
128                payload.as_ptr(),
129                payload.len() as u32,
130            )
131        }
132    }
133
134    fn send_to_server(&self, channel: &str, payload: &[u8]) -> bool {
135        let s = srv!(self);
136        unsafe {
137            (s.send_to_server)(
138                s.ctx,
139                YogStr::from_str(channel),
140                payload.as_ptr(),
141                payload.len() as u32,
142            )
143        }
144    }
145
146    fn entity_teleport(&self, uuid: &str, x: f64, y: f64, z: f64) -> bool {
147        let s = srv!(self);
148        unsafe { (s.entity_teleport)(s.ctx, YogStr::from_str(uuid), yog_abi::YogVec3 { x, y, z }) }
149    }
150
151    fn entity_position(&self, uuid: &str) -> Option<(f64, f64, f64)> {
152        let s = srv!(self);
153        let mut out = yog_abi::YogVec3 {
154            x: 0.0,
155            y: 0.0,
156            z: 0.0,
157        };
158        if unsafe { (s.entity_position)(s.ctx, YogStr::from_str(uuid), &mut out) } {
159            Some((out.x, out.y, out.z))
160        } else {
161            None
162        }
163    }
164
165    fn entity_health(&self, uuid: &str) -> Option<f32> {
166        let s = srv!(self);
167        let mut hp = 0f32;
168        if unsafe { (s.entity_health)(s.ctx, YogStr::from_str(uuid), &mut hp) } {
169            Some(hp)
170        } else {
171            None
172        }
173    }
174
175    fn entity_set_health(&self, uuid: &str, health: f32) -> bool {
176        let s = srv!(self);
177        unsafe { (s.entity_set_health)(s.ctx, YogStr::from_str(uuid), health) }
178    }
179
180    fn entity_kill(&self, uuid: &str) -> bool {
181        let s = srv!(self);
182        unsafe { (s.entity_kill)(s.ctx, YogStr::from_str(uuid)) }
183    }
184
185    fn spawn_entity(
186        &self,
187        entity_type: &str,
188        dimension: &str,
189        x: f64,
190        y: f64,
191        z: f64,
192    ) -> Option<String> {
193        let s = srv!(self);
194        let owned = unsafe {
195            (s.spawn_entity)(
196                s.ctx,
197                YogStr::from_str(entity_type),
198                YogStr::from_str(dimension),
199                yog_abi::YogVec3 { x, y, z },
200            )
201        };
202        if owned.is_none() {
203            return None;
204        }
205        let result = unsafe {
206            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
207                .ok()
208        };
209        unsafe { (s.free_str)(owned.ptr, owned.len) };
210        result
211    }
212
213    fn entity_add_effect(
214        &self,
215        uuid: &str,
216        effect_id: &str,
217        duration_ticks: i32,
218        amplifier: u8,
219        show_particles: bool,
220    ) -> bool {
221        let s = srv!(self);
222        unsafe {
223            (s.entity_add_effect)(
224                s.ctx,
225                YogStr::from_str(uuid),
226                YogStr::from_str(effect_id),
227                duration_ticks,
228                amplifier,
229                show_particles,
230            )
231        }
232    }
233
234    fn entity_remove_effect(&self, uuid: &str, effect_id: &str) -> bool {
235        let s = srv!(self);
236        unsafe {
237            (s.entity_remove_effect)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(effect_id))
238        }
239    }
240
241    fn entity_clear_effects(&self, uuid: &str) -> bool {
242        let s = srv!(self);
243        unsafe { (s.entity_clear_effects)(s.ctx, YogStr::from_str(uuid)) }
244    }
245
246    fn drop_loot(&self, table_id: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
247        let s = srv!(self);
248        unsafe {
249            (s.drop_loot)(
250                s.ctx,
251                YogStr::from_str(table_id),
252                YogStr::from_str(dimension),
253                yog_abi::YogVec3 { x, y, z },
254            )
255        }
256    }
257
258    fn has_item_tag(&self, item_id: &str, tag_id: &str) -> bool {
259        let s = srv!(self);
260        unsafe { (s.has_item_tag)(s.ctx, YogStr::from_str(item_id), YogStr::from_str(tag_id)) }
261    }
262
263    fn has_block_tag(&self, block_id: &str, tag_id: &str) -> bool {
264        let s = srv!(self);
265        unsafe { (s.has_block_tag)(s.ctx, YogStr::from_str(block_id), YogStr::from_str(tag_id)) }
266    }
267
268    fn world_time(&self, dimension: &str) -> Option<i64> {
269        let s = srv!(self);
270        let mut t = 0i64;
271        if unsafe { (s.world_time)(s.ctx, YogStr::from_str(dimension), &mut t) } {
272            Some(t)
273        } else {
274            None
275        }
276    }
277
278    fn world_set_time(&self, dimension: &str, time: i64) -> bool {
279        let s = srv!(self);
280        unsafe { (s.set_time)(s.ctx, YogStr::from_str(dimension), time) }
281    }
282
283    fn world_is_raining(&self, dimension: &str) -> bool {
284        let s = srv!(self);
285        unsafe { (s.is_raining)(s.ctx, YogStr::from_str(dimension)) }
286    }
287
288    fn world_set_weather(&self, dimension: &str, raining: bool, duration_ticks: i32) -> bool {
289        let s = srv!(self);
290        unsafe { (s.set_weather)(s.ctx, YogStr::from_str(dimension), raining, duration_ticks) }
291    }
292
293    fn entity_velocity(&self, uuid: &str) -> Option<(f64, f64, f64)> {
294        let s = srv!(self);
295        let mut v = yog_abi::YogVec3 {
296            x: 0.0,
297            y: 0.0,
298            z: 0.0,
299        };
300        if unsafe { (s.entity_velocity)(s.ctx, YogStr::from_str(uuid), &mut v) } {
301            Some((v.x, v.y, v.z))
302        } else {
303            None
304        }
305    }
306
307    fn entity_set_velocity(&self, uuid: &str, vx: f64, vy: f64, vz: f64) -> bool {
308        let s = srv!(self);
309        unsafe {
310            (s.entity_set_velocity)(
311                s.ctx,
312                YogStr::from_str(uuid),
313                yog_abi::YogVec3 {
314                    x: vx,
315                    y: vy,
316                    z: vz,
317                },
318            )
319        }
320    }
321
322    fn entity_add_velocity(&self, uuid: &str, vx: f64, vy: f64, vz: f64) -> bool {
323        let s = srv!(self);
324        unsafe {
325            (s.entity_add_velocity)(
326                s.ctx,
327                YogStr::from_str(uuid),
328                yog_abi::YogVec3 {
329                    x: vx,
330                    y: vy,
331                    z: vz,
332                },
333            )
334        }
335    }
336
337    fn scoreboard_get(&self, objective: &str, player: &str) -> Option<i32> {
338        let s = srv!(self);
339        let mut score = 0i32;
340        if unsafe {
341            (s.scoreboard_get)(
342                s.ctx,
343                YogStr::from_str(objective),
344                YogStr::from_str(player),
345                &mut score,
346            )
347        } {
348            Some(score)
349        } else {
350            None
351        }
352    }
353
354    fn scoreboard_set(&self, objective: &str, player: &str, score: i32) -> bool {
355        let s = srv!(self);
356        unsafe {
357            (s.scoreboard_set)(
358                s.ctx,
359                YogStr::from_str(objective),
360                YogStr::from_str(player),
361                score,
362            )
363        }
364    }
365
366    fn scoreboard_add(&self, objective: &str, player: &str, delta: i32) -> Option<i32> {
367        let s = srv!(self);
368        let mut new_score = 0i32;
369        if unsafe {
370            (s.scoreboard_add)(
371                s.ctx,
372                YogStr::from_str(objective),
373                YogStr::from_str(player),
374                delta,
375                &mut new_score,
376            )
377        } {
378            Some(new_score)
379        } else {
380            None
381        }
382    }
383
384    fn game_dir(&self) -> String {
385        let s = srv!(self);
386        let owned = unsafe { (s.game_dir)(s.ctx) };
387        if owned.is_none() {
388            return String::new();
389        }
390        let result = unsafe {
391            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
392                .unwrap_or_default()
393        };
394        unsafe { (s.free_str)(owned.ptr, owned.len) };
395        result
396    }
397
398    fn play_sound(
399        &self,
400        dimension: &str,
401        x: f64,
402        y: f64,
403        z: f64,
404        sound_id: &str,
405        volume: f32,
406        pitch: f32,
407    ) -> bool {
408        let s = srv!(self);
409        unsafe {
410            (s.play_sound)(
411                s.ctx,
412                YogStr::from_str(dimension),
413                yog_abi::YogVec3 { x, y, z },
414                YogStr::from_str(sound_id),
415                volume,
416                pitch,
417            )
418        }
419    }
420
421    fn play_sound_to_player(&self, player: &str, sound_id: &str, volume: f32, pitch: f32) -> bool {
422        let s = srv!(self);
423        unsafe {
424            (s.play_sound_player)(
425                s.ctx,
426                YogStr::from_str(player),
427                YogStr::from_str(sound_id),
428                volume,
429                pitch,
430            )
431        }
432    }
433
434    fn send_title(
435        &self,
436        player: &str,
437        title: &str,
438        subtitle: &str,
439        fadein: i32,
440        stay: i32,
441        fadeout: i32,
442    ) -> bool {
443        let s = srv!(self);
444        unsafe {
445            (s.send_title)(
446                s.ctx,
447                YogStr::from_str(player),
448                YogStr::from_str(title),
449                YogStr::from_str(subtitle),
450                fadein,
451                stay,
452                fadeout,
453            )
454        }
455    }
456
457    fn entity_rotation(&self, uuid: &str) -> Option<(f32, f32)> {
458        let s = srv!(self);
459        let mut out = yog_abi::YogVec3 {
460            x: 0.0,
461            y: 0.0,
462            z: 0.0,
463        };
464        let ok = unsafe { (s.entity_rotation)(s.ctx, YogStr::from_str(uuid), &mut out) };
465        if ok {
466            Some((out.x as f32, out.y as f32))
467        } else {
468            None
469        }
470    }
471
472    fn send_actionbar(&self, player: &str, message: &str) -> bool {
473        let s = srv!(self);
474        unsafe { (s.send_actionbar)(s.ctx, YogStr::from_str(player), YogStr::from_str(message)) }
475    }
476
477    fn kick_player(&self, player: &str, reason: &str) -> bool {
478        let s = srv!(self);
479        unsafe { (s.kick_player)(s.ctx, YogStr::from_str(player), YogStr::from_str(reason)) }
480    }
481
482    fn set_gamemode(&self, player: &str, gamemode: &str) -> bool {
483        let s = srv!(self);
484        unsafe { (s.set_gamemode)(s.ctx, YogStr::from_str(player), YogStr::from_str(gamemode)) }
485    }
486
487    fn bossbar_create(&self, id: &str, title: &str, color: &str, style: &str) -> bool {
488        let s = srv!(self);
489        unsafe {
490            (s.bossbar_create)(
491                s.ctx,
492                YogStr::from_str(id),
493                YogStr::from_str(title),
494                YogStr::from_str(color),
495                YogStr::from_str(style),
496            )
497        }
498    }
499
500    fn bossbar_remove(&self, id: &str) -> bool {
501        let s = srv!(self);
502        unsafe { (s.bossbar_remove)(s.ctx, YogStr::from_str(id)) }
503    }
504
505    fn bossbar_set_title(&self, id: &str, title: &str) -> bool {
506        let s = srv!(self);
507        unsafe { (s.bossbar_set_title)(s.ctx, YogStr::from_str(id), YogStr::from_str(title)) }
508    }
509
510    fn bossbar_set_progress(&self, id: &str, progress: f32) -> bool {
511        let s = srv!(self);
512        unsafe { (s.bossbar_set_progress)(s.ctx, YogStr::from_str(id), progress) }
513    }
514
515    fn bossbar_set_color(&self, id: &str, color: &str) -> bool {
516        let s = srv!(self);
517        unsafe { (s.bossbar_set_color)(s.ctx, YogStr::from_str(id), YogStr::from_str(color)) }
518    }
519
520    fn bossbar_add_player(&self, id: &str, player: &str) -> bool {
521        let s = srv!(self);
522        unsafe { (s.bossbar_add_player)(s.ctx, YogStr::from_str(id), YogStr::from_str(player)) }
523    }
524
525    fn bossbar_remove_player(&self, id: &str, player: &str) -> bool {
526        let s = srv!(self);
527        unsafe { (s.bossbar_remove_player)(s.ctx, YogStr::from_str(id), YogStr::from_str(player)) }
528    }
529
530    fn bossbar_set_visible(&self, id: &str, visible: bool) -> bool {
531        let s = srv!(self);
532        unsafe { (s.bossbar_set_visible)(s.ctx, YogStr::from_str(id), visible) }
533    }
534
535    fn online_players(&self) -> Vec<String> {
536        let s = srv!(self);
537        let owned = unsafe { (s.online_players)(s.ctx) };
538        if owned.is_none() {
539            return Vec::new();
540        }
541        let text = unsafe {
542            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
543                .unwrap_or_default()
544        };
545        unsafe { (s.free_str)(owned.ptr, owned.len) };
546        if text.is_empty() {
547            Vec::new()
548        } else {
549            text.lines().map(str::to_owned).collect()
550        }
551    }
552
553    fn get_block_nbt(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<String> {
554        let s = srv!(self);
555        let owned = unsafe {
556            (s.get_block_nbt)(
557                s.ctx,
558                YogStr::from_str(dimension),
559                yog_abi::YogBlockPos {
560                    x: pos.x,
561                    y: pos.y,
562                    z: pos.z,
563                },
564            )
565        };
566        if owned.is_none() {
567            return None;
568        }
569        let result = unsafe {
570            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
571                .ok()
572        };
573        unsafe { (s.free_str)(owned.ptr, owned.len) };
574        result
575    }
576
577    fn set_block_nbt(&self, dimension: &str, pos: yog_core::BlockPos, snbt: &str) -> bool {
578        let s = srv!(self);
579        unsafe {
580            (s.set_block_nbt)(
581                s.ctx,
582                YogStr::from_str(dimension),
583                yog_abi::YogBlockPos {
584                    x: pos.x,
585                    y: pos.y,
586                    z: pos.z,
587                },
588                YogStr::from_str(snbt),
589            )
590        }
591    }
592
593    fn get_inventory_slot(
594        &self,
595        dimension: &str,
596        pos: yog_core::BlockPos,
597        slot: u32,
598    ) -> Option<(String, u32)> {
599        let s = srv!(self);
600        let owned = unsafe {
601            (s.get_inventory_slot)(
602                s.ctx,
603                YogStr::from_str(dimension),
604                yog_abi::YogBlockPos {
605                    x: pos.x,
606                    y: pos.y,
607                    z: pos.z,
608                },
609                slot,
610            )
611        };
612        if owned.is_none() {
613            return None;
614        }
615        let text = unsafe {
616            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
617                .unwrap_or_default()
618        };
619        unsafe { (s.free_str)(owned.ptr, owned.len) };
620        let (item_id, count) = text.split_once('\t')?;
621        Some((item_id.to_owned(), count.parse().ok()?))
622    }
623
624    fn set_inventory_slot(
625        &self,
626        dimension: &str,
627        pos: yog_core::BlockPos,
628        slot: u32,
629        item_id: &str,
630        count: u32,
631    ) -> bool {
632        let s = srv!(self);
633        unsafe {
634            (s.set_inventory_slot)(
635                s.ctx,
636                YogStr::from_str(dimension),
637                yog_abi::YogBlockPos {
638                    x: pos.x,
639                    y: pos.y,
640                    z: pos.z,
641                },
642                slot,
643                YogStr::from_str(item_id),
644                count,
645            )
646        }
647    }
648
649    fn player_inventory(&self, player: &str) -> Vec<(u32, String, u32)> {
650        let s = srv!(self);
651        let owned = unsafe { (s.player_inventory)(s.ctx, YogStr::from_str(player)) };
652        if owned.is_none() {
653            return Vec::new();
654        }
655        let text = unsafe {
656            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
657                .unwrap_or_default()
658        };
659        unsafe { (s.free_str)(owned.ptr, owned.len) };
660        text.lines()
661            .filter_map(|line| {
662                let mut it = line.split('\t');
663                let slot: u32 = it.next()?.parse().ok()?;
664                let item_id = it.next()?.to_owned();
665                let count: u32 = it.next()?.parse().ok()?;
666                Some((slot, item_id, count))
667            })
668            .collect()
669    }
670
671    fn player_set_slot(&self, player: &str, slot: u32, item_id: &str, count: u32) -> bool {
672        let s = srv!(self);
673        unsafe {
674            (s.player_set_slot)(
675                s.ctx,
676                YogStr::from_str(player),
677                slot,
678                YogStr::from_str(item_id),
679                count,
680            )
681        }
682    }
683
684    fn teleport_to_dim(&self, player: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
685        let s = srv!(self);
686        unsafe {
687            (s.player_teleport_dim)(
688                s.ctx,
689                YogStr::from_str(player),
690                YogStr::from_str(dimension),
691                yog_abi::YogVec3 { x, y, z },
692            )
693        }
694    }
695
696    fn entity_teleport_to_dim(&self, uuid: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
697        let s = srv!(self);
698        unsafe {
699            (s.entity_teleport_dim)(
700                s.ctx,
701                YogStr::from_str(uuid),
702                YogStr::from_str(dimension),
703                yog_abi::YogVec3 { x, y, z },
704            )
705        }
706    }
707
708    fn world_entity_count(&self, dimension: &str, entity_type: &str) -> i32 {
709        let s = srv!(self);
710        unsafe {
711            (s.world_entity_count)(
712                s.ctx,
713                YogStr::from_str(dimension),
714                YogStr::from_str(entity_type),
715            )
716        }
717    }
718
719    fn entity_get_nbt(&self, uuid: &str) -> Option<String> {
720        let s = srv!(self);
721        let owned = unsafe { (s.entity_get_nbt)(s.ctx, YogStr::from_str(uuid)) };
722        if owned.is_none() {
723            return None;
724        }
725        let result = unsafe {
726            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
727                .ok()
728        };
729        unsafe { (s.free_str)(owned.ptr, owned.len) };
730        result
731    }
732
733    fn entity_set_nbt(&self, uuid: &str, snbt: &str) -> bool {
734        let s = srv!(self);
735        unsafe { (s.entity_set_nbt)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(snbt)) }
736    }
737
738    fn spawn_particles(
739        &self,
740        dimension: &str,
741        x: f64,
742        y: f64,
743        z: f64,
744        particle_type: &str,
745        count: i32,
746        dx: f64,
747        dy: f64,
748        dz: f64,
749        speed: f64,
750    ) -> bool {
751        let s = srv!(self);
752        unsafe {
753            (s.spawn_particles)(
754                s.ctx,
755                YogStr::from_str(dimension),
756                yog_abi::YogVec3 { x, y, z },
757                YogStr::from_str(particle_type),
758                count,
759                dx,
760                dy,
761                dz,
762                speed,
763            )
764        }
765    }
766
767    fn entity_attribute_get(&self, uuid: &str, attribute_id: &str) -> Option<f64> {
768        let s = srv!(self);
769        let v = unsafe {
770            (s.entity_attribute_get)(
771                s.ctx,
772                YogStr::from_str(uuid),
773                YogStr::from_str(attribute_id),
774            )
775        };
776        if v.is_nan() {
777            None
778        } else {
779            Some(v)
780        }
781    }
782
783    fn entity_attribute_set(&self, uuid: &str, attribute_id: &str, value: f64) -> bool {
784        let s = srv!(self);
785        unsafe {
786            (s.entity_attribute_set)(
787                s.ctx,
788                YogStr::from_str(uuid),
789                YogStr::from_str(attribute_id),
790                value,
791            )
792        }
793    }
794
795    fn get_held_item_nbt(&self, player: &str) -> Option<String> {
796        let s = srv!(self);
797        let owned = unsafe { (s.get_held_item_nbt)(s.ctx, YogStr::from_str(player)) };
798        if owned.is_none() {
799            return None;
800        }
801        let result = unsafe {
802            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
803                .ok()
804        };
805        unsafe { (s.free_str)(owned.ptr, owned.len) };
806        result
807    }
808
809    fn set_held_item_nbt(&self, player: &str, snbt: &str) -> bool {
810        let s = srv!(self);
811        unsafe { (s.set_held_item_nbt)(s.ctx, YogStr::from_str(player), YogStr::from_str(snbt)) }
812    }
813
814    fn get_offhand_item_nbt(&self, player: &str) -> Option<String> {
815        let s = srv!(self);
816        let owned = unsafe { (s.get_offhand_item_nbt)(s.ctx, YogStr::from_str(player)) };
817        if owned.is_none() {
818            return None;
819        }
820        let result = unsafe {
821            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
822                .ok()
823        };
824        unsafe { (s.free_str)(owned.ptr, owned.len) };
825        result
826    }
827
828    fn set_offhand_item_nbt(&self, player: &str, snbt: &str) -> bool {
829        let s = srv!(self);
830        unsafe { (s.set_offhand_item_nbt)(s.ctx, YogStr::from_str(player), YogStr::from_str(snbt)) }
831    }
832
833    fn get_slot_item(&self, player: &str, slot: u32) -> Option<(String, u32, String)> {
834        let s = srv!(self);
835        let owned = unsafe { (s.get_slot_item)(s.ctx, YogStr::from_str(player), slot) };
836        if owned.is_none() {
837            return None;
838        }
839        let text = unsafe {
840            String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
841                .unwrap_or_default()
842        };
843        unsafe { (s.free_str)(owned.ptr, owned.len) };
844        let mut it = text.splitn(3, '\t');
845        let item_id = it.next()?.to_owned();
846        let count: u32 = it.next()?.parse().ok()?;
847        let nbt = it.next().unwrap_or("{}").to_owned();
848        Some((item_id, count, nbt))
849    }
850
851    fn set_slot_item(
852        &self,
853        player: &str,
854        slot: u32,
855        item_id: &str,
856        count: u32,
857        snbt: &str,
858    ) -> bool {
859        let s = srv!(self);
860        unsafe {
861            (s.set_slot_item)(
862                s.ctx,
863                YogStr::from_str(player),
864                slot,
865                YogStr::from_str(item_id),
866                count,
867                YogStr::from_str(snbt),
868            )
869        }
870    }
871}
872
873// ── Trampoline helpers ────────────────────────────────────────────────────────
874//
875// Each trampoline is a `unsafe extern "C" fn` that:
876//   1. Casts `ud` back to the original boxed closure.
877//   2. Converts ABI C structs to Rust event types.
878//   3. Builds a `CServer` from the `*const YogServer`.
879//   4. Calls the closure.
880//
881// Closures are Box::into_raw'd in Registry methods — they are INTENTIONALLY
882// leaked and live for the process lifetime.
883
884// ── Trampoline helpers ────────────────────────────────────────────────────────
885//
886// All phased event trampolines share the same pattern:
887//   `phase: u8`  0 = EventPhase::Pre, 1 = EventPhase::Post
888//   Return value is meaningful only in Pre phase.
889
890macro_rules! trampoline_phased {
891    ($name:ident, $abi_ev:ty, $rust_ev:ty, |$ev:ident| $build:expr) => {
892        unsafe extern "C" fn $name<F>(
893            ud: *mut c_void,
894            srv: *const YogServer,
895            ev: *const $abi_ev,
896            phase: u8,
897        ) -> bool
898        where
899            F: Fn(&$rust_ev, EventPhase, &dyn Server) -> bool + Send + Sync,
900        {
901            let f = &*(ud as *const F);
902            let $ev = &*ev;
903            let rust_ev = $build;
904            let p = if phase == 0 {
905                EventPhase::Pre
906            } else {
907                EventPhase::Post
908            };
909            f(&rust_ev, p, &CServer(srv))
910        }
911    };
912}
913
914trampoline_phased!(
915    trampoline_block_break,
916    YogBlockBreakEvent,
917    BlockBreakEvent,
918    |ev| BlockBreakEvent {
919        player_name: ev.player.as_str().to_owned(),
920        block_id: ev.block.as_str().to_owned(),
921        pos: yog_core::BlockPos {
922            x: ev.pos.x,
923            y: ev.pos.y,
924            z: ev.pos.z
925        },
926        dimension: ev.dimension.as_str().to_owned(),
927    }
928);
929
930trampoline_phased!(trampoline_chat, YogChatEvent, ChatEvent, |ev| ChatEvent {
931    player_name: ev.player.as_str().to_owned(),
932    message: ev.message.as_str().to_owned(),
933    dimension: ev.dimension.as_str().to_owned(),
934});
935
936trampoline_phased!(
937    trampoline_player_join,
938    YogPlayerEvent,
939    PlayerJoinEvent,
940    |ev| PlayerJoinEvent {
941        player_name: ev.player.as_str().to_owned(),
942        uuid: ev.uuid.as_str().to_owned(),
943        dimension: ev.dimension.as_str().to_owned(),
944    }
945);
946
947trampoline_phased!(
948    trampoline_player_leave,
949    YogPlayerEvent,
950    PlayerLeaveEvent,
951    |ev| PlayerLeaveEvent {
952        player_name: ev.player.as_str().to_owned(),
953        uuid: ev.uuid.as_str().to_owned(),
954        dimension: ev.dimension.as_str().to_owned(),
955    }
956);
957
958trampoline_phased!(trampoline_use_item, YogUseItemEvent, UseItemEvent, |ev| {
959    UseItemEvent {
960        player_name: ev.player.as_str().to_owned(),
961        item_id: ev.item.as_str().to_owned(),
962        sneaking: ev.sneaking,
963        dimension: ev.dimension.as_str().to_owned(),
964    }
965});
966
967trampoline_phased!(
968    trampoline_use_block,
969    YogUseBlockEvent,
970    UseBlockEvent,
971    |ev| UseBlockEvent {
972        player_name: ev.player.as_str().to_owned(),
973        block_id: ev.block.as_str().to_owned(),
974        pos: yog_core::BlockPos {
975            x: ev.pos.x,
976            y: ev.pos.y,
977            z: ev.pos.z
978        },
979        dimension: ev.dimension.as_str().to_owned(),
980    }
981);
982
983trampoline_phased!(
984    trampoline_attack_entity,
985    YogAttackEntityEvent,
986    AttackEntityEvent,
987    |ev| AttackEntityEvent {
988        player_name: ev.player.as_str().to_owned(),
989        target_type: ev.target_type.as_str().to_owned(),
990        target_uuid: ev.target_uuid.as_str().to_owned(),
991        dimension: ev.dimension.as_str().to_owned(),
992    }
993);
994
995trampoline_phased!(
996    trampoline_entity_damage,
997    YogEntityDamageEvent,
998    EntityDamageEvent,
999    |ev| EntityDamageEvent {
1000        entity_type: ev.entity_type.as_str().to_owned(),
1001        uuid: ev.uuid.as_str().to_owned(),
1002        amount: ev.amount,
1003        source: ev.source.as_str().to_owned(),
1004        dimension: ev.dimension.as_str().to_owned(),
1005    }
1006);
1007
1008trampoline_phased!(
1009    trampoline_entity_death,
1010    YogEntityDeathEvent,
1011    EntityDeathEvent,
1012    |ev| EntityDeathEvent {
1013        entity_type: ev.entity_type.as_str().to_owned(),
1014        uuid: ev.uuid.as_str().to_owned(),
1015        source: ev.source.as_str().to_owned(),
1016        dimension: ev.dimension.as_str().to_owned(),
1017    }
1018);
1019
1020trampoline_phased!(
1021    trampoline_entity_spawn,
1022    YogEntitySpawnEvent,
1023    EntitySpawnEvent,
1024    |ev| EntitySpawnEvent {
1025        entity_type: ev.entity_type.as_str().to_owned(),
1026        uuid: ev.uuid.as_str().to_owned(),
1027        dimension: ev.dimension.as_str().to_owned(),
1028    }
1029);
1030
1031trampoline_phased!(
1032    trampoline_place_block,
1033    YogPlaceBlockEvent,
1034    PlaceBlockEvent,
1035    |ev| PlaceBlockEvent {
1036        player_name: ev.player.as_str().to_owned(),
1037        block_id: ev.block.as_str().to_owned(),
1038        pos: yog_core::BlockPos {
1039            x: ev.pos.x,
1040            y: ev.pos.y,
1041            z: ev.pos.z
1042        },
1043        dimension: ev.dimension.as_str().to_owned(),
1044    }
1045);
1046
1047trampoline_phased!(
1048    trampoline_player_death,
1049    YogPlayerDeathEvent,
1050    PlayerDeathEvent,
1051    |ev| PlayerDeathEvent {
1052        player_name: ev.player.as_str().to_owned(),
1053        uuid: ev.uuid.as_str().to_owned(),
1054        source: ev.source.as_str().to_owned(),
1055        dimension: ev.dimension.as_str().to_owned(),
1056    }
1057);
1058
1059trampoline_phased!(
1060    trampoline_player_respawn,
1061    YogPlayerRespawnEvent,
1062    PlayerRespawnEvent,
1063    |ev| PlayerRespawnEvent {
1064        player_name: ev.player.as_str().to_owned(),
1065        uuid: ev.uuid.as_str().to_owned(),
1066        at_anchor: ev.at_anchor,
1067        dimension: ev.dimension.as_str().to_owned(),
1068    }
1069);
1070
1071trampoline_phased!(
1072    trampoline_advancement,
1073    YogAdvancementEvent,
1074    AdvancementEvent,
1075    |ev| AdvancementEvent {
1076        player_name: ev.player.as_str().to_owned(),
1077        uuid: ev.uuid.as_str().to_owned(),
1078        advancement_id: ev.advancement.as_str().to_owned(),
1079        dimension: ev.dimension.as_str().to_owned(),
1080    }
1081);
1082
1083trampoline_phased!(
1084    trampoline_entity_interact,
1085    YogEntityInteractEvent,
1086    EntityInteractEvent,
1087    |ev| EntityInteractEvent {
1088        player_name: ev.player.as_str().to_owned(),
1089        player_uuid: ev.player_uuid.as_str().to_owned(),
1090        entity_type: ev.entity_type.as_str().to_owned(),
1091        entity_uuid: ev.entity_uuid.as_str().to_owned(),
1092        hand: ev.hand.as_str().to_owned(),
1093        dimension: ev.dimension.as_str().to_owned(),
1094    }
1095);
1096
1097trampoline_phased!(trampoline_craft, YogCraftEvent, CraftEvent, |ev| {
1098    CraftEvent {
1099        player_name: ev.player.as_str().to_owned(),
1100        player_uuid: ev.player_uuid.as_str().to_owned(),
1101        result_item: ev.result_item.as_str().to_owned(),
1102        result_count: ev.result_count,
1103        dimension: ev.dimension.as_str().to_owned(),
1104    }
1105});
1106
1107trampoline_phased!(
1108    trampoline_explosion,
1109    YogExplosionEvent,
1110    ExplosionEvent,
1111    |ev| ExplosionEvent {
1112        dimension: ev.dimension.as_str().to_owned(),
1113        x: ev.x,
1114        y: ev.y,
1115        z: ev.z,
1116        power: ev.power,
1117        cause_uuid: ev.cause_uuid.as_str().to_owned(),
1118    }
1119);
1120
1121trampoline_phased!(
1122    trampoline_item_pickup,
1123    YogItemPickupEvent,
1124    ItemPickupEvent,
1125    |ev| ItemPickupEvent {
1126        player_name: ev.player.as_str().to_owned(),
1127        player_uuid: ev.player_uuid.as_str().to_owned(),
1128        item_id: ev.item_id.as_str().to_owned(),
1129        item_count: ev.item_count,
1130        entity_uuid: ev.entity_uuid.as_str().to_owned(),
1131        dimension: ev.dimension.as_str().to_owned(),
1132    }
1133);
1134
1135trampoline_phased!(
1136    trampoline_player_move,
1137    YogPlayerMoveEvent,
1138    PlayerMoveEvent,
1139    |ev| PlayerMoveEvent {
1140        player_name: ev.player.as_str().to_owned(),
1141        player_uuid: ev.player_uuid.as_str().to_owned(),
1142        x: ev.x,
1143        y: ev.y,
1144        z: ev.z,
1145        yaw: ev.yaw,
1146        pitch: ev.pitch,
1147        dimension: ev.dimension.as_str().to_owned(),
1148    }
1149);
1150
1151trampoline_phased!(
1152    trampoline_container_open,
1153    YogContainerOpenEvent,
1154    ContainerOpenEvent,
1155    |ev| ContainerOpenEvent {
1156        player_name: ev.player.as_str().to_owned(),
1157        player_uuid: ev.player_uuid.as_str().to_owned(),
1158        container_type: ev.container_type.as_str().to_owned(),
1159        dimension: ev.dimension.as_str().to_owned(),
1160    }
1161);
1162
1163trampoline_phased!(
1164    trampoline_container_close,
1165    YogContainerCloseEvent,
1166    ContainerCloseEvent,
1167    |ev| ContainerCloseEvent {
1168        player_name: ev.player.as_str().to_owned(),
1169        player_uuid: ev.player_uuid.as_str().to_owned(),
1170        dimension: ev.dimension.as_str().to_owned(),
1171    }
1172);
1173
1174trampoline_phased!(
1175    trampoline_projectile_hit,
1176    YogProjectileHitEvent,
1177    ProjectileHitEvent,
1178    |ev| ProjectileHitEvent {
1179        projectile_type: ev.projectile_type.as_str().to_owned(),
1180        projectile_uuid: ev.projectile_uuid.as_str().to_owned(),
1181        shooter_uuid: ev.shooter_uuid.as_str().to_owned(),
1182        hit_type: ev.hit_type.as_str().to_owned(),
1183        hit_entity_uuid: ev.hit_entity_uuid.as_str().to_owned(),
1184        x: ev.x,
1185        y: ev.y,
1186        z: ev.z,
1187        dimension: ev.dimension.as_str().to_owned(),
1188    }
1189);
1190
1191unsafe extern "C" fn trampoline_server_fn<F>(ud: *mut c_void, srv: *const YogServer)
1192where
1193    F: Fn(&dyn Server) + Send + Sync,
1194{
1195    let f = &*(ud as *const F);
1196    f(&CServer(srv));
1197}
1198
1199unsafe extern "C" fn trampoline_packet<F>(
1200    ud: *mut c_void,
1201    srv: *const YogServer,
1202    ev: *const YogPacketEvent,
1203) where
1204    F: Fn(&PacketEvent, &dyn Server) + Send + Sync,
1205{
1206    let f = &*(ud as *const F);
1207    let ev = &*ev;
1208    let rust_ev = PacketEvent {
1209        channel: ev.channel.as_str().to_owned(),
1210        player: ev.player.as_str().to_owned(),
1211        payload: std::slice::from_raw_parts(ev.payload, ev.payload_len as usize).to_vec(),
1212    };
1213    f(&rust_ev, &CServer(srv));
1214}
1215
1216unsafe extern "C" fn trampoline_command<F>(
1217    ud: *mut c_void,
1218    srv: *const YogServer,
1219    ev: *const YogCommandEvent,
1220    reply_buf: *mut u8,
1221    reply_cap: u32,
1222    reply_len: *mut u32,
1223) where
1224    F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync,
1225{
1226    let f = &*(ud as *const F);
1227    let ev = &*ev;
1228    let ctx = CommandContext {
1229        name: ev.name.as_str().to_owned(),
1230        args: ev.args.as_str().to_owned(),
1231        source: ev.source.as_str().to_owned(),
1232        uuid: ev.uuid.as_str().to_owned(),
1233        dimension: ev.dimension.as_str().to_owned(),
1234    };
1235    *reply_len = 0;
1236    if let Some(reply) = f(&ctx, &CServer(srv)) {
1237        let bytes = reply.as_bytes();
1238        let n = bytes.len().min(reply_cap as usize);
1239        std::ptr::copy_nonoverlapping(bytes.as_ptr(), reply_buf, n);
1240        *reply_len = n as u32;
1241    }
1242}
1243
1244unsafe extern "C" fn trampoline_scheduled<F>(ud: *mut c_void, srv: *const YogServer)
1245where
1246    F: Fn(&dyn Server) + Send + Sync,
1247{
1248    let f = &*(ud as *const F);
1249    f(&CServer(srv));
1250}
1251
1252// ── ABI minor 10 — client-side trampolines ────────────────────────────────────
1253
1254unsafe extern "C" fn trampoline_client_tick<F>(ud: *mut c_void)
1255where
1256    F: Fn(&ClientTickEvent) + Send + Sync,
1257{
1258    let f = &*(ud as *const F);
1259    f(&ClientTickEvent {});
1260}
1261
1262unsafe extern "C" fn trampoline_hud_render<F>(ud: *mut c_void, gfx: *const YogGfxApi)
1263where
1264    F: Fn(&GfxContext) + Send + Sync,
1265{
1266    let f = &*(ud as *const F);
1267    f(&GfxContext::from_raw(gfx));
1268}
1269
1270unsafe extern "C" fn trampoline_world_render<F>(ud: *mut c_void, gfx: *const YogGfxApi)
1271where
1272    F: Fn(&GfxContext) + Send + Sync,
1273{
1274    let f = &*(ud as *const F);
1275    f(&GfxContext::from_raw(gfx));
1276}
1277
1278unsafe extern "C" fn trampoline_key_press<F>(ud: *mut c_void, ev: *const YogKeyPressEvent) -> bool
1279where
1280    F: Fn(&KeyPressEvent) -> bool + Send + Sync,
1281{
1282    let f = &*(ud as *const F);
1283    let e = &*ev;
1284    f(&KeyPressEvent {
1285        key_code: e.key_code,
1286        scan_code: e.scan_code,
1287        action: e.action,
1288        modifiers: e.modifiers,
1289    })
1290}
1291
1292unsafe extern "C" fn trampoline_screen<F>(ud: *mut c_void, screen_class: YogStr) -> bool
1293where
1294    F: Fn(&ScreenEvent) + Send + Sync,
1295{
1296    let f = &*(ud as *const F);
1297    f(&ScreenEvent {
1298        screen_class: screen_class.as_str().to_owned(),
1299    });
1300    true
1301}
1302
1303// ── Registry ─────────────────────────────────────────────────────────────────
1304
1305/// Wraps the [`YogApi`] table and provides an ergonomic registration API.
1306///
1307/// Obtained inside `yog_mod_register` via `export_mod!`.  Closures registered
1308/// here are boxed and leaked — they live as long as the process (which is the
1309/// correct lifetime for a server mod).
1310/// Pointer to the runtime's `YogApi` table (a process-lifetime static in the
1311/// runtime), captured when the mod registers. Lets free functions like
1312/// [`installed_mods`] work outside of `register()` — e.g. in UI handlers.
1313static GLOBAL_API: std::sync::atomic::AtomicPtr<YogApi> =
1314    std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());
1315
1316/// The runtime's `YogApi` table, null before this mod registered.
1317pub(crate) fn global_api() -> *mut YogApi {
1318    GLOBAL_API.load(std::sync::atomic::Ordering::Acquire)
1319}
1320
1321/// Metadata of an installed mod, as reported by the loader.
1322#[derive(Debug, Clone)]
1323pub struct ModInfo {
1324    /// `"yog"` for .yog mods, `"platform"` for loader (Java) mods.
1325    pub source: String,
1326    pub id: String,
1327    pub name: String,
1328    pub version: String,
1329    /// Comma-separated author list (may be empty).
1330    pub authors: String,
1331    pub description: String,
1332}
1333
1334/// All installed mods known to the loader: .yog mods plus, where the host
1335/// exposes them, platform (Java) mods. Callable at any time after this mod's
1336/// `register()` ran — including client-side UI handlers. Note that during
1337/// `register()` mods that load after this one are not in the list yet; query
1338/// lazily (e.g. on first render) for a complete view.
1339pub fn installed_mods() -> Vec<ModInfo> {
1340    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1341    if api.is_null() {
1342        return Vec::new();
1343    }
1344    let owned = unsafe { ((*api).mods_list)((*api).ctx) };
1345    if owned.is_none() {
1346        return Vec::new();
1347    }
1348    let text = unsafe {
1349        String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
1350            .unwrap_or_default()
1351    };
1352    unsafe { ((*api).free_str)(owned.ptr, owned.len) };
1353    text.lines()
1354        .filter_map(|line| {
1355            let mut f = line.split('\t');
1356            Some(ModInfo {
1357                source: f.next()?.to_string(),
1358                id: f.next()?.to_string(),
1359                name: f.next().unwrap_or_default().to_string(),
1360                version: f.next().unwrap_or_default().to_string(),
1361                authors: f.next().unwrap_or_default().to_string(),
1362                description: f.next().unwrap_or_default().to_string(),
1363            })
1364        })
1365        .collect()
1366}
1367
1368/// Open the Yog UI registered as `ui_id` (client side; no-op on dedicated
1369/// servers). `modal` blocks game input, `pause` pauses singleplayer. Callable
1370/// from any handler after registration — e.g. an `on_client_packet` handler.
1371pub fn open_ui(ui_id: &str, modal: bool, pause: bool) {
1372    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1373    if api.is_null() {
1374        return;
1375    }
1376    unsafe { ((*api).ui_open)((*api).ctx, YogStr::from_str(ui_id), modal, pause) }
1377}
1378
1379/// Close the Yog UI screen showing `ui_id` — e.g. from that screen's own
1380/// "Done" button. Does nothing when another screen is open. Deferred onto the
1381/// render thread, so the handler that calls it finishes first. Client side;
1382/// a no-op on dedicated servers.
1383pub fn close_ui(ui_id: &str) {
1384    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1385    if api.is_null() {
1386        return;
1387    }
1388    unsafe { ((*api).ui_close)((*api).ctx, YogStr::from_str(ui_id)) }
1389}
1390
1391/// What a [`Registry::register_ui`] handler returns: `()` (never marks
1392/// events as used) or `bool` (`true` = the handler used this `key:`/`char:`
1393/// event — the host then doesn't, e.g. Esc doesn't close the screen).
1394pub trait UiHandled {
1395    fn handled(self) -> bool;
1396}
1397
1398impl UiHandled for () {
1399    fn handled(self) -> bool {
1400        false
1401    }
1402}
1403
1404impl UiHandled for bool {
1405    fn handled(self) -> bool {
1406        self
1407    }
1408}
1409
1410/// Handle to the runtime's server-action table, usable from any handler after
1411/// registration — including client-side ones that don't receive `&dyn Server`
1412/// (UI event handlers, client tick). Server-world actions are no-ops client
1413/// side, but networking (`send_to_server`) and similar client-safe calls work.
1414pub fn server() -> Option<CServer> {
1415    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1416    if api.is_null() {
1417        return None;
1418    }
1419    let srv = unsafe { (*api).server };
1420    if srv.is_null() {
1421        return None;
1422    }
1423    Some(CServer(srv))
1424}
1425
1426pub struct Registry {
1427    api: *const YogApi,
1428}
1429
1430// SAFETY: `api` is a static provided by the runtime, valid for process lifetime.
1431unsafe impl Send for Registry {}
1432unsafe impl Sync for Registry {}
1433
1434impl Registry {
1435    /// Build from the pointer passed by the runtime. Only called by `export_mod!`.
1436    ///
1437    /// # Safety
1438    ///
1439    /// `api` must point to the runtime's `YogApi` table, valid for the rest of
1440    /// the process.
1441    pub unsafe fn from_raw(api: *const YogApi) -> Self {
1442        GLOBAL_API.store(api as *mut YogApi, std::sync::atomic::Ordering::Release);
1443        Self { api }
1444    }
1445
1446    #[inline]
1447    fn ctx(&self) -> *mut c_void {
1448        unsafe { (*self.api).ctx }
1449    }
1450
1451    // ── helpers ──────────────────────────────────────────────────────────────
1452
1453    fn leak<F: 'static>(f: F) -> *mut c_void {
1454        Box::into_raw(Box::new(f)) as *mut c_void
1455    }
1456
1457    // ── events ───────────────────────────────────────────────────────────────
1458    //
1459    // All handlers receive `(event, EventPhase, &dyn Server) -> bool`.
1460    // In `Pre` phase, returning `false` cancels the action.
1461    // In `Post` phase, the return value is ignored.
1462    // A single registration fires for BOTH phases.
1463
1464    pub fn on_block_break<F>(&mut self, handler: F)
1465    where
1466        F: Fn(&BlockBreakEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1467    {
1468        let ud = Self::leak(handler);
1469        unsafe { ((*self.api).on_block_break)(self.ctx(), ud, trampoline_block_break::<F>) }
1470    }
1471
1472    pub fn on_chat<F>(&mut self, handler: F)
1473    where
1474        F: Fn(&ChatEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1475    {
1476        let ud = Self::leak(handler);
1477        unsafe { ((*self.api).on_chat)(self.ctx(), ud, trampoline_chat::<F>) }
1478    }
1479
1480    pub fn on_player_join<F>(&mut self, handler: F)
1481    where
1482        F: Fn(&PlayerJoinEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1483    {
1484        let ud = Self::leak(handler);
1485        unsafe { ((*self.api).on_player_join)(self.ctx(), ud, trampoline_player_join::<F>) }
1486    }
1487
1488    pub fn on_player_leave<F>(&mut self, handler: F)
1489    where
1490        F: Fn(&PlayerLeaveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1491    {
1492        let ud = Self::leak(handler);
1493        unsafe { ((*self.api).on_player_leave)(self.ctx(), ud, trampoline_player_leave::<F>) }
1494    }
1495
1496    pub fn on_use_item<F>(&mut self, handler: F)
1497    where
1498        F: Fn(&UseItemEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1499    {
1500        let ud = Self::leak(handler);
1501        unsafe { ((*self.api).on_use_item)(self.ctx(), ud, trampoline_use_item::<F>) }
1502    }
1503
1504    pub fn on_use_block<F>(&mut self, handler: F)
1505    where
1506        F: Fn(&UseBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1507    {
1508        let ud = Self::leak(handler);
1509        unsafe { ((*self.api).on_use_block)(self.ctx(), ud, trampoline_use_block::<F>) }
1510    }
1511
1512    pub fn on_attack_entity<F>(&mut self, handler: F)
1513    where
1514        F: Fn(&AttackEntityEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1515    {
1516        let ud = Self::leak(handler);
1517        unsafe { ((*self.api).on_attack_entity)(self.ctx(), ud, trampoline_attack_entity::<F>) }
1518    }
1519
1520    pub fn on_entity_damage<F>(&mut self, handler: F)
1521    where
1522        F: Fn(&EntityDamageEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1523    {
1524        let ud = Self::leak(handler);
1525        unsafe { ((*self.api).on_entity_damage)(self.ctx(), ud, trampoline_entity_damage::<F>) }
1526    }
1527
1528    pub fn on_entity_death<F>(&mut self, handler: F)
1529    where
1530        F: Fn(&EntityDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1531    {
1532        let ud = Self::leak(handler);
1533        unsafe { ((*self.api).on_entity_death)(self.ctx(), ud, trampoline_entity_death::<F>) }
1534    }
1535
1536    pub fn on_entity_spawn<F>(&mut self, handler: F)
1537    where
1538        F: Fn(&EntitySpawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1539    {
1540        let ud = Self::leak(handler);
1541        unsafe { ((*self.api).on_entity_spawn)(self.ctx(), ud, trampoline_entity_spawn::<F>) }
1542    }
1543
1544    pub fn on_player_place_block<F>(&mut self, handler: F)
1545    where
1546        F: Fn(&PlaceBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1547    {
1548        let ud = Self::leak(handler);
1549        unsafe { ((*self.api).on_player_place_block)(self.ctx(), ud, trampoline_place_block::<F>) }
1550    }
1551
1552    pub fn on_player_death<F>(&mut self, handler: F)
1553    where
1554        F: Fn(&PlayerDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1555    {
1556        let ud = Self::leak(handler);
1557        unsafe { ((*self.api).on_player_death)(self.ctx(), ud, trampoline_player_death::<F>) }
1558    }
1559
1560    pub fn on_player_respawn<F>(&mut self, handler: F)
1561    where
1562        F: Fn(&PlayerRespawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1563    {
1564        let ud = Self::leak(handler);
1565        unsafe { ((*self.api).on_player_respawn)(self.ctx(), ud, trampoline_player_respawn::<F>) }
1566    }
1567
1568    pub fn on_advancement<F>(&mut self, handler: F)
1569    where
1570        F: Fn(&AdvancementEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1571    {
1572        let ud = Self::leak(handler);
1573        unsafe { ((*self.api).on_advancement)(self.ctx(), ud, trampoline_advancement::<F>) }
1574    }
1575
1576    pub fn on_entity_interact<F>(&mut self, handler: F)
1577    where
1578        F: Fn(&EntityInteractEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1579    {
1580        let ud = Self::leak(handler);
1581        unsafe { ((*self.api).on_entity_interact)(self.ctx(), ud, trampoline_entity_interact::<F>) }
1582    }
1583
1584    pub fn on_item_craft<F>(&mut self, handler: F)
1585    where
1586        F: Fn(&CraftEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1587    {
1588        let ud = Self::leak(handler);
1589        unsafe { ((*self.api).on_item_craft)(self.ctx(), ud, trampoline_craft::<F>) }
1590    }
1591
1592    pub fn on_explosion<F>(&mut self, handler: F)
1593    where
1594        F: Fn(&ExplosionEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1595    {
1596        let ud = Self::leak(handler);
1597        unsafe { ((*self.api).on_explosion)(self.ctx(), ud, trampoline_explosion::<F>) }
1598    }
1599
1600    pub fn on_item_pickup<F>(&mut self, handler: F)
1601    where
1602        F: Fn(&ItemPickupEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1603    {
1604        let ud = Self::leak(handler);
1605        unsafe { ((*self.api).on_item_pickup)(self.ctx(), ud, trampoline_item_pickup::<F>) }
1606    }
1607
1608    pub fn on_player_move<F>(&mut self, handler: F)
1609    where
1610        F: Fn(&PlayerMoveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1611    {
1612        let ud = Self::leak(handler);
1613        unsafe { ((*self.api).on_player_move)(self.ctx(), ud, trampoline_player_move::<F>) }
1614    }
1615
1616    pub fn on_container_open<F>(&mut self, handler: F)
1617    where
1618        F: Fn(&ContainerOpenEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1619    {
1620        let ud = Self::leak(handler);
1621        unsafe { ((*self.api).on_container_open)(self.ctx(), ud, trampoline_container_open::<F>) }
1622    }
1623
1624    pub fn on_container_close<F>(&mut self, handler: F)
1625    where
1626        F: Fn(&ContainerCloseEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1627    {
1628        let ud = Self::leak(handler);
1629        unsafe { ((*self.api).on_container_close)(self.ctx(), ud, trampoline_container_close::<F>) }
1630    }
1631
1632    pub fn on_projectile_hit<F>(&mut self, handler: F)
1633    where
1634        F: Fn(&ProjectileHitEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1635    {
1636        let ud = Self::leak(handler);
1637        unsafe { ((*self.api).on_projectile_hit)(self.ctx(), ud, trampoline_projectile_hit::<F>) }
1638    }
1639
1640    pub fn on_tick<F>(&mut self, listener: F)
1641    where
1642        F: Fn(&dyn Server) + Send + Sync + 'static,
1643    {
1644        let ud = Self::leak(listener);
1645        unsafe { ((*self.api).on_server_tick)(self.ctx(), ud, trampoline_server_fn::<F>) }
1646    }
1647
1648    pub fn on_server_started<F>(&mut self, listener: F)
1649    where
1650        F: Fn(&dyn Server) + Send + Sync + 'static,
1651    {
1652        let ud = Self::leak(listener);
1653        unsafe { ((*self.api).on_server_started)(self.ctx(), ud, trampoline_server_fn::<F>) }
1654    }
1655
1656    pub fn on_server_stopping<F>(&mut self, listener: F)
1657    where
1658        F: Fn(&dyn Server) + Send + Sync + 'static,
1659    {
1660        let ud = Self::leak(listener);
1661        unsafe { ((*self.api).on_server_stopping)(self.ctx(), ud, trampoline_server_fn::<F>) }
1662    }
1663
1664    // ── commands ─────────────────────────────────────────────────────────────
1665
1666    pub fn on_command<F>(&mut self, name: impl AsRef<str>, handler: F)
1667    where
1668        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
1669    {
1670        let name_ys = YogStr::from_str(name.as_ref());
1671        let ud = Self::leak(handler);
1672        unsafe { ((*self.api).register_command)(self.ctx(), name_ys, ud, trampoline_command::<F>) }
1673    }
1674
1675    /// Register a command with Brigadier-typed arguments.
1676    ///
1677    /// `schema` is a space-separated list of argument types:
1678    /// `int`, `float`, `word`, `string` (greedy, must be last), `player`, `blockpos`.
1679    ///
1680    /// In the handler use `ctx.arg_int(0)`, `ctx.arg_blockpos(1)`, etc.
1681    pub fn on_typed_command<F>(
1682        &mut self,
1683        name: impl AsRef<str>,
1684        schema: impl AsRef<str>,
1685        handler: F,
1686    ) where
1687        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
1688    {
1689        let name_ys = YogStr::from_str(name.as_ref());
1690        let schema_ys = YogStr::from_str(schema.as_ref());
1691        let ud = Self::leak(handler);
1692        unsafe {
1693            ((*self.api).register_typed_command)(
1694                self.ctx(),
1695                name_ys,
1696                schema_ys,
1697                ud,
1698                trampoline_command::<F>,
1699            )
1700        }
1701    }
1702
1703    // ── networking ───────────────────────────────────────────────────────────
1704
1705    pub fn on_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
1706    where
1707        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
1708    {
1709        let ch = YogStr::from_str(channel.as_ref());
1710        let ud = Self::leak(handler);
1711        unsafe { ((*self.api).on_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
1712    }
1713
1714    pub fn on_client_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
1715    where
1716        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
1717    {
1718        let ch = YogStr::from_str(channel.as_ref());
1719        let ud = Self::leak(handler);
1720        unsafe { ((*self.api).on_client_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
1721    }
1722
1723    /// Register a typed-packet handler.
1724    ///
1725    /// The payload is decoded from raw bytes using `P`'s [`Packet`] impl.
1726    /// Malformed payloads are silently dropped.
1727    pub fn on_typed_packet<P, F>(&mut self, channel: impl AsRef<str>, handler: F)
1728    where
1729        P: Packet + Send + Sync + 'static,
1730        F: Fn(&P, &dyn Server) + Send + Sync + 'static,
1731    {
1732        self.on_packet(channel, move |ev, srv| {
1733            if let Some(pkt) = P::decode(&ev.payload) {
1734                handler(&pkt, srv);
1735            }
1736        });
1737    }
1738
1739    // ── recipes ──────────────────────────────────────────────────────────────
1740
1741    fn recipe(&mut self, ns: &str, name: &str, json: &str) {
1742        unsafe {
1743            ((*self.api).register_recipe_json)(
1744                self.ctx(),
1745                YogStr::from_str(ns),
1746                YogStr::from_str(name),
1747                YogStr::from_str(json),
1748            )
1749        }
1750    }
1751
1752    /// Register a shaped crafting recipe.
1753    pub fn add_shaped_recipe(&mut self, recipe: ShapedRecipe) {
1754        let json = recipe.to_json();
1755        let (ns, name) = recipe.ns_name();
1756        self.recipe(ns, name, &json);
1757    }
1758
1759    /// Register a shapeless crafting recipe.
1760    pub fn add_shapeless_recipe(&mut self, recipe: ShapelessRecipe) {
1761        let json = recipe.to_json();
1762        let (ns, name) = recipe.ns_name();
1763        self.recipe(ns, name, &json);
1764    }
1765
1766    /// Register a furnace smelting recipe.
1767    pub fn add_furnace_recipe(&mut self, recipe: FurnaceRecipe) {
1768        let json = recipe.to_json();
1769        let (ns, name) = recipe.ns_name();
1770        self.recipe(ns, name, &json);
1771    }
1772
1773    // ── content ──────────────────────────────────────────────────────────────
1774
1775    pub fn register_item(&mut self, def: ItemDef) {
1776        // Build a C-compatible YogItemDef whose YogStr fields point into `def`'s
1777        // String storage.  We then call register_item which must copy the data
1778        // before returning (the runtime stores owned Strings).
1779        let food_nutrition = def.food.as_ref().map_or(0, |f| f.nutrition);
1780        let food_saturation = def.food.as_ref().map_or(0.0, |f| f.saturation);
1781        let food_always_eat = def.food.as_ref().is_some_and(|f| f.can_always_eat);
1782        let c = YogItemDef {
1783            id: YogStr::from_str(&def.id),
1784            max_stack: def.max_stack as u32,
1785            name: def
1786                .name
1787                .as_deref()
1788                .map(YogStr::from_str)
1789                .unwrap_or(YogStr::EMPTY),
1790            tooltip: def
1791                .tooltip
1792                .as_deref()
1793                .map(YogStr::from_str)
1794                .unwrap_or(YogStr::EMPTY),
1795            max_damage: def.max_damage,
1796            fire_resistant: def.fire_resistant,
1797            fuel_ticks: def.fuel_ticks,
1798            food_nutrition,
1799            food_saturation,
1800            food_always_eat,
1801        };
1802        unsafe { ((*self.api).register_item)(self.ctx(), &c) }
1803    }
1804
1805    pub fn register_block(&mut self, def: BlockDef) {
1806        let shape = def.shape.unwrap_or([0.0; 6]);
1807        let groups_joined = def.connect_groups.join(",");
1808        let c = YogBlockDef {
1809            id: YogStr::from_str(&def.id),
1810            hardness: def.hardness,
1811            resistance: def.resistance,
1812            name: def
1813                .name
1814                .as_deref()
1815                .map(YogStr::from_str)
1816                .unwrap_or(YogStr::EMPTY),
1817            light_level: def.light_level,
1818            sound: def
1819                .sound
1820                .as_deref()
1821                .map(YogStr::from_str)
1822                .unwrap_or(YogStr::EMPTY),
1823            requires_tool: def.requires_tool,
1824            no_collision: def.no_collision,
1825            slipperiness: def.slipperiness,
1826            shape,
1827            connects: def.connects,
1828            connect_groups: YogStr::from_str(&groups_joined),
1829            inventory_id: def
1830                .inventory_id
1831                .as_deref()
1832                .map(YogStr::from_str)
1833                .unwrap_or(YogStr::EMPTY),
1834        };
1835        unsafe { ((*self.api).register_block)(self.ctx(), &c) }
1836    }
1837
1838    /// Register a real Container/Menu inventory screen — see
1839    /// `yog_inventory::InventoryDef`. Attach it to a block via
1840    /// `BlockDef::inventory(id)`.
1841    pub fn register_inventory(&mut self, def: yog_inventory::InventoryDef) {
1842        let layout = yog_inventory::encode_layout(&def.resolved_layout());
1843        let c = YogInventoryDef {
1844            id: YogStr::from_str(&def.id),
1845            slot_count: def.slot_count as u32,
1846            layout: YogStr::from_str(&layout),
1847            include_player_inventory: def.include_player_inventory,
1848            player_inv_x: def.player_inv_offset.0,
1849            player_inv_y: def.player_inv_offset.1,
1850            background_texture: def
1851                .background_texture
1852                .as_deref()
1853                .map(YogStr::from_str)
1854                .unwrap_or(YogStr::EMPTY),
1855            title: YogStr::from_str(&def.title),
1856            background_w: def.background_size.map(|(w, _)| w).unwrap_or(0.0),
1857            background_h: def.background_size.map(|(_, h)| h).unwrap_or(0.0),
1858        };
1859        unsafe { ((*self.api).register_inventory)(self.ctx(), &c) }
1860    }
1861
1862    // ── startup grants ───────────────────────────────────────────────────────
1863
1864    /// Register a startup grant: items/books to give once when a player first joins.
1865    pub fn register_startup_grant(&mut self, grant: StartupGrant) {
1866        let items_str = grant.items.join("|");
1867        let c = YogStartupGrantDef {
1868            id: YogStr::from_str(&grant.id),
1869            items: YogStr::from_str(&items_str),
1870            book: grant
1871                .book
1872                .as_deref()
1873                .map(YogStr::from_str)
1874                .unwrap_or(YogStr::EMPTY),
1875            command: grant
1876                .command
1877                .as_deref()
1878                .map(YogStr::from_str)
1879                .unwrap_or(YogStr::EMPTY),
1880        };
1881        unsafe { ((*self.api).register_startup_grant)(self.ctx(), &c) }
1882    }
1883
1884    /// Register a book with its JSON-serialized content.
1885    pub fn register_book(&mut self, book: &Book) {
1886        let json = book.to_json();
1887        let id = YogStr::from_str(&book.id);
1888        let j = YogStr::from_str(&json);
1889        unsafe { ((*self.api).register_book)(self.ctx(), id, j) }
1890    }
1891
1892    /// Register (or patch) a dimension's *type* (sky, lighting, physics, ...).
1893    ///
1894    /// `def.id` need not be a new custom id — pass a vanilla id
1895    /// (`"minecraft:overworld"`, `"minecraft:the_nether"`,
1896    /// `"minecraft:the_end"`) to patch that dimension's type/generator
1897    /// instead of creating a new one (e.g. to replace the overworld's
1898    /// terrain with your own generator type).
1899    ///
1900    /// Must be called from `register()` — the same mod-init window as
1901    /// blocks/items — so the host can declare/patch the dimension before
1902    /// Minecraft's registries freeze. See the `yog-dimensions` crate docs;
1903    /// set `def.generator_type` (via [`YogDimensionDef::generator_type`]) to
1904    /// pick a generator type registered with
1905    /// [`Registry::register_chunk_generator`].
1906    pub fn register_dimension(&mut self, def: &YogDimensionDef) {
1907        let json = def.to_json();
1908        let id = YogStr::from_str(&def.id);
1909        let j = YogStr::from_str(&json);
1910        unsafe { ((*self.api).register_dimension_json)(self.ctx(), id, j) }
1911    }
1912
1913    /// Register a named, reusable chunk-generator type under
1914    /// `generator_type_id` (e.g. `"mymod:custom_terrain"`) — analogous to
1915    /// how Biomes O'Plenty registers selectable world-type presets. Any
1916    /// dimension (custom or vanilla) can opt into this generator via
1917    /// [`YogDimensionDef::generator_type`]; the platform host may also list
1918    /// registered generator type ids as options on the world-creation screen.
1919    ///
1920    /// `generator` is called once per chunk column that needs generating in
1921    /// any dimension using this type — write whatever terrain logic you want
1922    /// using the [`ChunkWriter`] handle (combine as many noise layers as you
1923    /// like; this crate doesn't prescribe a generation style).
1924    pub fn register_chunk_generator<F>(&mut self, generator_type_id: &str, generator: F)
1925    where
1926        F: Fn(&ChunkWriter) + Send + Sync + 'static,
1927    {
1928        let ud = Self::leak(generator);
1929        let id = YogStr::from_str(generator_type_id);
1930        unsafe {
1931            ((*self.api).register_chunk_generator)(
1932                self.ctx(),
1933                id,
1934                ud,
1935                trampoline_chunk_generator::<F>,
1936            )
1937        }
1938    }
1939
1940    /// Register a menu entry — the host renders a button on vanilla screens
1941    /// (TitleScreen on Fabric, ModListScreen on Forge/NeoForge) that opens `ui_id`.
1942    /// `label` is the human-readable button text (e.g. "Yog Mods").
1943    /// `ui_id` is the UI to open when clicked (e.g. "yog:modlist").
1944    /// See [`installed_mods`]. During `register()` the list only contains
1945    /// mods loaded before this one.
1946    pub fn installed_mods(&self) -> Vec<ModInfo> {
1947        installed_mods()
1948    }
1949
1950    /// Access the inter-mod communication layer.
1951    ///
1952    /// Allows exporting function pointers from this mod and importing
1953    /// function pointers from other mods.
1954    pub fn interop(&self) -> crate::Interop {
1955        crate::Interop::new(self.api)
1956    }
1957
1958    /// Raw `YogApi` pointer — for passing to interop-imported functions
1959    /// that register content through the C ABI table directly.
1960    pub fn raw_api(&self) -> *const yog_abi::YogApi {
1961        self.api
1962    }
1963
1964    pub fn register_menu_entry(&mut self, label: &str, ui_id: &str) {
1965        let l = YogStr::from_str(label);
1966        let u = YogStr::from_str(ui_id);
1967        unsafe { ((*self.api).register_menu_entry)(self.ctx(), l, u) }
1968    }
1969
1970    /// Register a UI tree with an event callback.
1971    /// `ui_id` is the unique identifier (e.g. "mymod:menu").
1972    /// `handler` receives `(ui_id, event)` for the screen's input: `click:X:Y`,
1973    /// `drag:X:Y`, `release:X:Y`, `scroll:DY`, `key:KEY:MODS` (GLFW key code
1974    /// and modifier bits, on press and repeat) and `char:CODEPOINT` (a typed
1975    /// character). It returns `()` or a `bool`: `true` marks a `key:`/`char:`
1976    /// event as used, so the host skips its default handling of the key
1977    /// (Esc closing the screen, ...) — see [`UiHandled`].
1978    pub fn register_ui<F, R>(&mut self, ui_id: &str, handler: F)
1979    where
1980        F: Fn(&str, &str) -> R + Send + Sync + 'static,
1981        R: UiHandled,
1982    {
1983        let ud = Self::leak(handler);
1984        let id = YogStr::from_str(ui_id);
1985        let empty = YogStr::from_str("{}");
1986        unsafe {
1987            ((*self.api).register_ui)(self.ctx(), id, empty, ud, trampoline_ui_event::<F, R>)
1988        }
1989    }
1990
1991    // ── scheduler ────────────────────────────────────────────────────────────
1992
1993    pub fn schedule_once<F>(&self, delay_ticks: u64, handler: F)
1994    where
1995        F: Fn(&dyn Server) + Send + Sync + 'static,
1996    {
1997        let ud = Self::leak(handler);
1998        unsafe {
1999            ((*self.api).schedule_once)(self.ctx(), delay_ticks, ud, trampoline_scheduled::<F>)
2000        }
2001    }
2002
2003    pub fn schedule_repeating<F>(&self, period_ticks: u64, handler: F)
2004    where
2005        F: Fn(&dyn Server) + Send + Sync + 'static,
2006    {
2007        let ud = Self::leak(handler);
2008        unsafe {
2009            ((*self.api).schedule_repeating)(
2010                self.ctx(),
2011                period_ticks,
2012                ud,
2013                trampoline_scheduled::<F>,
2014            )
2015        }
2016    }
2017
2018    // ── client-side hooks (ABI minor 10) ─────────────────────────────────────
2019
2020    /// Register a handler called every client tick (render thread, no server).
2021    pub fn on_client_tick<F>(&mut self, handler: F)
2022    where
2023        F: Fn(&ClientTickEvent) + Send + Sync + 'static,
2024    {
2025        let ud = Self::leak(handler);
2026        unsafe { ((*self.api).on_client_tick)(self.ctx(), ud, trampoline_client_tick::<F>) }
2027    }
2028
2029    /// Register a render callback for a specific UI screen (`ui_id`).
2030    ///
2031    /// Called from `YogUIScreen.render()` — i.e. AFTER `renderBackground()` darkens
2032    /// the screen — so your UI draws on top of the dimmed world view.
2033    /// Use this instead of `on_hud_render` for book/inventory screens.
2034    ///
2035    /// Clicks are forwarded as `"click:X:Y"` via the `register_ui` handler so you
2036    /// can do hit-testing on your own stored layout.
2037    pub fn on_ui_render<F>(&mut self, ui_id: &str, handler: F)
2038    where
2039        F: Fn(&GfxContext) + Send + Sync + 'static,
2040    {
2041        let ud = Self::leak(handler);
2042        let id = YogStr::from_str(ui_id);
2043        unsafe { ((*self.api).on_ui_render)(self.ctx(), id, ud, trampoline_hud_render::<F>) }
2044    }
2045
2046    /// Register a handler called every frame when the HUD is rendered.
2047    ///
2048    /// `gfx` provides full GPU pipeline access plus 2D convenience draw calls.
2049    /// `view_proj` and `camera_pos` are zero in HUD context; use `gfx.draw2d()` for HUD elements.
2050    pub fn on_hud_render<F>(&mut self, handler: F)
2051    where
2052        F: Fn(&GfxContext) + Send + Sync + 'static,
2053    {
2054        let ud = Self::leak(handler);
2055        unsafe { ((*self.api).on_hud_render)(self.ctx(), ud, trampoline_hud_render::<F>) }
2056    }
2057
2058    /// Register a handler called every frame at the end of world rendering.
2059    ///
2060    /// `gfx.view_proj()` is the combined projection × view matrix (camera-relative).
2061    /// `gfx.camera_pos()` is the camera world position.
2062    /// To render at world position P, translate by `P - camera_pos` before drawing.
2063    pub fn on_world_render<F>(&mut self, handler: F)
2064    where
2065        F: Fn(&GfxContext) + Send + Sync + 'static,
2066    {
2067        let ud = Self::leak(handler);
2068        unsafe { ((*self.api).on_world_render)(self.ctx(), ud, trampoline_world_render::<F>) }
2069    }
2070
2071    /// Register a handler for keyboard input (client-side).
2072    /// Return `false` to prevent Minecraft from processing the key.
2073    pub fn on_key_press<F>(&mut self, handler: F)
2074    where
2075        F: Fn(&KeyPressEvent) -> bool + Send + Sync + 'static,
2076    {
2077        let ud = Self::leak(handler);
2078        unsafe { ((*self.api).on_key_press)(self.ctx(), ud, trampoline_key_press::<F>) }
2079    }
2080
2081    /// Register a handler called when a GUI screen is opened.
2082    pub fn on_screen_open<F>(&mut self, handler: F)
2083    where
2084        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2085    {
2086        let ud = Self::leak(handler);
2087        unsafe { ((*self.api).on_screen_open)(self.ctx(), ud, trampoline_screen::<F>) }
2088    }
2089
2090    /// Register a handler called when a GUI screen is closed.
2091    pub fn on_screen_close<F>(&mut self, handler: F)
2092    where
2093        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2094    {
2095        let ud = Self::leak(handler);
2096        unsafe { ((*self.api).on_screen_close)(self.ctx(), ud, trampoline_screen::<F>) }
2097    }
2098}
2099
2100unsafe extern "C" fn trampoline_ui_event<F, R>(
2101    ud: *mut c_void,
2102    ui_id: yog_abi::YogStr,
2103    event_id: yog_abi::YogStr,
2104) where
2105    F: Fn(&str, &str) -> R + Send + Sync + 'static,
2106    R: UiHandled,
2107{
2108    let f = &*(ud as *const F);
2109    let ui = unsafe { ui_id.as_str() };
2110    let ev = unsafe { event_id.as_str() };
2111    if f(ui, ev).handled() {
2112        let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
2113        if !api.is_null() {
2114            unsafe { ((*api).ui_consume_event)((*api).ctx) }
2115        }
2116    }
2117}
2118
2119unsafe extern "C" fn trampoline_chunk_generator<F>(
2120    ud: *mut c_void,
2121    writer: *const yog_abi::YogChunkWriterApi,
2122) where
2123    F: Fn(&ChunkWriter) + Send + Sync + 'static,
2124{
2125    let f = &*(ud as *const F);
2126    let writer = unsafe { ChunkWriter::from_raw(writer) };
2127    f(&writer);
2128}
2129
2130// ── Mod trait ─────────────────────────────────────────────────────────────────
2131
2132/// Implemented by every Yog mod. Called once at startup to register handlers.
2133pub trait Mod {
2134    fn register(registry: &mut Registry);
2135}