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/// Metadata of an installed mod, as reported by the loader.
1317#[derive(Debug, Clone)]
1318pub struct ModInfo {
1319    /// `"yog"` for .yog mods, `"platform"` for loader (Java) mods.
1320    pub source: String,
1321    pub id: String,
1322    pub name: String,
1323    pub version: String,
1324    /// Comma-separated author list (may be empty).
1325    pub authors: String,
1326    pub description: String,
1327}
1328
1329/// All installed mods known to the loader: .yog mods plus, where the host
1330/// exposes them, platform (Java) mods. Callable at any time after this mod's
1331/// `register()` ran — including client-side UI handlers. Note that during
1332/// `register()` mods that load after this one are not in the list yet; query
1333/// lazily (e.g. on first render) for a complete view.
1334pub fn installed_mods() -> Vec<ModInfo> {
1335    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1336    if api.is_null() {
1337        return Vec::new();
1338    }
1339    let owned = unsafe { ((*api).mods_list)((*api).ctx) };
1340    if owned.is_none() {
1341        return Vec::new();
1342    }
1343    let text = unsafe {
1344        String::from_utf8(std::slice::from_raw_parts(owned.ptr, owned.len as usize).to_vec())
1345            .unwrap_or_default()
1346    };
1347    unsafe { ((*api).free_str)(owned.ptr, owned.len) };
1348    text.lines()
1349        .filter_map(|line| {
1350            let mut f = line.split('\t');
1351            Some(ModInfo {
1352                source: f.next()?.to_string(),
1353                id: f.next()?.to_string(),
1354                name: f.next().unwrap_or_default().to_string(),
1355                version: f.next().unwrap_or_default().to_string(),
1356                authors: f.next().unwrap_or_default().to_string(),
1357                description: f.next().unwrap_or_default().to_string(),
1358            })
1359        })
1360        .collect()
1361}
1362
1363/// Open the Yog UI registered as `ui_id` (client side; no-op on dedicated
1364/// servers). `modal` blocks game input, `pause` pauses singleplayer. Callable
1365/// from any handler after registration — e.g. an `on_client_packet` handler.
1366pub fn open_ui(ui_id: &str, modal: bool, pause: bool) {
1367    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1368    if api.is_null() {
1369        return;
1370    }
1371    unsafe { ((*api).ui_open)((*api).ctx, YogStr::from_str(ui_id), modal, pause) }
1372}
1373
1374/// Handle to the runtime's server-action table, usable from any handler after
1375/// registration — including client-side ones that don't receive `&dyn Server`
1376/// (UI event handlers, client tick). Server-world actions are no-ops client
1377/// side, but networking (`send_to_server`) and similar client-safe calls work.
1378pub fn server() -> Option<CServer> {
1379    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1380    if api.is_null() {
1381        return None;
1382    }
1383    let srv = unsafe { (*api).server };
1384    if srv.is_null() {
1385        return None;
1386    }
1387    Some(CServer(srv))
1388}
1389
1390pub struct Registry {
1391    api: *const YogApi,
1392}
1393
1394// SAFETY: `api` is a static provided by the runtime, valid for process lifetime.
1395unsafe impl Send for Registry {}
1396unsafe impl Sync for Registry {}
1397
1398impl Registry {
1399    /// Build from the pointer passed by the runtime. Only called by `export_mod!`.
1400    ///
1401    /// # Safety
1402    ///
1403    /// `api` must point to the runtime's `YogApi` table, valid for the rest of
1404    /// the process.
1405    pub unsafe fn from_raw(api: *const YogApi) -> Self {
1406        GLOBAL_API.store(api as *mut YogApi, std::sync::atomic::Ordering::Release);
1407        Self { api }
1408    }
1409
1410    #[inline]
1411    fn ctx(&self) -> *mut c_void {
1412        unsafe { (*self.api).ctx }
1413    }
1414
1415    // ── helpers ──────────────────────────────────────────────────────────────
1416
1417    fn leak<F: 'static>(f: F) -> *mut c_void {
1418        Box::into_raw(Box::new(f)) as *mut c_void
1419    }
1420
1421    // ── events ───────────────────────────────────────────────────────────────
1422    //
1423    // All handlers receive `(event, EventPhase, &dyn Server) -> bool`.
1424    // In `Pre` phase, returning `false` cancels the action.
1425    // In `Post` phase, the return value is ignored.
1426    // A single registration fires for BOTH phases.
1427
1428    pub fn on_block_break<F>(&mut self, handler: F)
1429    where
1430        F: Fn(&BlockBreakEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1431    {
1432        let ud = Self::leak(handler);
1433        unsafe { ((*self.api).on_block_break)(self.ctx(), ud, trampoline_block_break::<F>) }
1434    }
1435
1436    pub fn on_chat<F>(&mut self, handler: F)
1437    where
1438        F: Fn(&ChatEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1439    {
1440        let ud = Self::leak(handler);
1441        unsafe { ((*self.api).on_chat)(self.ctx(), ud, trampoline_chat::<F>) }
1442    }
1443
1444    pub fn on_player_join<F>(&mut self, handler: F)
1445    where
1446        F: Fn(&PlayerJoinEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1447    {
1448        let ud = Self::leak(handler);
1449        unsafe { ((*self.api).on_player_join)(self.ctx(), ud, trampoline_player_join::<F>) }
1450    }
1451
1452    pub fn on_player_leave<F>(&mut self, handler: F)
1453    where
1454        F: Fn(&PlayerLeaveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1455    {
1456        let ud = Self::leak(handler);
1457        unsafe { ((*self.api).on_player_leave)(self.ctx(), ud, trampoline_player_leave::<F>) }
1458    }
1459
1460    pub fn on_use_item<F>(&mut self, handler: F)
1461    where
1462        F: Fn(&UseItemEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1463    {
1464        let ud = Self::leak(handler);
1465        unsafe { ((*self.api).on_use_item)(self.ctx(), ud, trampoline_use_item::<F>) }
1466    }
1467
1468    pub fn on_use_block<F>(&mut self, handler: F)
1469    where
1470        F: Fn(&UseBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1471    {
1472        let ud = Self::leak(handler);
1473        unsafe { ((*self.api).on_use_block)(self.ctx(), ud, trampoline_use_block::<F>) }
1474    }
1475
1476    pub fn on_attack_entity<F>(&mut self, handler: F)
1477    where
1478        F: Fn(&AttackEntityEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1479    {
1480        let ud = Self::leak(handler);
1481        unsafe { ((*self.api).on_attack_entity)(self.ctx(), ud, trampoline_attack_entity::<F>) }
1482    }
1483
1484    pub fn on_entity_damage<F>(&mut self, handler: F)
1485    where
1486        F: Fn(&EntityDamageEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1487    {
1488        let ud = Self::leak(handler);
1489        unsafe { ((*self.api).on_entity_damage)(self.ctx(), ud, trampoline_entity_damage::<F>) }
1490    }
1491
1492    pub fn on_entity_death<F>(&mut self, handler: F)
1493    where
1494        F: Fn(&EntityDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1495    {
1496        let ud = Self::leak(handler);
1497        unsafe { ((*self.api).on_entity_death)(self.ctx(), ud, trampoline_entity_death::<F>) }
1498    }
1499
1500    pub fn on_entity_spawn<F>(&mut self, handler: F)
1501    where
1502        F: Fn(&EntitySpawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1503    {
1504        let ud = Self::leak(handler);
1505        unsafe { ((*self.api).on_entity_spawn)(self.ctx(), ud, trampoline_entity_spawn::<F>) }
1506    }
1507
1508    pub fn on_player_place_block<F>(&mut self, handler: F)
1509    where
1510        F: Fn(&PlaceBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1511    {
1512        let ud = Self::leak(handler);
1513        unsafe { ((*self.api).on_player_place_block)(self.ctx(), ud, trampoline_place_block::<F>) }
1514    }
1515
1516    pub fn on_player_death<F>(&mut self, handler: F)
1517    where
1518        F: Fn(&PlayerDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1519    {
1520        let ud = Self::leak(handler);
1521        unsafe { ((*self.api).on_player_death)(self.ctx(), ud, trampoline_player_death::<F>) }
1522    }
1523
1524    pub fn on_player_respawn<F>(&mut self, handler: F)
1525    where
1526        F: Fn(&PlayerRespawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1527    {
1528        let ud = Self::leak(handler);
1529        unsafe { ((*self.api).on_player_respawn)(self.ctx(), ud, trampoline_player_respawn::<F>) }
1530    }
1531
1532    pub fn on_advancement<F>(&mut self, handler: F)
1533    where
1534        F: Fn(&AdvancementEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1535    {
1536        let ud = Self::leak(handler);
1537        unsafe { ((*self.api).on_advancement)(self.ctx(), ud, trampoline_advancement::<F>) }
1538    }
1539
1540    pub fn on_entity_interact<F>(&mut self, handler: F)
1541    where
1542        F: Fn(&EntityInteractEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1543    {
1544        let ud = Self::leak(handler);
1545        unsafe { ((*self.api).on_entity_interact)(self.ctx(), ud, trampoline_entity_interact::<F>) }
1546    }
1547
1548    pub fn on_item_craft<F>(&mut self, handler: F)
1549    where
1550        F: Fn(&CraftEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1551    {
1552        let ud = Self::leak(handler);
1553        unsafe { ((*self.api).on_item_craft)(self.ctx(), ud, trampoline_craft::<F>) }
1554    }
1555
1556    pub fn on_explosion<F>(&mut self, handler: F)
1557    where
1558        F: Fn(&ExplosionEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1559    {
1560        let ud = Self::leak(handler);
1561        unsafe { ((*self.api).on_explosion)(self.ctx(), ud, trampoline_explosion::<F>) }
1562    }
1563
1564    pub fn on_item_pickup<F>(&mut self, handler: F)
1565    where
1566        F: Fn(&ItemPickupEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1567    {
1568        let ud = Self::leak(handler);
1569        unsafe { ((*self.api).on_item_pickup)(self.ctx(), ud, trampoline_item_pickup::<F>) }
1570    }
1571
1572    pub fn on_player_move<F>(&mut self, handler: F)
1573    where
1574        F: Fn(&PlayerMoveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1575    {
1576        let ud = Self::leak(handler);
1577        unsafe { ((*self.api).on_player_move)(self.ctx(), ud, trampoline_player_move::<F>) }
1578    }
1579
1580    pub fn on_container_open<F>(&mut self, handler: F)
1581    where
1582        F: Fn(&ContainerOpenEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1583    {
1584        let ud = Self::leak(handler);
1585        unsafe { ((*self.api).on_container_open)(self.ctx(), ud, trampoline_container_open::<F>) }
1586    }
1587
1588    pub fn on_container_close<F>(&mut self, handler: F)
1589    where
1590        F: Fn(&ContainerCloseEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1591    {
1592        let ud = Self::leak(handler);
1593        unsafe { ((*self.api).on_container_close)(self.ctx(), ud, trampoline_container_close::<F>) }
1594    }
1595
1596    pub fn on_projectile_hit<F>(&mut self, handler: F)
1597    where
1598        F: Fn(&ProjectileHitEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1599    {
1600        let ud = Self::leak(handler);
1601        unsafe { ((*self.api).on_projectile_hit)(self.ctx(), ud, trampoline_projectile_hit::<F>) }
1602    }
1603
1604    pub fn on_tick<F>(&mut self, listener: F)
1605    where
1606        F: Fn(&dyn Server) + Send + Sync + 'static,
1607    {
1608        let ud = Self::leak(listener);
1609        unsafe { ((*self.api).on_server_tick)(self.ctx(), ud, trampoline_server_fn::<F>) }
1610    }
1611
1612    pub fn on_server_started<F>(&mut self, listener: F)
1613    where
1614        F: Fn(&dyn Server) + Send + Sync + 'static,
1615    {
1616        let ud = Self::leak(listener);
1617        unsafe { ((*self.api).on_server_started)(self.ctx(), ud, trampoline_server_fn::<F>) }
1618    }
1619
1620    pub fn on_server_stopping<F>(&mut self, listener: F)
1621    where
1622        F: Fn(&dyn Server) + Send + Sync + 'static,
1623    {
1624        let ud = Self::leak(listener);
1625        unsafe { ((*self.api).on_server_stopping)(self.ctx(), ud, trampoline_server_fn::<F>) }
1626    }
1627
1628    // ── commands ─────────────────────────────────────────────────────────────
1629
1630    pub fn on_command<F>(&mut self, name: impl AsRef<str>, handler: F)
1631    where
1632        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
1633    {
1634        let name_ys = YogStr::from_str(name.as_ref());
1635        let ud = Self::leak(handler);
1636        unsafe { ((*self.api).register_command)(self.ctx(), name_ys, ud, trampoline_command::<F>) }
1637    }
1638
1639    /// Register a command with Brigadier-typed arguments.
1640    ///
1641    /// `schema` is a space-separated list of argument types:
1642    /// `int`, `float`, `word`, `string` (greedy, must be last), `player`, `blockpos`.
1643    ///
1644    /// In the handler use `ctx.arg_int(0)`, `ctx.arg_blockpos(1)`, etc.
1645    pub fn on_typed_command<F>(
1646        &mut self,
1647        name: impl AsRef<str>,
1648        schema: impl AsRef<str>,
1649        handler: F,
1650    ) where
1651        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
1652    {
1653        let name_ys = YogStr::from_str(name.as_ref());
1654        let schema_ys = YogStr::from_str(schema.as_ref());
1655        let ud = Self::leak(handler);
1656        unsafe {
1657            ((*self.api).register_typed_command)(
1658                self.ctx(),
1659                name_ys,
1660                schema_ys,
1661                ud,
1662                trampoline_command::<F>,
1663            )
1664        }
1665    }
1666
1667    // ── networking ───────────────────────────────────────────────────────────
1668
1669    pub fn on_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
1670    where
1671        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
1672    {
1673        let ch = YogStr::from_str(channel.as_ref());
1674        let ud = Self::leak(handler);
1675        unsafe { ((*self.api).on_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
1676    }
1677
1678    pub fn on_client_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
1679    where
1680        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
1681    {
1682        let ch = YogStr::from_str(channel.as_ref());
1683        let ud = Self::leak(handler);
1684        unsafe { ((*self.api).on_client_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
1685    }
1686
1687    /// Register a typed-packet handler.
1688    ///
1689    /// The payload is decoded from raw bytes using `P`'s [`Packet`] impl.
1690    /// Malformed payloads are silently dropped.
1691    pub fn on_typed_packet<P, F>(&mut self, channel: impl AsRef<str>, handler: F)
1692    where
1693        P: Packet + Send + Sync + 'static,
1694        F: Fn(&P, &dyn Server) + Send + Sync + 'static,
1695    {
1696        self.on_packet(channel, move |ev, srv| {
1697            if let Some(pkt) = P::decode(&ev.payload) {
1698                handler(&pkt, srv);
1699            }
1700        });
1701    }
1702
1703    // ── recipes ──────────────────────────────────────────────────────────────
1704
1705    fn recipe(&mut self, ns: &str, name: &str, json: &str) {
1706        unsafe {
1707            ((*self.api).register_recipe_json)(
1708                self.ctx(),
1709                YogStr::from_str(ns),
1710                YogStr::from_str(name),
1711                YogStr::from_str(json),
1712            )
1713        }
1714    }
1715
1716    /// Register a shaped crafting recipe.
1717    pub fn add_shaped_recipe(&mut self, recipe: ShapedRecipe) {
1718        let json = recipe.to_json();
1719        let (ns, name) = recipe.ns_name();
1720        self.recipe(ns, name, &json);
1721    }
1722
1723    /// Register a shapeless crafting recipe.
1724    pub fn add_shapeless_recipe(&mut self, recipe: ShapelessRecipe) {
1725        let json = recipe.to_json();
1726        let (ns, name) = recipe.ns_name();
1727        self.recipe(ns, name, &json);
1728    }
1729
1730    /// Register a furnace smelting recipe.
1731    pub fn add_furnace_recipe(&mut self, recipe: FurnaceRecipe) {
1732        let json = recipe.to_json();
1733        let (ns, name) = recipe.ns_name();
1734        self.recipe(ns, name, &json);
1735    }
1736
1737    // ── content ──────────────────────────────────────────────────────────────
1738
1739    pub fn register_item(&mut self, def: ItemDef) {
1740        // Build a C-compatible YogItemDef whose YogStr fields point into `def`'s
1741        // String storage.  We then call register_item which must copy the data
1742        // before returning (the runtime stores owned Strings).
1743        let food_nutrition = def.food.as_ref().map_or(0, |f| f.nutrition);
1744        let food_saturation = def.food.as_ref().map_or(0.0, |f| f.saturation);
1745        let food_always_eat = def.food.as_ref().is_some_and(|f| f.can_always_eat);
1746        let c = YogItemDef {
1747            id: YogStr::from_str(&def.id),
1748            max_stack: def.max_stack as u32,
1749            name: def
1750                .name
1751                .as_deref()
1752                .map(YogStr::from_str)
1753                .unwrap_or(YogStr::EMPTY),
1754            tooltip: def
1755                .tooltip
1756                .as_deref()
1757                .map(YogStr::from_str)
1758                .unwrap_or(YogStr::EMPTY),
1759            max_damage: def.max_damage,
1760            fire_resistant: def.fire_resistant,
1761            fuel_ticks: def.fuel_ticks,
1762            food_nutrition,
1763            food_saturation,
1764            food_always_eat,
1765        };
1766        unsafe { ((*self.api).register_item)(self.ctx(), &c) }
1767    }
1768
1769    pub fn register_block(&mut self, def: BlockDef) {
1770        let shape = def.shape.unwrap_or([0.0; 6]);
1771        let groups_joined = def.connect_groups.join(",");
1772        let c = YogBlockDef {
1773            id: YogStr::from_str(&def.id),
1774            hardness: def.hardness,
1775            resistance: def.resistance,
1776            name: def
1777                .name
1778                .as_deref()
1779                .map(YogStr::from_str)
1780                .unwrap_or(YogStr::EMPTY),
1781            light_level: def.light_level,
1782            sound: def
1783                .sound
1784                .as_deref()
1785                .map(YogStr::from_str)
1786                .unwrap_or(YogStr::EMPTY),
1787            requires_tool: def.requires_tool,
1788            no_collision: def.no_collision,
1789            slipperiness: def.slipperiness,
1790            shape,
1791            connects: def.connects,
1792            connect_groups: YogStr::from_str(&groups_joined),
1793            inventory_id: def
1794                .inventory_id
1795                .as_deref()
1796                .map(YogStr::from_str)
1797                .unwrap_or(YogStr::EMPTY),
1798        };
1799        unsafe { ((*self.api).register_block)(self.ctx(), &c) }
1800    }
1801
1802    /// Register a real Container/Menu inventory screen — see
1803    /// `yog_inventory::InventoryDef`. Attach it to a block via
1804    /// `BlockDef::inventory(id)`.
1805    pub fn register_inventory(&mut self, def: yog_inventory::InventoryDef) {
1806        let layout = yog_inventory::encode_layout(&def.resolved_layout());
1807        let c = YogInventoryDef {
1808            id: YogStr::from_str(&def.id),
1809            slot_count: def.slot_count as u32,
1810            layout: YogStr::from_str(&layout),
1811            include_player_inventory: def.include_player_inventory,
1812            player_inv_x: def.player_inv_offset.0,
1813            player_inv_y: def.player_inv_offset.1,
1814            background_texture: def
1815                .background_texture
1816                .as_deref()
1817                .map(YogStr::from_str)
1818                .unwrap_or(YogStr::EMPTY),
1819            title: YogStr::from_str(&def.title),
1820            background_w: def.background_size.map(|(w, _)| w).unwrap_or(0.0),
1821            background_h: def.background_size.map(|(_, h)| h).unwrap_or(0.0),
1822        };
1823        unsafe { ((*self.api).register_inventory)(self.ctx(), &c) }
1824    }
1825
1826    // ── startup grants ───────────────────────────────────────────────────────
1827
1828    /// Register a startup grant: items/books to give once when a player first joins.
1829    pub fn register_startup_grant(&mut self, grant: StartupGrant) {
1830        let items_str = grant.items.join("|");
1831        let c = YogStartupGrantDef {
1832            id: YogStr::from_str(&grant.id),
1833            items: YogStr::from_str(&items_str),
1834            book: grant
1835                .book
1836                .as_deref()
1837                .map(YogStr::from_str)
1838                .unwrap_or(YogStr::EMPTY),
1839            command: grant
1840                .command
1841                .as_deref()
1842                .map(YogStr::from_str)
1843                .unwrap_or(YogStr::EMPTY),
1844        };
1845        unsafe { ((*self.api).register_startup_grant)(self.ctx(), &c) }
1846    }
1847
1848    /// Register a book with its JSON-serialized content.
1849    pub fn register_book(&mut self, book: &Book) {
1850        let json = book.to_json();
1851        let id = YogStr::from_str(&book.id);
1852        let j = YogStr::from_str(&json);
1853        unsafe { ((*self.api).register_book)(self.ctx(), id, j) }
1854    }
1855
1856    /// Register (or patch) a dimension's *type* (sky, lighting, physics, ...).
1857    ///
1858    /// `def.id` need not be a new custom id — pass a vanilla id
1859    /// (`"minecraft:overworld"`, `"minecraft:the_nether"`,
1860    /// `"minecraft:the_end"`) to patch that dimension's type/generator
1861    /// instead of creating a new one (e.g. to replace the overworld's
1862    /// terrain with your own generator type).
1863    ///
1864    /// Must be called from `register()` — the same mod-init window as
1865    /// blocks/items — so the host can declare/patch the dimension before
1866    /// Minecraft's registries freeze. See the `yog-dimensions` crate docs;
1867    /// set `def.generator_type` (via [`YogDimensionDef::generator_type`]) to
1868    /// pick a generator type registered with
1869    /// [`Registry::register_chunk_generator`].
1870    pub fn register_dimension(&mut self, def: &YogDimensionDef) {
1871        let json = def.to_json();
1872        let id = YogStr::from_str(&def.id);
1873        let j = YogStr::from_str(&json);
1874        unsafe { ((*self.api).register_dimension_json)(self.ctx(), id, j) }
1875    }
1876
1877    /// Register a named, reusable chunk-generator type under
1878    /// `generator_type_id` (e.g. `"mymod:custom_terrain"`) — analogous to
1879    /// how Biomes O'Plenty registers selectable world-type presets. Any
1880    /// dimension (custom or vanilla) can opt into this generator via
1881    /// [`YogDimensionDef::generator_type`]; the platform host may also list
1882    /// registered generator type ids as options on the world-creation screen.
1883    ///
1884    /// `generator` is called once per chunk column that needs generating in
1885    /// any dimension using this type — write whatever terrain logic you want
1886    /// using the [`ChunkWriter`] handle (combine as many noise layers as you
1887    /// like; this crate doesn't prescribe a generation style).
1888    pub fn register_chunk_generator<F>(&mut self, generator_type_id: &str, generator: F)
1889    where
1890        F: Fn(&ChunkWriter) + Send + Sync + 'static,
1891    {
1892        let ud = Self::leak(generator);
1893        let id = YogStr::from_str(generator_type_id);
1894        unsafe {
1895            ((*self.api).register_chunk_generator)(
1896                self.ctx(),
1897                id,
1898                ud,
1899                trampoline_chunk_generator::<F>,
1900            )
1901        }
1902    }
1903
1904    /// Register a menu entry — the host renders a button on vanilla screens
1905    /// (TitleScreen on Fabric, ModListScreen on Forge/NeoForge) that opens `ui_id`.
1906    /// `label` is the human-readable button text (e.g. "Yog Mods").
1907    /// `ui_id` is the UI to open when clicked (e.g. "yog:modlist").
1908    /// See [`installed_mods`]. During `register()` the list only contains
1909    /// mods loaded before this one.
1910    pub fn installed_mods(&self) -> Vec<ModInfo> {
1911        installed_mods()
1912    }
1913
1914    /// Access the inter-mod communication layer.
1915    ///
1916    /// Allows exporting function pointers from this mod and importing
1917    /// function pointers from other mods.
1918    pub fn interop(&self) -> crate::Interop {
1919        crate::Interop::new(self.api)
1920    }
1921
1922    /// Raw `YogApi` pointer — for passing to interop-imported functions
1923    /// that register content through the C ABI table directly.
1924    pub fn raw_api(&self) -> *const yog_abi::YogApi {
1925        self.api
1926    }
1927
1928    pub fn register_menu_entry(&mut self, label: &str, ui_id: &str) {
1929        let l = YogStr::from_str(label);
1930        let u = YogStr::from_str(ui_id);
1931        unsafe { ((*self.api).register_menu_entry)(self.ctx(), l, u) }
1932    }
1933
1934    /// Register a UI tree with an event callback.
1935    /// `ui_id` is the unique identifier (e.g. "mymod:menu").
1936    /// `handler` receives `(ui_id, event_id)` when a widget is clicked.
1937    pub fn register_ui<F>(&mut self, ui_id: &str, handler: F)
1938    where
1939        F: Fn(&str, &str) + Send + Sync + 'static,
1940    {
1941        let ud = Self::leak(handler);
1942        let id = YogStr::from_str(ui_id);
1943        let empty = YogStr::from_str("{}");
1944        unsafe { ((*self.api).register_ui)(self.ctx(), id, empty, ud, trampoline_ui_event::<F>) }
1945    }
1946
1947    // ── scheduler ────────────────────────────────────────────────────────────
1948
1949    pub fn schedule_once<F>(&self, delay_ticks: u64, handler: F)
1950    where
1951        F: Fn(&dyn Server) + Send + Sync + 'static,
1952    {
1953        let ud = Self::leak(handler);
1954        unsafe {
1955            ((*self.api).schedule_once)(self.ctx(), delay_ticks, ud, trampoline_scheduled::<F>)
1956        }
1957    }
1958
1959    pub fn schedule_repeating<F>(&self, period_ticks: u64, handler: F)
1960    where
1961        F: Fn(&dyn Server) + Send + Sync + 'static,
1962    {
1963        let ud = Self::leak(handler);
1964        unsafe {
1965            ((*self.api).schedule_repeating)(
1966                self.ctx(),
1967                period_ticks,
1968                ud,
1969                trampoline_scheduled::<F>,
1970            )
1971        }
1972    }
1973
1974    // ── client-side hooks (ABI minor 10) ─────────────────────────────────────
1975
1976    /// Register a handler called every client tick (render thread, no server).
1977    pub fn on_client_tick<F>(&mut self, handler: F)
1978    where
1979        F: Fn(&ClientTickEvent) + Send + Sync + 'static,
1980    {
1981        let ud = Self::leak(handler);
1982        unsafe { ((*self.api).on_client_tick)(self.ctx(), ud, trampoline_client_tick::<F>) }
1983    }
1984
1985    /// Register a render callback for a specific UI screen (`ui_id`).
1986    ///
1987    /// Called from `YogUIScreen.render()` — i.e. AFTER `renderBackground()` darkens
1988    /// the screen — so your UI draws on top of the dimmed world view.
1989    /// Use this instead of `on_hud_render` for book/inventory screens.
1990    ///
1991    /// Clicks are forwarded as `"click:X:Y"` via the `register_ui` handler so you
1992    /// can do hit-testing on your own stored layout.
1993    pub fn on_ui_render<F>(&mut self, ui_id: &str, handler: F)
1994    where
1995        F: Fn(&GfxContext) + Send + Sync + 'static,
1996    {
1997        let ud = Self::leak(handler);
1998        let id = YogStr::from_str(ui_id);
1999        unsafe { ((*self.api).on_ui_render)(self.ctx(), id, ud, trampoline_hud_render::<F>) }
2000    }
2001
2002    /// Register a handler called every frame when the HUD is rendered.
2003    ///
2004    /// `gfx` provides full GPU pipeline access plus 2D convenience draw calls.
2005    /// `view_proj` and `camera_pos` are zero in HUD context; use `gfx.draw2d()` for HUD elements.
2006    pub fn on_hud_render<F>(&mut self, handler: F)
2007    where
2008        F: Fn(&GfxContext) + Send + Sync + 'static,
2009    {
2010        let ud = Self::leak(handler);
2011        unsafe { ((*self.api).on_hud_render)(self.ctx(), ud, trampoline_hud_render::<F>) }
2012    }
2013
2014    /// Register a handler called every frame at the end of world rendering.
2015    ///
2016    /// `gfx.view_proj()` is the combined projection × view matrix (camera-relative).
2017    /// `gfx.camera_pos()` is the camera world position.
2018    /// To render at world position P, translate by `P - camera_pos` before drawing.
2019    pub fn on_world_render<F>(&mut self, handler: F)
2020    where
2021        F: Fn(&GfxContext) + Send + Sync + 'static,
2022    {
2023        let ud = Self::leak(handler);
2024        unsafe { ((*self.api).on_world_render)(self.ctx(), ud, trampoline_world_render::<F>) }
2025    }
2026
2027    /// Register a handler for keyboard input (client-side).
2028    /// Return `false` to prevent Minecraft from processing the key.
2029    pub fn on_key_press<F>(&mut self, handler: F)
2030    where
2031        F: Fn(&KeyPressEvent) -> bool + Send + Sync + 'static,
2032    {
2033        let ud = Self::leak(handler);
2034        unsafe { ((*self.api).on_key_press)(self.ctx(), ud, trampoline_key_press::<F>) }
2035    }
2036
2037    /// Register a handler called when a GUI screen is opened.
2038    pub fn on_screen_open<F>(&mut self, handler: F)
2039    where
2040        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2041    {
2042        let ud = Self::leak(handler);
2043        unsafe { ((*self.api).on_screen_open)(self.ctx(), ud, trampoline_screen::<F>) }
2044    }
2045
2046    /// Register a handler called when a GUI screen is closed.
2047    pub fn on_screen_close<F>(&mut self, handler: F)
2048    where
2049        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2050    {
2051        let ud = Self::leak(handler);
2052        unsafe { ((*self.api).on_screen_close)(self.ctx(), ud, trampoline_screen::<F>) }
2053    }
2054}
2055
2056unsafe extern "C" fn trampoline_ui_event<F>(
2057    ud: *mut c_void,
2058    ui_id: yog_abi::YogStr,
2059    event_id: yog_abi::YogStr,
2060) where
2061    F: Fn(&str, &str) + Send + Sync + 'static,
2062{
2063    let f = &*(ud as *const F);
2064    let ui = unsafe { ui_id.as_str() };
2065    let ev = unsafe { event_id.as_str() };
2066    f(ui, ev);
2067}
2068
2069unsafe extern "C" fn trampoline_chunk_generator<F>(
2070    ud: *mut c_void,
2071    writer: *const yog_abi::YogChunkWriterApi,
2072) where
2073    F: Fn(&ChunkWriter) + Send + Sync + 'static,
2074{
2075    let f = &*(ud as *const F);
2076    let writer = unsafe { ChunkWriter::from_raw(writer) };
2077    f(&writer);
2078}
2079
2080// ── Mod trait ─────────────────────────────────────────────────────────────────
2081
2082/// Implemented by every Yog mod. Called once at startup to register handlers.
2083pub trait Mod {
2084    fn register(registry: &mut Registry);
2085}