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, 
14    YogChatEvent, YogCommandEvent, YogContainerCloseEvent, YogContainerOpenEvent, YogCraftEvent,
15    YogEntityDamageEvent, YogEntityDeathEvent, YogEntityInteractEvent, YogEntitySpawnEvent,
16    YogExplosionEvent, YogGfxApi, YogItemPickupEvent, YogMachineCraftEvent,
17    YogKeyPressEvent, YogPacketEvent, YogPlaceBlockEvent, YogPlayerDeathEvent, YogPlayerEvent,
18    YogPlayerMoveEvent, YogPlayerRespawnEvent, YogProjectileHitEvent, YogServer,
19    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::{ArmorMaterial, BlockDef, ItemDef, Recipe, SoundGroup, StartupGrant, ToolMaterial};
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
72        take_owned(s.free_str, owned)
73    }
74
75    fn set_block(&self, dimension: &str, pos: yog_core::BlockPos, block_id: &str) -> bool {
76        let s = srv!(self);
77        unsafe {
78            (s.set_block)(
79                s.ctx,
80                YogStr::from_str(dimension),
81                yog_abi::YogBlockPos {
82                    x: pos.x,
83                    y: pos.y,
84                    z: pos.z,
85                },
86                YogStr::from_str(block_id),
87            )
88        }
89    }
90
91    fn give_item(&self, player: &str, item_id: &str, count: u32) -> bool {
92        let s = srv!(self);
93        unsafe {
94            (s.give_item)(
95                s.ctx,
96                YogStr::from_str(player),
97                YogStr::from_str(item_id),
98                count,
99            )
100        }
101    }
102
103    fn teleport(&self, player: &str, x: f64, y: f64, z: f64) -> bool {
104        let s = srv!(self);
105        unsafe {
106            (s.player_teleport)(
107                s.ctx,
108                YogStr::from_str(player),
109                yog_abi::YogVec3 { x, y, z },
110            )
111        }
112    }
113
114    fn send_to_player(&self, player: &str, channel: &str, payload: &[u8]) -> bool {
115        let s = srv!(self);
116        unsafe {
117            (s.send_to_player)(
118                s.ctx,
119                YogStr::from_str(player),
120                YogStr::from_str(channel),
121                payload.as_ptr(),
122                payload.len() as u32,
123            )
124        }
125    }
126
127    fn send_to_server(&self, channel: &str, payload: &[u8]) -> bool {
128        let s = srv!(self);
129        unsafe {
130            (s.send_to_server)(
131                s.ctx,
132                YogStr::from_str(channel),
133                payload.as_ptr(),
134                payload.len() as u32,
135            )
136        }
137    }
138
139    fn entity_teleport(&self, uuid: &str, x: f64, y: f64, z: f64) -> bool {
140        let s = srv!(self);
141        unsafe { (s.entity_teleport)(s.ctx, YogStr::from_str(uuid), yog_abi::YogVec3 { x, y, z }) }
142    }
143
144    fn entity_position(&self, uuid: &str) -> Option<(f64, f64, f64)> {
145        let s = srv!(self);
146        let mut out = yog_abi::YogVec3 {
147            x: 0.0,
148            y: 0.0,
149            z: 0.0,
150        };
151        if unsafe { (s.entity_position)(s.ctx, YogStr::from_str(uuid), &mut out) } {
152            Some((out.x, out.y, out.z))
153        } else {
154            None
155        }
156    }
157
158    fn entity_health(&self, uuid: &str) -> Option<f32> {
159        let s = srv!(self);
160        let mut hp = 0f32;
161        if unsafe { (s.entity_health)(s.ctx, YogStr::from_str(uuid), &mut hp) } {
162            Some(hp)
163        } else {
164            None
165        }
166    }
167
168    fn entity_set_health(&self, uuid: &str, health: f32) -> bool {
169        let s = srv!(self);
170        unsafe { (s.entity_set_health)(s.ctx, YogStr::from_str(uuid), health) }
171    }
172
173    fn entity_kill(&self, uuid: &str) -> bool {
174        let s = srv!(self);
175        unsafe { (s.entity_kill)(s.ctx, YogStr::from_str(uuid)) }
176    }
177
178    fn spawn_entity(
179        &self,
180        entity_type: &str,
181        dimension: &str,
182        x: f64,
183        y: f64,
184        z: f64,
185    ) -> Option<String> {
186        let s = srv!(self);
187        let owned = unsafe {
188            (s.spawn_entity)(
189                s.ctx,
190                YogStr::from_str(entity_type),
191                YogStr::from_str(dimension),
192                yog_abi::YogVec3 { x, y, z },
193            )
194        };
195
196        take_owned(s.free_str, owned)
197    }
198
199    fn entity_add_effect(
200        &self,
201        uuid: &str,
202        effect_id: &str,
203        duration_ticks: i32,
204        amplifier: u8,
205        show_particles: bool,
206    ) -> bool {
207        let s = srv!(self);
208        unsafe {
209            (s.entity_add_effect)(
210                s.ctx,
211                YogStr::from_str(uuid),
212                YogStr::from_str(effect_id),
213                duration_ticks,
214                amplifier,
215                show_particles,
216            )
217        }
218    }
219
220    fn entity_remove_effect(&self, uuid: &str, effect_id: &str) -> bool {
221        let s = srv!(self);
222        unsafe {
223            (s.entity_remove_effect)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(effect_id))
224        }
225    }
226
227    fn entity_clear_effects(&self, uuid: &str) -> bool {
228        let s = srv!(self);
229        unsafe { (s.entity_clear_effects)(s.ctx, YogStr::from_str(uuid)) }
230    }
231
232    fn drop_loot(&self, table_id: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
233        let s = srv!(self);
234        unsafe {
235            (s.drop_loot)(
236                s.ctx,
237                YogStr::from_str(table_id),
238                YogStr::from_str(dimension),
239                yog_abi::YogVec3 { x, y, z },
240            )
241        }
242    }
243
244    fn has_item_tag(&self, item_id: &str, tag_id: &str) -> bool {
245        let s = srv!(self);
246        unsafe { (s.has_item_tag)(s.ctx, YogStr::from_str(item_id), YogStr::from_str(tag_id)) }
247    }
248
249    fn has_block_tag(&self, block_id: &str, tag_id: &str) -> bool {
250        let s = srv!(self);
251        unsafe { (s.has_block_tag)(s.ctx, YogStr::from_str(block_id), YogStr::from_str(tag_id)) }
252    }
253
254    fn world_time(&self, dimension: &str) -> Option<i64> {
255        let s = srv!(self);
256        let mut t = 0i64;
257        if unsafe { (s.world_time)(s.ctx, YogStr::from_str(dimension), &mut t) } {
258            Some(t)
259        } else {
260            None
261        }
262    }
263
264    fn world_set_time(&self, dimension: &str, time: i64) -> bool {
265        let s = srv!(self);
266        unsafe { (s.set_time)(s.ctx, YogStr::from_str(dimension), time) }
267    }
268
269    fn world_is_raining(&self, dimension: &str) -> bool {
270        let s = srv!(self);
271        unsafe { (s.is_raining)(s.ctx, YogStr::from_str(dimension)) }
272    }
273
274    fn world_set_weather(&self, dimension: &str, raining: bool, duration_ticks: i32) -> bool {
275        let s = srv!(self);
276        unsafe { (s.set_weather)(s.ctx, YogStr::from_str(dimension), raining, duration_ticks) }
277    }
278
279    fn entity_velocity(&self, uuid: &str) -> Option<(f64, f64, f64)> {
280        let s = srv!(self);
281        let mut v = yog_abi::YogVec3 {
282            x: 0.0,
283            y: 0.0,
284            z: 0.0,
285        };
286        if unsafe { (s.entity_velocity)(s.ctx, YogStr::from_str(uuid), &mut v) } {
287            Some((v.x, v.y, v.z))
288        } else {
289            None
290        }
291    }
292
293    fn entity_set_velocity(&self, uuid: &str, vx: f64, vy: f64, vz: f64) -> bool {
294        let s = srv!(self);
295        unsafe {
296            (s.entity_set_velocity)(
297                s.ctx,
298                YogStr::from_str(uuid),
299                yog_abi::YogVec3 {
300                    x: vx,
301                    y: vy,
302                    z: vz,
303                },
304            )
305        }
306    }
307
308    fn entity_add_velocity(&self, uuid: &str, vx: f64, vy: f64, vz: f64) -> bool {
309        let s = srv!(self);
310        unsafe {
311            (s.entity_add_velocity)(
312                s.ctx,
313                YogStr::from_str(uuid),
314                yog_abi::YogVec3 {
315                    x: vx,
316                    y: vy,
317                    z: vz,
318                },
319            )
320        }
321    }
322
323    fn scoreboard_get(&self, objective: &str, player: &str) -> Option<i32> {
324        let s = srv!(self);
325        let mut score = 0i32;
326        if unsafe {
327            (s.scoreboard_get)(
328                s.ctx,
329                YogStr::from_str(objective),
330                YogStr::from_str(player),
331                &mut score,
332            )
333        } {
334            Some(score)
335        } else {
336            None
337        }
338    }
339
340    fn scoreboard_set(&self, objective: &str, player: &str, score: i32) -> bool {
341        let s = srv!(self);
342        unsafe {
343            (s.scoreboard_set)(
344                s.ctx,
345                YogStr::from_str(objective),
346                YogStr::from_str(player),
347                score,
348            )
349        }
350    }
351
352    fn scoreboard_add(&self, objective: &str, player: &str, delta: i32) -> Option<i32> {
353        let s = srv!(self);
354        let mut new_score = 0i32;
355        if unsafe {
356            (s.scoreboard_add)(
357                s.ctx,
358                YogStr::from_str(objective),
359                YogStr::from_str(player),
360                delta,
361                &mut new_score,
362            )
363        } {
364            Some(new_score)
365        } else {
366            None
367        }
368    }
369
370    fn game_dir(&self) -> String {
371        let s = srv!(self);
372        let owned = unsafe { (s.game_dir)(s.ctx) };
373        take_owned(s.free_str, owned).unwrap_or_default()
374    }
375
376    fn play_sound(
377        &self,
378        dimension: &str,
379        x: f64,
380        y: f64,
381        z: f64,
382        sound_id: &str,
383        volume: f32,
384        pitch: f32,
385    ) -> bool {
386        let s = srv!(self);
387        unsafe {
388            (s.play_sound)(
389                s.ctx,
390                YogStr::from_str(dimension),
391                yog_abi::YogVec3 { x, y, z },
392                YogStr::from_str(sound_id),
393                volume,
394                pitch,
395            )
396        }
397    }
398
399    fn play_sound_to_player(&self, player: &str, sound_id: &str, volume: f32, pitch: f32) -> bool {
400        let s = srv!(self);
401        unsafe {
402            (s.play_sound_player)(
403                s.ctx,
404                YogStr::from_str(player),
405                YogStr::from_str(sound_id),
406                volume,
407                pitch,
408            )
409        }
410    }
411
412    fn send_title(
413        &self,
414        player: &str,
415        title: &str,
416        subtitle: &str,
417        fadein: i32,
418        stay: i32,
419        fadeout: i32,
420    ) -> bool {
421        let s = srv!(self);
422        unsafe {
423            (s.send_title)(
424                s.ctx,
425                YogStr::from_str(player),
426                YogStr::from_str(title),
427                YogStr::from_str(subtitle),
428                fadein,
429                stay,
430                fadeout,
431            )
432        }
433    }
434
435    fn entity_rotation(&self, uuid: &str) -> Option<(f32, f32)> {
436        let s = srv!(self);
437        let mut out = yog_abi::YogVec3 {
438            x: 0.0,
439            y: 0.0,
440            z: 0.0,
441        };
442        let ok = unsafe { (s.entity_rotation)(s.ctx, YogStr::from_str(uuid), &mut out) };
443        if ok {
444            Some((out.x as f32, out.y as f32))
445        } else {
446            None
447        }
448    }
449
450    fn send_actionbar(&self, player: &str, message: &str) -> bool {
451        let s = srv!(self);
452        unsafe { (s.send_actionbar)(s.ctx, YogStr::from_str(player), YogStr::from_str(message)) }
453    }
454
455    fn kick_player(&self, player: &str, reason: &str) -> bool {
456        let s = srv!(self);
457        unsafe { (s.kick_player)(s.ctx, YogStr::from_str(player), YogStr::from_str(reason)) }
458    }
459
460    fn set_gamemode(&self, player: &str, gamemode: &str) -> bool {
461        let s = srv!(self);
462        unsafe { (s.set_gamemode)(s.ctx, YogStr::from_str(player), YogStr::from_str(gamemode)) }
463    }
464
465    fn bossbar_create(&self, id: &str, title: &str, color: &str, style: &str) -> bool {
466        let s = srv!(self);
467        unsafe {
468            (s.bossbar_create)(
469                s.ctx,
470                YogStr::from_str(id),
471                YogStr::from_str(title),
472                YogStr::from_str(color),
473                YogStr::from_str(style),
474            )
475        }
476    }
477
478    fn bossbar_remove(&self, id: &str) -> bool {
479        let s = srv!(self);
480        unsafe { (s.bossbar_remove)(s.ctx, YogStr::from_str(id)) }
481    }
482
483    fn bossbar_set_title(&self, id: &str, title: &str) -> bool {
484        let s = srv!(self);
485        unsafe { (s.bossbar_set_title)(s.ctx, YogStr::from_str(id), YogStr::from_str(title)) }
486    }
487
488    fn bossbar_set_progress(&self, id: &str, progress: f32) -> bool {
489        let s = srv!(self);
490        unsafe { (s.bossbar_set_progress)(s.ctx, YogStr::from_str(id), progress) }
491    }
492
493    fn bossbar_set_color(&self, id: &str, color: &str) -> bool {
494        let s = srv!(self);
495        unsafe { (s.bossbar_set_color)(s.ctx, YogStr::from_str(id), YogStr::from_str(color)) }
496    }
497
498    fn bossbar_add_player(&self, id: &str, player: &str) -> bool {
499        let s = srv!(self);
500        unsafe { (s.bossbar_add_player)(s.ctx, YogStr::from_str(id), YogStr::from_str(player)) }
501    }
502
503    fn bossbar_remove_player(&self, id: &str, player: &str) -> bool {
504        let s = srv!(self);
505        unsafe { (s.bossbar_remove_player)(s.ctx, YogStr::from_str(id), YogStr::from_str(player)) }
506    }
507
508    fn bossbar_set_visible(&self, id: &str, visible: bool) -> bool {
509        let s = srv!(self);
510        unsafe { (s.bossbar_set_visible)(s.ctx, YogStr::from_str(id), visible) }
511    }
512
513    fn online_players(&self) -> Vec<String> {
514        let s = srv!(self);
515        let owned = unsafe { (s.online_players)(s.ctx) };
516        let Some(text) = take_owned(s.free_str, owned) else {
517            return Vec::new();
518        };
519        if text.is_empty() {
520            Vec::new()
521        } else {
522            text.lines().map(str::to_owned).collect()
523        }
524    }
525
526    fn get_block_nbt(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<String> {
527        let s = srv!(self);
528        let owned = unsafe {
529            (s.get_block_nbt)(
530                s.ctx,
531                YogStr::from_str(dimension),
532                yog_abi::YogBlockPos {
533                    x: pos.x,
534                    y: pos.y,
535                    z: pos.z,
536                },
537            )
538        };
539
540        take_owned(s.free_str, owned)
541    }
542
543    fn set_block_nbt(&self, dimension: &str, pos: yog_core::BlockPos, snbt: &str) -> bool {
544        let s = srv!(self);
545        unsafe {
546            (s.set_block_nbt)(
547                s.ctx,
548                YogStr::from_str(dimension),
549                yog_abi::YogBlockPos {
550                    x: pos.x,
551                    y: pos.y,
552                    z: pos.z,
553                },
554                YogStr::from_str(snbt),
555            )
556        }
557    }
558
559    fn get_inventory_slot(
560        &self,
561        dimension: &str,
562        pos: yog_core::BlockPos,
563        slot: u32,
564    ) -> Option<(String, u32, String)> {
565        let s = srv!(self);
566        let owned = unsafe {
567            (s.get_inventory_slot)(
568                s.ctx,
569                YogStr::from_str(dimension),
570                yog_abi::YogBlockPos {
571                    x: pos.x,
572                    y: pos.y,
573                    z: pos.z,
574                },
575                slot,
576            )
577        };
578        let text = take_owned(s.free_str, owned)?;
579        let mut it = text.splitn(3, '\t');
580        let item_id = it.next()?.to_owned();
581        let count = it.next()?.parse().ok()?;
582        let snbt = it.next().unwrap_or("{}").to_owned();
583        Some((item_id, count, snbt))
584    }
585
586    fn set_inventory_slot(
587        &self,
588        dimension: &str,
589        pos: yog_core::BlockPos,
590        slot: u32,
591        item_id: &str,
592        count: u32,
593        snbt: &str,
594    ) -> bool {
595        // The ABI's item id carries the SNBT after a tab.
596        let item = if snbt.is_empty() { item_id.to_string() } else { format!("{item_id}\t{snbt}") };
597        let s = srv!(self);
598        unsafe {
599            (s.set_inventory_slot)(
600                s.ctx,
601                YogStr::from_str(dimension),
602                yog_abi::YogBlockPos {
603                    x: pos.x,
604                    y: pos.y,
605                    z: pos.z,
606                },
607                slot,
608                YogStr::from_str(&item),
609                count,
610            )
611        }
612    }
613
614    fn player_inventory(&self, player: &str) -> Vec<(u32, String, u32)> {
615        let s = srv!(self);
616        let owned = unsafe { (s.player_inventory)(s.ctx, YogStr::from_str(player)) };
617        let Some(text) = take_owned(s.free_str, owned) else {
618            return Vec::new();
619        };
620        text.lines()
621            .filter_map(|line| {
622                let mut it = line.split('\t');
623                let slot: u32 = it.next()?.parse().ok()?;
624                let item_id = it.next()?.to_owned();
625                let count: u32 = it.next()?.parse().ok()?;
626                Some((slot, item_id, count))
627            })
628            .collect()
629    }
630
631    fn player_set_slot(&self, player: &str, slot: u32, item_id: &str, count: u32) -> bool {
632        let s = srv!(self);
633        unsafe {
634            (s.player_set_slot)(
635                s.ctx,
636                YogStr::from_str(player),
637                slot,
638                YogStr::from_str(item_id),
639                count,
640            )
641        }
642    }
643
644    fn teleport_to_dim(&self, player: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
645        let s = srv!(self);
646        unsafe {
647            (s.player_teleport_dim)(
648                s.ctx,
649                YogStr::from_str(player),
650                YogStr::from_str(dimension),
651                yog_abi::YogVec3 { x, y, z },
652            )
653        }
654    }
655
656    fn entity_teleport_to_dim(&self, uuid: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
657        let s = srv!(self);
658        unsafe {
659            (s.entity_teleport_dim)(
660                s.ctx,
661                YogStr::from_str(uuid),
662                YogStr::from_str(dimension),
663                yog_abi::YogVec3 { x, y, z },
664            )
665        }
666    }
667
668    fn world_entity_count(&self, dimension: &str, entity_type: &str) -> i32 {
669        let s = srv!(self);
670        unsafe {
671            (s.world_entity_count)(
672                s.ctx,
673                YogStr::from_str(dimension),
674                YogStr::from_str(entity_type),
675            )
676        }
677    }
678
679    fn entity_get_nbt(&self, uuid: &str) -> Option<String> {
680        let s = srv!(self);
681        let owned = unsafe { (s.entity_get_nbt)(s.ctx, YogStr::from_str(uuid)) };
682
683        take_owned(s.free_str, owned)
684    }
685
686    fn entity_set_nbt(&self, uuid: &str, snbt: &str) -> bool {
687        let s = srv!(self);
688        unsafe { (s.entity_set_nbt)(s.ctx, YogStr::from_str(uuid), YogStr::from_str(snbt)) }
689    }
690
691    fn spawn_particles(
692        &self,
693        dimension: &str,
694        x: f64,
695        y: f64,
696        z: f64,
697        particle_type: &str,
698        count: i32,
699        dx: f64,
700        dy: f64,
701        dz: f64,
702        speed: f64,
703    ) -> bool {
704        let s = srv!(self);
705        unsafe {
706            (s.spawn_particles)(
707                s.ctx,
708                YogStr::from_str(dimension),
709                yog_abi::YogVec3 { x, y, z },
710                YogStr::from_str(particle_type),
711                count,
712                dx,
713                dy,
714                dz,
715                speed,
716            )
717        }
718    }
719
720    fn entity_attribute_get(&self, uuid: &str, attribute_id: &str) -> Option<f64> {
721        let s = srv!(self);
722        let v = unsafe {
723            (s.entity_attribute_get)(
724                s.ctx,
725                YogStr::from_str(uuid),
726                YogStr::from_str(attribute_id),
727            )
728        };
729        if v.is_nan() { None } else { Some(v) }
730    }
731
732    fn entity_attribute_set(&self, uuid: &str, attribute_id: &str, value: f64) -> bool {
733        let s = srv!(self);
734        unsafe {
735            (s.entity_attribute_set)(
736                s.ctx,
737                YogStr::from_str(uuid),
738                YogStr::from_str(attribute_id),
739                value,
740            )
741        }
742    }
743
744    fn get_held_item_nbt(&self, player: &str) -> Option<String> {
745        let s = srv!(self);
746        let owned = unsafe { (s.get_held_item_nbt)(s.ctx, YogStr::from_str(player)) };
747
748        take_owned(s.free_str, owned)
749    }
750
751    fn set_held_item_nbt(&self, player: &str, snbt: &str) -> bool {
752        let s = srv!(self);
753        unsafe { (s.set_held_item_nbt)(s.ctx, YogStr::from_str(player), YogStr::from_str(snbt)) }
754    }
755
756    fn get_offhand_item_nbt(&self, player: &str) -> Option<String> {
757        let s = srv!(self);
758        let owned = unsafe { (s.get_offhand_item_nbt)(s.ctx, YogStr::from_str(player)) };
759
760        take_owned(s.free_str, owned)
761    }
762
763    fn set_offhand_item_nbt(&self, player: &str, snbt: &str) -> bool {
764        let s = srv!(self);
765        unsafe { (s.set_offhand_item_nbt)(s.ctx, YogStr::from_str(player), YogStr::from_str(snbt)) }
766    }
767
768    fn get_slot_item(&self, player: &str, slot: u32) -> Option<(String, u32, String)> {
769        let s = srv!(self);
770        let owned = unsafe { (s.get_slot_item)(s.ctx, YogStr::from_str(player), slot) };
771        let text = take_owned(s.free_str, owned)?;
772        let mut it = text.splitn(3, '\t');
773        let item_id = it.next()?.to_owned();
774        let count: u32 = it.next()?.parse().ok()?;
775        let nbt = it.next().unwrap_or("{}").to_owned();
776        Some((item_id, count, nbt))
777    }
778
779    fn set_slot_item(
780        &self,
781        player: &str,
782        slot: u32,
783        item_id: &str,
784        count: u32,
785        snbt: &str,
786    ) -> bool {
787        let s = srv!(self);
788        unsafe {
789            (s.set_slot_item)(
790                s.ctx,
791                YogStr::from_str(player),
792                slot,
793                YogStr::from_str(item_id),
794                count,
795                YogStr::from_str(snbt),
796            )
797        }
798    }
799
800    // ── world queries & effects (ABI minor 1) ────────────────────────────────
801
802    fn entity_info(&self, uuid: &str) -> Option<yog_core::EntityInfo> {
803        let s = srv!(self);
804        let owned = unsafe { (s.entity_info)(s.ctx, YogStr::from_str(uuid)) };
805        take_owned(s.free_str, owned).and_then(|l| yog_core::EntityInfo::decode(&l))
806    }
807
808    fn entities_in_box(
809        &self,
810        dimension: &str,
811        min: (f64, f64, f64),
812        max: (f64, f64, f64),
813    ) -> Vec<String> {
814        let s = srv!(self);
815        let owned =
816            unsafe { (s.entities_in_box)(s.ctx, YogStr::from_str(dimension), v3(min), v3(max)) };
817        take_owned(s.free_str, owned)
818            .map(|t| {
819                t.lines()
820                    .filter(|l| !l.is_empty())
821                    .map(str::to_owned)
822                    .collect()
823            })
824            .unwrap_or_default()
825    }
826
827    fn raycast_block(
828        &self,
829        dimension: &str,
830        from: (f64, f64, f64),
831        to: (f64, f64, f64),
832    ) -> Option<yog_core::BlockHit> {
833        let s = srv!(self);
834        let owned =
835            unsafe { (s.raycast_block)(s.ctx, YogStr::from_str(dimension), v3(from), v3(to)) };
836        take_owned(s.free_str, owned).and_then(|l| yog_core::BlockHit::decode(&l))
837    }
838
839    fn raycast_entity(
840        &self,
841        dimension: &str,
842        from: (f64, f64, f64),
843        to: (f64, f64, f64),
844        exclude: &str,
845    ) -> Option<String> {
846        let s = srv!(self);
847        let owned = unsafe {
848            (s.raycast_entity)(
849                s.ctx,
850                YogStr::from_str(dimension),
851                v3(from),
852                v3(to),
853                YogStr::from_str(exclude),
854            )
855        };
856        take_owned(s.free_str, owned).filter(|u| !u.is_empty())
857    }
858
859    fn block_info(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<yog_core::BlockInfo> {
860        let s = srv!(self);
861        let owned = unsafe { (s.block_info)(s.ctx, YogStr::from_str(dimension), bp(pos)) };
862        take_owned(s.free_str, owned).and_then(|l| yog_core::BlockInfo::decode(&l))
863    }
864
865    fn break_block(
866        &self,
867        dimension: &str,
868        pos: yog_core::BlockPos,
869        drop: bool,
870        breaker: &str,
871    ) -> bool {
872        let s = srv!(self);
873        unsafe {
874            (s.break_block)(
875                s.ctx,
876                YogStr::from_str(dimension),
877                bp(pos),
878                drop,
879                YogStr::from_str(breaker),
880            )
881        }
882    }
883
884    fn place_block_from_slot(
885        &self,
886        player: &str,
887        slot: u32,
888        dimension: &str,
889        pos: yog_core::BlockPos,
890    ) -> bool {
891        let s = srv!(self);
892        unsafe {
893            (s.place_block_from_slot)(
894                s.ctx,
895                YogStr::from_str(player),
896                slot,
897                YogStr::from_str(dimension),
898                bp(pos),
899            )
900        }
901    }
902
903    fn bonemeal(&self, dimension: &str, pos: yog_core::BlockPos) -> bool {
904        let s = srv!(self);
905        unsafe { (s.bonemeal)(s.ctx, YogStr::from_str(dimension), bp(pos)) }
906    }
907
908    fn explode(
909        &self,
910        dimension: &str,
911        x: f64,
912        y: f64,
913        z: f64,
914        power: f32,
915        fire: bool,
916        source: &str,
917    ) -> bool {
918        let s = srv!(self);
919        unsafe {
920            (s.explode)(
921                s.ctx,
922                YogStr::from_str(dimension),
923                v3((x, y, z)),
924                power,
925                fire,
926                YogStr::from_str(source),
927            )
928        }
929    }
930
931    fn tellraw(&self, player: &str, json: &str) -> bool {
932        let s = srv!(self);
933        unsafe { (s.tellraw)(s.ctx, YogStr::from_str(player), YogStr::from_str(json)) }
934    }
935
936    fn entity_damage(&self, uuid: &str, amount: f32, damage_type: &str, attacker: &str) -> bool {
937        let s = srv!(self);
938        unsafe {
939            (s.entity_damage)(
940                s.ctx,
941                YogStr::from_str(uuid),
942                amount,
943                YogStr::from_str(damage_type),
944                YogStr::from_str(attacker),
945            )
946        }
947    }
948
949    fn entity_set_fire_ticks(&self, uuid: &str, ticks: i32) -> bool {
950        let s = srv!(self);
951        unsafe { (s.entity_set_fire_ticks)(s.ctx, YogStr::from_str(uuid), ticks) }
952    }
953
954    fn player_add_xp(&self, player: &str, amount: i32) -> bool {
955        let s = srv!(self);
956        unsafe { (s.player_add_xp)(s.ctx, YogStr::from_str(player), amount) }
957    }
958
959    fn player_set_may_fly(&self, player: &str, may_fly: bool) -> bool {
960        let s = srv!(self);
961        unsafe { (s.player_set_may_fly)(s.ctx, YogStr::from_str(player), may_fly) }
962    }
963
964    fn player_info(&self, player: &str) -> Option<yog_core::PlayerInfo> {
965        let s = srv!(self);
966        let owned = unsafe { (s.player_info)(s.ctx, YogStr::from_str(player)) };
967        take_owned(s.free_str, owned).and_then(|l| yog_core::PlayerInfo::decode(&l))
968    }
969
970    fn spawn_item(
971        &self,
972        dimension: &str,
973        pos: (f64, f64, f64),
974        vel: (f64, f64, f64),
975        item_id: &str,
976        count: u32,
977        snbt: &str,
978    ) -> Option<String> {
979        let s = srv!(self);
980        let owned = unsafe {
981            (s.spawn_item)(
982                s.ctx,
983                YogStr::from_str(dimension),
984                v3(pos),
985                v3(vel),
986                YogStr::from_str(item_id),
987                count,
988                YogStr::from_str(snbt),
989            )
990        };
991        take_owned(s.free_str, owned).filter(|u| !u.is_empty())
992    }
993
994    fn item_entity_stack(&self, uuid: &str) -> Option<(String, u32, String)> {
995        let s = srv!(self);
996        let owned = unsafe { (s.item_entity_stack)(s.ctx, YogStr::from_str(uuid)) };
997        let text = take_owned(s.free_str, owned)?;
998        let mut it = text.splitn(3, '\t');
999        let item_id = it.next()?.to_owned();
1000        let count = it.next()?.parse().ok()?;
1001        let nbt = it.next().unwrap_or("{}").to_owned();
1002        Some((item_id, count, nbt))
1003    }
1004
1005    fn item_entity_set_stack(&self, uuid: &str, item_id: &str, count: u32, snbt: &str) -> bool {
1006        let s = srv!(self);
1007        unsafe {
1008            (s.item_entity_set_stack)(
1009                s.ctx,
1010                YogStr::from_str(uuid),
1011                YogStr::from_str(item_id),
1012                count,
1013                YogStr::from_str(snbt),
1014            )
1015        }
1016    }
1017
1018    fn actionbar_json(&self, player: &str, json: &str) -> bool {
1019        let s = srv!(self);
1020        unsafe { (s.actionbar_json)(s.ctx, YogStr::from_str(player), YogStr::from_str(json)) }
1021    }
1022
1023    fn use_item_on_block(
1024        &self,
1025        dimension: &str,
1026        pos: yog_core::BlockPos,
1027        face: yog_core::Face,
1028        item_id: &str,
1029        player: &str,
1030    ) -> bool {
1031        let s = srv!(self);
1032        unsafe {
1033            (s.use_item_on_block)(
1034                s.ctx,
1035                YogStr::from_str(dimension),
1036                bp(pos),
1037                face.index(),
1038                YogStr::from_str(item_id),
1039                YogStr::from_str(player),
1040            )
1041        }
1042    }
1043
1044    fn pour_fluid(&self, dimension: &str, pos: yog_core::BlockPos, bucket_item_id: &str) -> bool {
1045        let s = srv!(self);
1046        unsafe {
1047            (s.pour_fluid)(
1048                s.ctx,
1049                YogStr::from_str(dimension),
1050                bp(pos),
1051                YogStr::from_str(bucket_item_id),
1052            )
1053        }
1054    }
1055
1056    fn has_entity_tag(&self, entity_type: &str, tag_id: &str) -> bool {
1057        let s = srv!(self);
1058        unsafe {
1059            (s.has_entity_tag)(
1060                s.ctx,
1061                YogStr::from_str(entity_type),
1062                YogStr::from_str(tag_id),
1063            )
1064        }
1065    }
1066
1067    fn item_block(&self, item_id: &str) -> Option<String> {
1068        let s = srv!(self);
1069        let owned = unsafe { (s.item_block)(s.ctx, YogStr::from_str(item_id)) };
1070        take_owned(s.free_str, owned).filter(|b| !b.is_empty())
1071    }
1072
1073    fn place_feature(&self, dimension: &str, pos: yog_core::BlockPos, feature_id: &str) -> bool {
1074        let s = srv!(self);
1075        unsafe {
1076            (s.place_feature)(
1077                s.ctx,
1078                YogStr::from_str(dimension),
1079                bp(pos),
1080                YogStr::from_str(feature_id),
1081            )
1082        }
1083    }
1084
1085    fn set_item_cooldown(&self, player: &str, item_id: &str, ticks: u32) -> bool {
1086        let s = srv!(self);
1087        unsafe { (s.set_item_cooldown)(s.ctx, YogStr::from_str(player), YogStr::from_str(item_id), ticks.min(i32::MAX as u32) as i32) }
1088    }
1089
1090    fn entity_teleport_with_passengers(&self, uuid: &str, dimension: &str, x: f64, y: f64, z: f64) -> bool {
1091        let s = srv!(self);
1092        unsafe {
1093            (s.entity_teleport_with_passengers)(
1094                s.ctx,
1095                YogStr::from_str(uuid),
1096                YogStr::from_str(dimension),
1097                yog_abi::YogVec3 { x, y, z },
1098            )
1099        }
1100    }
1101
1102    fn redstone_power(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<u8> {
1103        let s = srv!(self);
1104        let p = unsafe { (s.redstone_power)(s.ctx, YogStr::from_str(dimension), bp(pos)) };
1105        (0..=15).contains(&p).then_some(p as u8)
1106    }
1107
1108    fn set_redstone_output(&self, dimension: &str, pos: yog_core::BlockPos, level: u8) -> bool {
1109        let s = srv!(self);
1110        unsafe { (s.set_redstone_output)(s.ctx, YogStr::from_str(dimension), bp(pos), level.min(15) as i32) }
1111    }
1112
1113    fn get_block_state(&self, dimension: &str, pos: yog_core::BlockPos) -> Option<String> {
1114        let s = srv!(self);
1115        let owned = unsafe { (s.get_block_state)(s.ctx, YogStr::from_str(dimension), bp(pos)) };
1116        take_owned(s.free_str, owned).filter(|b| !b.is_empty())
1117    }
1118
1119    fn set_block_state(&self, dimension: &str, pos: yog_core::BlockPos, state: &str) -> bool {
1120        let s = srv!(self);
1121        unsafe { (s.set_block_state)(s.ctx, YogStr::from_str(dimension), bp(pos), YogStr::from_str(state)) }
1122    }
1123
1124    fn world_is_thundering(&self, dimension: &str) -> bool {
1125        let s = srv!(self);
1126        unsafe { (s.world_is_thundering)(s.ctx, YogStr::from_str(dimension)) }
1127    }
1128
1129    fn world_set_thunder(&self, dimension: &str, thundering: bool, duration_ticks: i32) -> bool {
1130        let s = srv!(self);
1131        unsafe { (s.world_set_thunder)(s.ctx, YogStr::from_str(dimension), thundering, duration_ticks) }
1132    }
1133
1134    fn fill_region(&self, dimension: &str, from: yog_core::BlockPos, to: yog_core::BlockPos, state: &str) -> Option<u32> {
1135        let s = srv!(self);
1136        let n = unsafe { (s.fill_region)(s.ctx, YogStr::from_str(dimension), bp(from), bp(to), YogStr::from_str(state)) };
1137        u32::try_from(n).ok()
1138    }
1139
1140    fn scan_region(&self, dimension: &str, from: yog_core::BlockPos, to: yog_core::BlockPos) -> Vec<(yog_core::BlockPos, String)> {
1141        let s = srv!(self);
1142        let owned = unsafe { (s.scan_region)(s.ctx, YogStr::from_str(dimension), bp(from), bp(to)) };
1143        let Some(text) = take_owned(s.free_str, owned) else {
1144            return Vec::new();
1145        };
1146        text.lines()
1147            .filter_map(|line| {
1148                let mut it = line.splitn(4, ' ');
1149                let (x, y, z) = (it.next()?.parse().ok()?, it.next()?.parse().ok()?, it.next()?.parse().ok()?);
1150                Some((yog_core::BlockPos { x, y, z }, it.next()?.to_string()))
1151            })
1152            .collect()
1153    }
1154}
1155
1156/// Copy a runtime-owned string out and free it; `None` for NONE.
1157pub(crate) fn take_owned(
1158    free_str: unsafe extern "C" fn(ptr: *mut u8, len: u32),
1159    owned: yog_abi::YogOwnedStr,
1160) -> Option<String> {
1161    if owned.is_none() {
1162        return None;
1163    }
1164    // SAFETY: a non-NONE owned string is `len` valid bytes until freed.
1165    let text = unsafe {
1166        String::from_utf8_lossy(std::slice::from_raw_parts(owned.ptr, owned.len as usize))
1167            .into_owned()
1168    };
1169    unsafe { free_str(owned.ptr, owned.len) };
1170    Some(text)
1171}
1172
1173fn v3((x, y, z): (f64, f64, f64)) -> yog_abi::YogVec3 {
1174    yog_abi::YogVec3 { x, y, z }
1175}
1176
1177fn bp(pos: yog_core::BlockPos) -> yog_abi::YogBlockPos {
1178    yog_abi::YogBlockPos {
1179        x: pos.x,
1180        y: pos.y,
1181        z: pos.z,
1182    }
1183}
1184
1185// ── Trampoline helpers ────────────────────────────────────────────────────────
1186//
1187// A panic must never unwind out of a trampoline: the runtime calls them
1188// through `extern "C"`, so it would abort the whole game. `guard` stops it
1189// at the boundary — the panic message is already in the log — and the
1190// event goes on as if the mod hadn't handled it.
1191
1192fn guard<R>(fallback: R, call: impl FnOnce() -> R) -> R {
1193    std::panic::catch_unwind(std::panic::AssertUnwindSafe(call)).unwrap_or_else(|_| {
1194        crate::error!("a mod's callback panicked (see above); carrying on without it");
1195        fallback
1196    })
1197}
1198//
1199// Each trampoline is a `unsafe extern "C" fn` that:
1200//   1. Casts `ud` back to the original boxed closure.
1201//   2. Converts ABI C structs to Rust event types.
1202//   3. Builds a `CServer` from the `*const YogServer`.
1203//   4. Calls the closure.
1204//
1205// Closures are Box::into_raw'd in Registry methods — they are INTENTIONALLY
1206// leaked and live for the process lifetime.
1207
1208// ── Trampoline helpers ────────────────────────────────────────────────────────
1209//
1210// All phased event trampolines share the same pattern:
1211//   `phase: u8`  0 = EventPhase::Pre, 1 = EventPhase::Post
1212//   Return value is meaningful only in Pre phase.
1213
1214macro_rules! trampoline_phased {
1215    ($name:ident, $abi_ev:ty, $rust_ev:ty, |$ev:ident| $build:expr_2021) => {
1216        unsafe extern "C" fn $name<F>(
1217            ud: *mut c_void,
1218            srv: *const YogServer,
1219            ev: *const $abi_ev,
1220            phase: u8,
1221        ) -> bool
1222        where
1223            F: Fn(&$rust_ev, EventPhase, &dyn Server) -> bool + Send + Sync,
1224        {
1225            unsafe {
1226                let f = &*(ud as *const F);
1227                let $ev = &*ev;
1228                let rust_ev = $build;
1229                let p = if phase == 0 {
1230                    EventPhase::Pre
1231                } else {
1232                    EventPhase::Post
1233                };
1234                guard(true, || f(&rust_ev, p, &CServer(srv)))
1235            }
1236        }
1237    };
1238}
1239
1240trampoline_phased!(
1241    trampoline_block_break,
1242    YogBlockBreakEvent,
1243    BlockBreakEvent,
1244    |ev| BlockBreakEvent {
1245        player_name: ev.player.as_str().to_owned(),
1246        block_id: ev.block.as_str().to_owned(),
1247        pos: yog_core::BlockPos {
1248            x: ev.pos.x,
1249            y: ev.pos.y,
1250            z: ev.pos.z
1251        },
1252        dimension: ev.dimension.as_str().to_owned(),
1253    }
1254);
1255
1256trampoline_phased!(trampoline_chat, YogChatEvent, ChatEvent, |ev| ChatEvent {
1257    player_name: ev.player.as_str().to_owned(),
1258    message: ev.message.as_str().to_owned(),
1259    dimension: ev.dimension.as_str().to_owned(),
1260});
1261
1262trampoline_phased!(
1263    trampoline_player_join,
1264    YogPlayerEvent,
1265    PlayerJoinEvent,
1266    |ev| PlayerJoinEvent {
1267        player_name: ev.player.as_str().to_owned(),
1268        uuid: ev.uuid.as_str().to_owned(),
1269        dimension: ev.dimension.as_str().to_owned(),
1270    }
1271);
1272
1273trampoline_phased!(
1274    trampoline_player_leave,
1275    YogPlayerEvent,
1276    PlayerLeaveEvent,
1277    |ev| PlayerLeaveEvent {
1278        player_name: ev.player.as_str().to_owned(),
1279        uuid: ev.uuid.as_str().to_owned(),
1280        dimension: ev.dimension.as_str().to_owned(),
1281    }
1282);
1283
1284trampoline_phased!(trampoline_use_item, YogUseItemEvent, UseItemEvent, |ev| {
1285    UseItemEvent {
1286        player_name: ev.player.as_str().to_owned(),
1287        item_id: ev.item.as_str().to_owned(),
1288        sneaking: ev.sneaking,
1289        dimension: ev.dimension.as_str().to_owned(),
1290    }
1291});
1292
1293trampoline_phased!(
1294    trampoline_use_block,
1295    YogUseBlockEvent,
1296    UseBlockEvent,
1297    |ev| UseBlockEvent {
1298        player_name: ev.player.as_str().to_owned(),
1299        block_id: ev.block.as_str().to_owned(),
1300        pos: yog_core::BlockPos {
1301            x: ev.pos.x,
1302            y: ev.pos.y,
1303            z: ev.pos.z
1304        },
1305        dimension: ev.dimension.as_str().to_owned(),
1306    }
1307);
1308
1309trampoline_phased!(
1310    trampoline_attack_entity,
1311    YogAttackEntityEvent,
1312    AttackEntityEvent,
1313    |ev| AttackEntityEvent {
1314        player_name: ev.player.as_str().to_owned(),
1315        target_type: ev.target_type.as_str().to_owned(),
1316        target_uuid: ev.target_uuid.as_str().to_owned(),
1317        dimension: ev.dimension.as_str().to_owned(),
1318    }
1319);
1320
1321trampoline_phased!(
1322    trampoline_entity_damage,
1323    YogEntityDamageEvent,
1324    EntityDamageEvent,
1325    |ev| EntityDamageEvent {
1326        entity_type: ev.entity_type.as_str().to_owned(),
1327        uuid: ev.uuid.as_str().to_owned(),
1328        amount: ev.amount,
1329        source: ev.source.as_str().to_owned(),
1330        dimension: ev.dimension.as_str().to_owned(),
1331    }
1332);
1333
1334trampoline_phased!(
1335    trampoline_entity_death,
1336    YogEntityDeathEvent,
1337    EntityDeathEvent,
1338    |ev| EntityDeathEvent {
1339        entity_type: ev.entity_type.as_str().to_owned(),
1340        uuid: ev.uuid.as_str().to_owned(),
1341        source: ev.source.as_str().to_owned(),
1342        dimension: ev.dimension.as_str().to_owned(),
1343    }
1344);
1345
1346trampoline_phased!(
1347    trampoline_entity_spawn,
1348    YogEntitySpawnEvent,
1349    EntitySpawnEvent,
1350    |ev| EntitySpawnEvent {
1351        entity_type: ev.entity_type.as_str().to_owned(),
1352        uuid: ev.uuid.as_str().to_owned(),
1353        dimension: ev.dimension.as_str().to_owned(),
1354    }
1355);
1356
1357trampoline_phased!(
1358    trampoline_place_block,
1359    YogPlaceBlockEvent,
1360    PlaceBlockEvent,
1361    |ev| PlaceBlockEvent {
1362        player_name: ev.player.as_str().to_owned(),
1363        block_id: ev.block.as_str().to_owned(),
1364        pos: yog_core::BlockPos {
1365            x: ev.pos.x,
1366            y: ev.pos.y,
1367            z: ev.pos.z
1368        },
1369        dimension: ev.dimension.as_str().to_owned(),
1370    }
1371);
1372
1373trampoline_phased!(
1374    trampoline_player_death,
1375    YogPlayerDeathEvent,
1376    PlayerDeathEvent,
1377    |ev| PlayerDeathEvent {
1378        player_name: ev.player.as_str().to_owned(),
1379        uuid: ev.uuid.as_str().to_owned(),
1380        source: ev.source.as_str().to_owned(),
1381        dimension: ev.dimension.as_str().to_owned(),
1382    }
1383);
1384
1385trampoline_phased!(
1386    trampoline_player_respawn,
1387    YogPlayerRespawnEvent,
1388    PlayerRespawnEvent,
1389    |ev| PlayerRespawnEvent {
1390        player_name: ev.player.as_str().to_owned(),
1391        uuid: ev.uuid.as_str().to_owned(),
1392        at_anchor: ev.at_anchor,
1393        dimension: ev.dimension.as_str().to_owned(),
1394    }
1395);
1396
1397trampoline_phased!(
1398    trampoline_advancement,
1399    YogAdvancementEvent,
1400    AdvancementEvent,
1401    |ev| AdvancementEvent {
1402        player_name: ev.player.as_str().to_owned(),
1403        uuid: ev.uuid.as_str().to_owned(),
1404        advancement_id: ev.advancement.as_str().to_owned(),
1405        dimension: ev.dimension.as_str().to_owned(),
1406    }
1407);
1408
1409trampoline_phased!(
1410    trampoline_entity_interact,
1411    YogEntityInteractEvent,
1412    EntityInteractEvent,
1413    |ev| EntityInteractEvent {
1414        player_name: ev.player.as_str().to_owned(),
1415        player_uuid: ev.player_uuid.as_str().to_owned(),
1416        entity_type: ev.entity_type.as_str().to_owned(),
1417        entity_uuid: ev.entity_uuid.as_str().to_owned(),
1418        hand: ev.hand.as_str().to_owned(),
1419        dimension: ev.dimension.as_str().to_owned(),
1420    }
1421);
1422
1423trampoline_phased!(trampoline_craft, YogCraftEvent, CraftEvent, |ev| {
1424    CraftEvent {
1425        player_name: ev.player.as_str().to_owned(),
1426        player_uuid: ev.player_uuid.as_str().to_owned(),
1427        result_item: ev.result_item.as_str().to_owned(),
1428        result_count: ev.result_count,
1429        dimension: ev.dimension.as_str().to_owned(),
1430    }
1431});
1432
1433/// A machine — an inventory whose `.yui` has a `<RecipeArea kind="…">` —
1434/// making a recipe of its kind, like a crafting table: the result shows as
1435/// soon as its slots hold a recipe's ingredients, and taking it takes them.
1436///
1437/// - `Pre` — whether it may: `false` and the result doesn't show (a
1438///   workbench short of what the recipe's `values` cost). `player` is empty.
1439/// - `Post` — a player took the result; the host takes the ingredients, the mod
1440///   its share (the workbench's resources).
1441#[derive(Debug, Clone)]
1442pub struct MachineCraftEvent {
1443    /// The machine's inventory, e.g. `"mymod:press"`.
1444    pub machine: String,
1445    /// The recipe's kind (`"mymod:pressing"`) and id.
1446    pub kind: String,
1447    pub recipe: String,
1448    pub result_item: String,
1449    pub result_count: u32,
1450    /// The recipe's values: `{ "energy": 4 }`.
1451    pub values: yog_data::Value,
1452    pub pos: yog_core::BlockPos,
1453    pub dimension: String,
1454    pub player: String,
1455}
1456
1457trampoline_phased!(trampoline_machine_craft, YogMachineCraftEvent, MachineCraftEvent, |ev| {
1458    MachineCraftEvent {
1459        machine: ev.machine.as_str().to_owned(),
1460        kind: ev.kind.as_str().to_owned(),
1461        recipe: ev.recipe.as_str().to_owned(),
1462        result_item: ev.result_item.as_str().to_owned(),
1463        result_count: ev.result_count,
1464        values: yog_data::json::from_json_text(ev.values.as_str()).unwrap_or(yog_data::Value::Null),
1465        pos: yog_core::BlockPos { x: ev.pos.x, y: ev.pos.y, z: ev.pos.z },
1466        dimension: ev.dimension.as_str().to_owned(),
1467        player: ev.player.as_str().to_owned(),
1468    }
1469});
1470
1471trampoline_phased!(
1472    trampoline_explosion,
1473    YogExplosionEvent,
1474    ExplosionEvent,
1475    |ev| ExplosionEvent {
1476        dimension: ev.dimension.as_str().to_owned(),
1477        x: ev.x,
1478        y: ev.y,
1479        z: ev.z,
1480        power: ev.power,
1481        cause_uuid: ev.cause_uuid.as_str().to_owned(),
1482    }
1483);
1484
1485trampoline_phased!(
1486    trampoline_item_pickup,
1487    YogItemPickupEvent,
1488    ItemPickupEvent,
1489    |ev| ItemPickupEvent {
1490        player_name: ev.player.as_str().to_owned(),
1491        player_uuid: ev.player_uuid.as_str().to_owned(),
1492        item_id: ev.item_id.as_str().to_owned(),
1493        item_count: ev.item_count,
1494        entity_uuid: ev.entity_uuid.as_str().to_owned(),
1495        dimension: ev.dimension.as_str().to_owned(),
1496    }
1497);
1498
1499trampoline_phased!(
1500    trampoline_player_move,
1501    YogPlayerMoveEvent,
1502    PlayerMoveEvent,
1503    |ev| PlayerMoveEvent {
1504        player_name: ev.player.as_str().to_owned(),
1505        player_uuid: ev.player_uuid.as_str().to_owned(),
1506        x: ev.x,
1507        y: ev.y,
1508        z: ev.z,
1509        yaw: ev.yaw,
1510        pitch: ev.pitch,
1511        dimension: ev.dimension.as_str().to_owned(),
1512    }
1513);
1514
1515trampoline_phased!(
1516    trampoline_container_open,
1517    YogContainerOpenEvent,
1518    ContainerOpenEvent,
1519    |ev| ContainerOpenEvent {
1520        player_name: ev.player.as_str().to_owned(),
1521        player_uuid: ev.player_uuid.as_str().to_owned(),
1522        container_type: ev.container_type.as_str().to_owned(),
1523        dimension: ev.dimension.as_str().to_owned(),
1524    }
1525);
1526
1527trampoline_phased!(
1528    trampoline_container_close,
1529    YogContainerCloseEvent,
1530    ContainerCloseEvent,
1531    |ev| ContainerCloseEvent {
1532        player_name: ev.player.as_str().to_owned(),
1533        player_uuid: ev.player_uuid.as_str().to_owned(),
1534        dimension: ev.dimension.as_str().to_owned(),
1535    }
1536);
1537
1538trampoline_phased!(
1539    trampoline_projectile_hit,
1540    YogProjectileHitEvent,
1541    ProjectileHitEvent,
1542    |ev| ProjectileHitEvent {
1543        projectile_type: ev.projectile_type.as_str().to_owned(),
1544        projectile_uuid: ev.projectile_uuid.as_str().to_owned(),
1545        shooter_uuid: ev.shooter_uuid.as_str().to_owned(),
1546        hit_type: ev.hit_type.as_str().to_owned(),
1547        hit_entity_uuid: ev.hit_entity_uuid.as_str().to_owned(),
1548        x: ev.x,
1549        y: ev.y,
1550        z: ev.z,
1551        dimension: ev.dimension.as_str().to_owned(),
1552    }
1553);
1554
1555unsafe extern "C" fn trampoline_server_fn<F>(ud: *mut c_void, srv: *const YogServer)
1556where
1557    F: Fn(&dyn Server) + Send + Sync,
1558{
1559    unsafe {
1560        let f = &*(ud as *const F);
1561        guard((), || f(&CServer(srv)));
1562    }
1563}
1564
1565unsafe extern "C" fn trampoline_packet<F>(
1566    ud: *mut c_void,
1567    srv: *const YogServer,
1568    ev: *const YogPacketEvent,
1569) where
1570    F: Fn(&PacketEvent, &dyn Server) + Send + Sync,
1571{
1572    unsafe {
1573        let f = &*(ud as *const F);
1574        let ev = &*ev;
1575        let rust_ev = PacketEvent {
1576            channel: ev.channel.as_str().to_owned(),
1577            player: ev.player.as_str().to_owned(),
1578            // (A null pointer with no bytes is fine for C, not for a slice.)
1579            payload: if ev.payload.is_null() || ev.payload_len == 0 {
1580                Vec::new()
1581            } else {
1582                std::slice::from_raw_parts(ev.payload, ev.payload_len as usize).to_vec()
1583            },
1584        };
1585        guard((), || f(&rust_ev, &CServer(srv)));
1586    }
1587}
1588
1589unsafe extern "C" fn trampoline_command<F>(
1590    ud: *mut c_void,
1591    srv: *const YogServer,
1592    ev: *const YogCommandEvent,
1593    reply_buf: *mut u8,
1594    reply_cap: u32,
1595    reply_len: *mut u32,
1596) where
1597    F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync,
1598{
1599    unsafe {
1600        let f = &*(ud as *const F);
1601        let ev = &*ev;
1602        let ctx = CommandContext {
1603            name: ev.name.as_str().to_owned(),
1604            args: ev.args.as_str().to_owned(),
1605            source: ev.source.as_str().to_owned(),
1606            uuid: ev.uuid.as_str().to_owned(),
1607            dimension: ev.dimension.as_str().to_owned(),
1608        };
1609        *reply_len = 0;
1610        if let Some(reply) = guard(None, || f(&ctx, &CServer(srv))) {
1611            let bytes = reply.as_bytes();
1612            // As much as fits, cut between characters (it's read as UTF-8).
1613            let mut n = bytes.len().min(reply_cap as usize);
1614            while !reply.is_char_boundary(n) {
1615                n -= 1;
1616            }
1617            std::ptr::copy_nonoverlapping(bytes.as_ptr(), reply_buf, n);
1618            *reply_len = n as u32;
1619        }
1620    }
1621}
1622
1623unsafe extern "C" fn trampoline_scheduled<F>(ud: *mut c_void, srv: *const YogServer)
1624where
1625    F: Fn(&dyn Server) + Send + Sync,
1626{
1627    unsafe {
1628        let f = &*(ud as *const F);
1629        guard((), || f(&CServer(srv)));
1630    }
1631}
1632
1633// ── ABI minor 10 — client-side trampolines ────────────────────────────────────
1634
1635unsafe extern "C" fn trampoline_client_tick<F>(ud: *mut c_void)
1636where
1637    F: Fn(&ClientTickEvent) + Send + Sync,
1638{
1639    unsafe {
1640        let f = &*(ud as *const F);
1641        guard((), || f(&ClientTickEvent {}));
1642    }
1643}
1644
1645unsafe extern "C" fn trampoline_hud_render<F>(ud: *mut c_void, gfx: *const YogGfxApi)
1646where
1647    F: Fn(&GfxContext) + Send + Sync,
1648{
1649    unsafe {
1650        let f = &*(ud as *const F);
1651        guard((), || f(&GfxContext::from_raw(gfx)));
1652    }
1653}
1654
1655/// What `Registry::on_item_tooltip` keeps: the size and the draw closures.
1656struct TooltipPicture<S, D> {
1657    size: S,
1658    draw: D,
1659}
1660
1661unsafe extern "C" fn trampoline_tooltip_size<S, D>(ud: *mut c_void, item: YogStr, snbt: YogStr, w: *mut f32, h: *mut f32) -> bool
1662where
1663    S: Fn(&str, &str) -> Option<(f32, f32)> + Send + Sync,
1664{
1665    unsafe {
1666        let t = &*(ud as *const TooltipPicture<S, D>);
1667        match guard(None, || (t.size)(item.as_str(), snbt.as_str())) {
1668            Some((pw, ph)) => {
1669                (*w, *h) = (pw, ph);
1670                true
1671            }
1672            None => false,
1673        }
1674    }
1675}
1676
1677unsafe extern "C" fn trampoline_item_text<F>(ud: *mut c_void, item: YogStr, snbt: YogStr, sink: *mut c_void, write: yog_abi::YogTextSink) -> bool
1678where
1679    F: Fn(&str, &str) -> Option<(Option<String>, Vec<String>)> + Send + Sync,
1680{
1681    unsafe {
1682        let f = &*(ud as *const F);
1683        let Some((name, lines)) = guard(None, || f(item.as_str(), snbt.as_str())) else { return false };
1684        let mut text = name.unwrap_or_default();
1685        for l in lines {
1686            text.push('\n');
1687            text.push_str(&l.replace('\n', " "));
1688        }
1689        write(sink, YogStr::from_str(&text));
1690        true
1691    }
1692}
1693
1694#[allow(clippy::too_many_arguments)]
1695unsafe extern "C" fn trampoline_tooltip_draw<S, D>(ud: *mut c_void, gfx: *const YogGfxApi, item: YogStr, snbt: YogStr, x: f32, y: f32, w: f32, h: f32)
1696where
1697    D: Fn(&GfxContext, &str, &str, [f32; 4]) + Send + Sync,
1698{
1699    unsafe {
1700        let t = &*(ud as *const TooltipPicture<S, D>);
1701        guard((), || (t.draw)(&GfxContext::from_raw(gfx), item.as_str(), snbt.as_str(), [x, y, w, h]));
1702    }
1703}
1704
1705#[allow(clippy::too_many_arguments)]
1706unsafe extern "C" fn trampoline_book_page<F>(ud: *mut c_void, gfx: *const YogGfxApi, data: *const u8, len: usize, x: f32, y: f32, w: f32, h: f32)
1707where
1708    F: Fn(&GfxContext, &yog_data::Value, [f32; 4]) + Send + Sync,
1709{
1710    unsafe {
1711        let f = &*(ud as *const F);
1712        let bytes = if data.is_null() { &[][..] } else { std::slice::from_raw_parts(data, len) };
1713        let value = yog_data::binary::decode(bytes).unwrap_or(yog_data::Value::Null);
1714        guard((), || f(&GfxContext::from_raw(gfx), &value, [x, y, w, h]));
1715    }
1716}
1717
1718unsafe extern "C" fn trampoline_world_render<F>(ud: *mut c_void, gfx: *const YogGfxApi)
1719where
1720    F: Fn(&GfxContext) + Send + Sync,
1721{
1722    unsafe {
1723        let f = &*(ud as *const F);
1724        guard((), || f(&GfxContext::from_raw(gfx)));
1725    }
1726}
1727
1728unsafe extern "C" fn trampoline_key_press<F>(ud: *mut c_void, ev: *const YogKeyPressEvent) -> bool
1729where
1730    F: Fn(&KeyPressEvent) -> bool + Send + Sync,
1731{
1732    unsafe {
1733        let f = &*(ud as *const F);
1734        let e = &*ev;
1735        let ev = KeyPressEvent { key_code: e.key_code, scan_code: e.scan_code, action: e.action, modifiers: e.modifiers };
1736        guard(false, || f(&ev))
1737    }
1738}
1739
1740unsafe extern "C" fn trampoline_screen<F>(ud: *mut c_void, screen_class: YogStr) -> bool
1741where
1742    F: Fn(&ScreenEvent) + Send + Sync,
1743{
1744    unsafe {
1745        let f = &*(ud as *const F);
1746        let ev = ScreenEvent { screen_class: screen_class.as_str().to_owned() };
1747        guard((), || f(&ev));
1748        true
1749    }
1750}
1751
1752// ── Registry ─────────────────────────────────────────────────────────────────
1753
1754/// Wraps the [`YogApi`] table and provides an ergonomic registration API.
1755///
1756/// Obtained inside `yog_mod_register` via `export_mod!`.  Closures registered
1757/// here are boxed and leaked — they live as long as the process (which is the
1758/// correct lifetime for a server mod).
1759/// Pointer to the runtime's `YogApi` table (a process-lifetime static in the
1760/// runtime), captured when the mod registers. Lets free functions like
1761/// [`installed_mods`] work outside of `register()` — e.g. in UI handlers.
1762static GLOBAL_API: std::sync::atomic::AtomicPtr<YogApi> =
1763    std::sync::atomic::AtomicPtr::new(std::ptr::null_mut());
1764
1765/// The runtime's `YogApi` table, null before this mod registered.
1766pub(crate) fn global_api() -> *mut YogApi {
1767    GLOBAL_API.load(std::sync::atomic::Ordering::Acquire)
1768}
1769
1770/// Metadata of an installed mod, as reported by the loader.
1771#[derive(Debug, Clone)]
1772pub struct ModInfo {
1773    /// `"yog"` for .yog mods, `"platform"` for loader (Java) mods.
1774    pub source: String,
1775    pub id: String,
1776    pub name: String,
1777    pub version: String,
1778    /// Comma-separated author list (may be empty).
1779    pub authors: String,
1780    pub description: String,
1781}
1782
1783/// All installed mods known to the loader: .yog mods plus, where the host
1784/// exposes them, platform (Java) mods. Callable at any time after this mod's
1785/// `register()` ran — including client-side UI handlers. Note that during
1786/// `register()` mods that load after this one are not in the list yet; query
1787/// lazily (e.g. on first render) for a complete view.
1788pub fn installed_mods() -> Vec<ModInfo> {
1789    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1790    if api.is_null() {
1791        return Vec::new();
1792    }
1793    let owned = unsafe { ((*api).mods_list)((*api).ctx) };
1794    let Some(text) = take_owned(unsafe { (*api).free_str }, owned) else {
1795        return Vec::new();
1796    };
1797    text.lines()
1798        .filter_map(|line| {
1799            let mut f = line.split('\t');
1800            Some(ModInfo {
1801                source: f.next()?.to_string(),
1802                id: f.next()?.to_string(),
1803                name: f.next().unwrap_or_default().to_string(),
1804                version: f.next().unwrap_or_default().to_string(),
1805                authors: f.next().unwrap_or_default().to_string(),
1806                description: f.next().unwrap_or_default().to_string(),
1807            })
1808        })
1809        .collect()
1810}
1811
1812/// Open the Yog UI registered as `ui_id` (client side; no-op on dedicated
1813/// servers). `modal` blocks game input, `pause` pauses singleplayer. Callable
1814/// from any handler after registration — e.g. an `on_client_packet` handler.
1815pub fn open_ui(ui_id: &str, modal: bool, pause: bool) {
1816    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1817    if api.is_null() {
1818        return;
1819    }
1820    unsafe { ((*api).ui_open)((*api).ctx, YogStr::from_str(ui_id), modal, pause) }
1821}
1822
1823/// Close the Yog UI screen showing `ui_id` — e.g. from that screen's own
1824/// "Done" button. Does nothing when another screen is open. Deferred onto the
1825/// render thread, so the handler that calls it finishes first. Client side;
1826/// a no-op on dedicated servers.
1827pub fn close_ui(ui_id: &str) {
1828    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1829    if api.is_null() {
1830        return;
1831    }
1832    unsafe { ((*api).ui_close)((*api).ctx, YogStr::from_str(ui_id)) }
1833}
1834
1835/// What a [`Registry::register_ui`] handler returns: `()` (never marks
1836/// events as used) or `bool` (`true` = the handler used this `key:`/`char:`
1837/// event — the host then doesn't, e.g. Esc doesn't close the screen).
1838pub trait UiHandled {
1839    fn handled(self) -> bool;
1840}
1841
1842impl UiHandled for () {
1843    fn handled(self) -> bool {
1844        false
1845    }
1846}
1847
1848impl UiHandled for bool {
1849    fn handled(self) -> bool {
1850        self
1851    }
1852}
1853
1854/// Handle to the runtime's server-action table, usable from any handler after
1855/// registration — including client-side ones that don't receive `&dyn Server`
1856/// (UI event handlers, client tick). Server-world actions are no-ops client
1857/// side, but networking (`send_to_server`) and similar client-safe calls work.
1858pub fn server() -> Option<CServer> {
1859    let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
1860    if api.is_null() {
1861        return None;
1862    }
1863    let srv = unsafe { (*api).server };
1864    if srv.is_null() {
1865        return None;
1866    }
1867    Some(CServer(srv))
1868}
1869
1870pub struct Registry {
1871    api: *const YogApi,
1872}
1873
1874// SAFETY: `api` is a static provided by the runtime, valid for process lifetime.
1875unsafe impl Send for Registry {}
1876unsafe impl Sync for Registry {}
1877
1878impl Registry {
1879    /// Build from the pointer passed by the runtime. Only called by `export_mod!`.
1880    ///
1881    /// # Safety
1882    ///
1883    /// `api` must point to the runtime's `YogApi` table, valid for the rest of
1884    /// the process.
1885    pub unsafe fn from_raw(api: *const YogApi) -> Self {
1886        GLOBAL_API.store(api as *mut YogApi, std::sync::atomic::Ordering::Release);
1887        Self { api }
1888    }
1889
1890    #[inline]
1891    fn ctx(&self) -> *mut c_void {
1892        unsafe { (*self.api).ctx }
1893    }
1894
1895    // ── helpers ──────────────────────────────────────────────────────────────
1896
1897    fn leak<F: 'static>(f: F) -> *mut c_void {
1898        Box::into_raw(Box::new(f)) as *mut c_void
1899    }
1900
1901    // ── events ───────────────────────────────────────────────────────────────
1902    //
1903    // All handlers receive `(event, EventPhase, &dyn Server) -> bool`.
1904    // In `Pre` phase, returning `false` cancels the action.
1905    // In `Post` phase, the return value is ignored.
1906    // A single registration fires for BOTH phases.
1907
1908    pub fn on_block_break<F>(&mut self, handler: F)
1909    where
1910        F: Fn(&BlockBreakEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1911    {
1912        let ud = Self::leak(handler);
1913        unsafe { ((*self.api).on_block_break)(self.ctx(), ud, trampoline_block_break::<F>) }
1914    }
1915
1916    pub fn on_chat<F>(&mut self, handler: F)
1917    where
1918        F: Fn(&ChatEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1919    {
1920        let ud = Self::leak(handler);
1921        unsafe { ((*self.api).on_chat)(self.ctx(), ud, trampoline_chat::<F>) }
1922    }
1923
1924    pub fn on_player_join<F>(&mut self, handler: F)
1925    where
1926        F: Fn(&PlayerJoinEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1927    {
1928        let ud = Self::leak(handler);
1929        unsafe { ((*self.api).on_player_join)(self.ctx(), ud, trampoline_player_join::<F>) }
1930    }
1931
1932    pub fn on_player_leave<F>(&mut self, handler: F)
1933    where
1934        F: Fn(&PlayerLeaveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1935    {
1936        let ud = Self::leak(handler);
1937        unsafe { ((*self.api).on_player_leave)(self.ctx(), ud, trampoline_player_leave::<F>) }
1938    }
1939
1940    pub fn on_use_item<F>(&mut self, handler: F)
1941    where
1942        F: Fn(&UseItemEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1943    {
1944        let ud = Self::leak(handler);
1945        unsafe { ((*self.api).on_use_item)(self.ctx(), ud, trampoline_use_item::<F>) }
1946    }
1947
1948    pub fn on_use_block<F>(&mut self, handler: F)
1949    where
1950        F: Fn(&UseBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1951    {
1952        let ud = Self::leak(handler);
1953        unsafe { ((*self.api).on_use_block)(self.ctx(), ud, trampoline_use_block::<F>) }
1954    }
1955
1956    pub fn on_attack_entity<F>(&mut self, handler: F)
1957    where
1958        F: Fn(&AttackEntityEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1959    {
1960        let ud = Self::leak(handler);
1961        unsafe { ((*self.api).on_attack_entity)(self.ctx(), ud, trampoline_attack_entity::<F>) }
1962    }
1963
1964    pub fn on_entity_damage<F>(&mut self, handler: F)
1965    where
1966        F: Fn(&EntityDamageEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1967    {
1968        let ud = Self::leak(handler);
1969        unsafe { ((*self.api).on_entity_damage)(self.ctx(), ud, trampoline_entity_damage::<F>) }
1970    }
1971
1972    pub fn on_entity_death<F>(&mut self, handler: F)
1973    where
1974        F: Fn(&EntityDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1975    {
1976        let ud = Self::leak(handler);
1977        unsafe { ((*self.api).on_entity_death)(self.ctx(), ud, trampoline_entity_death::<F>) }
1978    }
1979
1980    pub fn on_entity_spawn<F>(&mut self, handler: F)
1981    where
1982        F: Fn(&EntitySpawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1983    {
1984        let ud = Self::leak(handler);
1985        unsafe { ((*self.api).on_entity_spawn)(self.ctx(), ud, trampoline_entity_spawn::<F>) }
1986    }
1987
1988    pub fn on_player_place_block<F>(&mut self, handler: F)
1989    where
1990        F: Fn(&PlaceBlockEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1991    {
1992        let ud = Self::leak(handler);
1993        unsafe { ((*self.api).on_player_place_block)(self.ctx(), ud, trampoline_place_block::<F>) }
1994    }
1995
1996    pub fn on_player_death<F>(&mut self, handler: F)
1997    where
1998        F: Fn(&PlayerDeathEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
1999    {
2000        let ud = Self::leak(handler);
2001        unsafe { ((*self.api).on_player_death)(self.ctx(), ud, trampoline_player_death::<F>) }
2002    }
2003
2004    pub fn on_player_respawn<F>(&mut self, handler: F)
2005    where
2006        F: Fn(&PlayerRespawnEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2007    {
2008        let ud = Self::leak(handler);
2009        unsafe { ((*self.api).on_player_respawn)(self.ctx(), ud, trampoline_player_respawn::<F>) }
2010    }
2011
2012    pub fn on_advancement<F>(&mut self, handler: F)
2013    where
2014        F: Fn(&AdvancementEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2015    {
2016        let ud = Self::leak(handler);
2017        unsafe { ((*self.api).on_advancement)(self.ctx(), ud, trampoline_advancement::<F>) }
2018    }
2019
2020    pub fn on_entity_interact<F>(&mut self, handler: F)
2021    where
2022        F: Fn(&EntityInteractEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2023    {
2024        let ud = Self::leak(handler);
2025        unsafe { ((*self.api).on_entity_interact)(self.ctx(), ud, trampoline_entity_interact::<F>) }
2026    }
2027
2028    pub fn on_item_craft<F>(&mut self, handler: F)
2029    where
2030        F: Fn(&CraftEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2031    {
2032        let ud = Self::leak(handler);
2033        unsafe { ((*self.api).on_item_craft)(self.ctx(), ud, trampoline_craft::<F>) }
2034    }
2035
2036    /// A machine making a recipe — see [`MachineCraftEvent`].
2037    pub fn on_machine_craft<F>(&mut self, handler: F)
2038    where
2039        F: Fn(&MachineCraftEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2040    {
2041        let ud = Self::leak(handler);
2042        unsafe { ((*self.api).on_machine_craft)(self.ctx(), ud, trampoline_machine_craft::<F>) }
2043    }
2044
2045    pub fn on_explosion<F>(&mut self, handler: F)
2046    where
2047        F: Fn(&ExplosionEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2048    {
2049        let ud = Self::leak(handler);
2050        unsafe { ((*self.api).on_explosion)(self.ctx(), ud, trampoline_explosion::<F>) }
2051    }
2052
2053    pub fn on_item_pickup<F>(&mut self, handler: F)
2054    where
2055        F: Fn(&ItemPickupEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2056    {
2057        let ud = Self::leak(handler);
2058        unsafe { ((*self.api).on_item_pickup)(self.ctx(), ud, trampoline_item_pickup::<F>) }
2059    }
2060
2061    pub fn on_player_move<F>(&mut self, handler: F)
2062    where
2063        F: Fn(&PlayerMoveEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2064    {
2065        let ud = Self::leak(handler);
2066        unsafe { ((*self.api).on_player_move)(self.ctx(), ud, trampoline_player_move::<F>) }
2067    }
2068
2069    pub fn on_container_open<F>(&mut self, handler: F)
2070    where
2071        F: Fn(&ContainerOpenEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2072    {
2073        let ud = Self::leak(handler);
2074        unsafe { ((*self.api).on_container_open)(self.ctx(), ud, trampoline_container_open::<F>) }
2075    }
2076
2077    pub fn on_container_close<F>(&mut self, handler: F)
2078    where
2079        F: Fn(&ContainerCloseEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2080    {
2081        let ud = Self::leak(handler);
2082        unsafe { ((*self.api).on_container_close)(self.ctx(), ud, trampoline_container_close::<F>) }
2083    }
2084
2085    pub fn on_projectile_hit<F>(&mut self, handler: F)
2086    where
2087        F: Fn(&ProjectileHitEvent, EventPhase, &dyn Server) -> bool + Send + Sync + 'static,
2088    {
2089        let ud = Self::leak(handler);
2090        unsafe { ((*self.api).on_projectile_hit)(self.ctx(), ud, trampoline_projectile_hit::<F>) }
2091    }
2092
2093    pub fn on_tick<F>(&mut self, listener: F)
2094    where
2095        F: Fn(&dyn Server) + Send + Sync + 'static,
2096    {
2097        let ud = Self::leak(listener);
2098        unsafe { ((*self.api).on_server_tick)(self.ctx(), ud, trampoline_server_fn::<F>) }
2099    }
2100
2101    pub fn on_server_started<F>(&mut self, listener: F)
2102    where
2103        F: Fn(&dyn Server) + Send + Sync + 'static,
2104    {
2105        let ud = Self::leak(listener);
2106        unsafe { ((*self.api).on_server_started)(self.ctx(), ud, trampoline_server_fn::<F>) }
2107    }
2108
2109    pub fn on_server_stopping<F>(&mut self, listener: F)
2110    where
2111        F: Fn(&dyn Server) + Send + Sync + 'static,
2112    {
2113        let ud = Self::leak(listener);
2114        unsafe { ((*self.api).on_server_stopping)(self.ctx(), ud, trampoline_server_fn::<F>) }
2115    }
2116
2117    // ── commands ─────────────────────────────────────────────────────────────
2118
2119    pub fn on_command<F>(&mut self, name: impl AsRef<str>, handler: F)
2120    where
2121        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
2122    {
2123        let name_ys = YogStr::from_str(name.as_ref());
2124        let ud = Self::leak(handler);
2125        unsafe { ((*self.api).register_command)(self.ctx(), name_ys, ud, trampoline_command::<F>) }
2126    }
2127
2128    /// Register a command with Brigadier-typed arguments.
2129    ///
2130    /// `schema` is a space-separated list of argument types:
2131    /// `int`, `float`, `word`, `string` (greedy, must be last), `player`, `blockpos`.
2132    ///
2133    /// In the handler use `ctx.arg_int(0)`, `ctx.arg_blockpos(1)`, etc.
2134    pub fn on_typed_command<F>(
2135        &mut self,
2136        name: impl AsRef<str>,
2137        schema: impl AsRef<str>,
2138        handler: F,
2139    ) where
2140        F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync + 'static,
2141    {
2142        let name_ys = YogStr::from_str(name.as_ref());
2143        let schema_ys = YogStr::from_str(schema.as_ref());
2144        let ud = Self::leak(handler);
2145        unsafe {
2146            ((*self.api).register_typed_command)(
2147                self.ctx(),
2148                name_ys,
2149                schema_ys,
2150                ud,
2151                trampoline_command::<F>,
2152            );
2153        }
2154    }
2155
2156    // ── networking ───────────────────────────────────────────────────────────
2157
2158    pub fn on_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
2159    where
2160        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
2161    {
2162        let ch = YogStr::from_str(channel.as_ref());
2163        let ud = Self::leak(handler);
2164        unsafe { ((*self.api).on_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
2165    }
2166
2167    pub fn on_client_packet<F>(&mut self, channel: impl AsRef<str>, handler: F)
2168    where
2169        F: Fn(&PacketEvent, &dyn Server) + Send + Sync + 'static,
2170    {
2171        let ch = YogStr::from_str(channel.as_ref());
2172        let ud = Self::leak(handler);
2173        unsafe { ((*self.api).on_client_packet)(self.ctx(), ch, ud, trampoline_packet::<F>) }
2174    }
2175
2176    /// Register a typed-packet handler.
2177    ///
2178    /// The payload is decoded from raw bytes using `P`'s [`Packet`] impl.
2179    /// Malformed payloads are silently dropped.
2180    pub fn on_typed_packet<P, F>(&mut self, channel: impl AsRef<str>, handler: F)
2181    where
2182        P: Packet + Send + Sync + 'static,
2183        F: Fn(&P, &dyn Server) + Send + Sync + 'static,
2184    {
2185        self.on_packet(channel, move |ev, srv| {
2186            if let Some(pkt) = P::decode(&ev.payload) {
2187                handler(&pkt, srv);
2188            }
2189        });
2190    }
2191
2192    // ── content ──────────────────────────────────────────────────────────────
2193
2194    /// Hands the runtime content of `kind` named `id`: its definition as a
2195    /// Yog Data blob (`register_content`, one ABI call for every kind).
2196    fn content(&mut self, kind: &str, id: &str, def: &yog_data::Value) {
2197        let blob = yog_data::binary::encode(def);
2198        unsafe { ((*self.api).register_content)(self.ctx(), YogStr::from_str(kind), YogStr::from_str(id), blob.as_ptr(), blob.len()) }
2199    }
2200
2201    /// JSON text as Yog Data (recipes and books are written as JSON by their crates).
2202    fn json(text: &str) -> yog_data::Value {
2203        yog_data::json::from_json_text(text).unwrap_or_default()
2204    }
2205
2206    /// Register a recipe (Yog's format — see [`Recipe`]; the host writes
2207    /// its Minecraft version's JSON).
2208    pub fn add_recipe(&mut self, recipe: Recipe) {
2209        let (ns, name) = recipe.ns_name();
2210        let id = format!("{ns}:{name}");
2211        self.content("recipe", &id, &recipe.to_data());
2212    }
2213
2214    /// Register a recipe given as Yog's recipe JSON — how `yog build`
2215    /// registers the mod's own kinds (`{"type": "mymod:infusion", "slots":
2216    /// …}`), which stay the mod's data: for its machines and its books.
2217    pub fn add_recipe_json(&mut self, id: &str, json: &str) {
2218        let id = if id.contains(':') { id.to_string() } else { format!("minecraft:{id}") };
2219        self.content("recipe", &id, &Self::json(json));
2220    }
2221
2222    pub fn register_item(&mut self, def: ItemDef) {
2223        use yog_data::Schema;
2224        self.content("item", &def.id.clone(), &def.write());
2225    }
2226
2227    pub fn register_block(&mut self, def: BlockDef) {
2228        use yog_data::Schema;
2229        self.content("block", &def.id.clone(), &def.write());
2230    }
2231
2232    /// Add placed feature `feature` (the mod's datapack's, like an ore's
2233    /// `mymod:mythril_ore`) to the biomes of tag `biomes` at generation
2234    /// `step` (`underground_ores`). An ore `.ydef` does this for you.
2235    pub fn add_biome_feature(&mut self, feature: &str, biomes: &str, step: &str) {
2236        use yog_data::Schema;
2237        let f = yog_registry::BiomeFeature { feature: feature.into(), biomes: biomes.into(), step: step.into() };
2238        self.content("biome_feature", feature, &f.write());
2239    }
2240
2241    /// Register a tool material — what tool items naming it
2242    /// (`ItemDef::tool`) are made of. The game's are built in.
2243    pub fn register_tool_material(&mut self, material: ToolMaterial) {
2244        use yog_data::Schema;
2245        self.content("tool_material", &material.id.clone(), &material.write());
2246    }
2247
2248    /// Register an armor material — what armor items naming it
2249    /// (`ItemDef::armor`) are made of. The game's are built in.
2250    pub fn register_armor_material(&mut self, material: ArmorMaterial) {
2251        use yog_data::Schema;
2252        self.content("armor_material", &material.id.clone(), &material.write());
2253    }
2254
2255    /// Register a sound group — what blocks naming it (`BlockDef::sound`)
2256    /// sound like. The game's groups are built in.
2257    pub fn register_sound_group(&mut self, group: SoundGroup) {
2258        use yog_data::Schema;
2259        self.content("sound_group", &group.id.clone(), &group.write());
2260    }
2261
2262    /// Register a real Container/Menu inventory screen — see
2263    /// `yog_inventory::InventoryDef`. Attach it to a block via
2264    /// `BlockDef::inventory(id)`.
2265    pub fn register_inventory(&mut self, def: yog_inventory::InventoryDef) {
2266        use yog_data::Schema;
2267        self.content("inventory", &def.id.clone(), &def.write());
2268    }
2269
2270    // ── startup grants ───────────────────────────────────────────────────────
2271
2272    /// Register a startup grant: items/books to give once when a player first joins.
2273    pub fn register_startup_grant(&mut self, grant: StartupGrant) {
2274        use yog_data::Schema;
2275        self.content("startup_grant", &grant.id.clone(), &grant.write());
2276    }
2277
2278    /// Register a book.
2279    pub fn register_book(&mut self, book: &Book) {
2280        use yog_data::Schema;
2281        self.content("book", &book.id, &book.write());
2282    }
2283
2284    /// Register a book given as Yog Data, binary — what `yog build` makes
2285    /// of a `content/**/*.ybook`; the bytes go to the runtime as they are.
2286    pub fn register_book_data(&mut self, id: &str, data: &[u8]) {
2287        unsafe { ((*self.api).register_content)(self.ctx(), YogStr::from_str("book"), YogStr::from_str(id), data.as_ptr(), data.len()) }
2288    }
2289
2290    /// Register (or patch) a dimension's *type* (sky, lighting, physics, ...).
2291    ///
2292    /// `def.id` need not be a new custom id — pass a vanilla id
2293    /// (`"minecraft:overworld"`, `"minecraft:the_nether"`,
2294    /// `"minecraft:the_end"`) to patch that dimension's type/generator
2295    /// instead of creating a new one (e.g. to replace the overworld's
2296    /// terrain with your own generator type).
2297    ///
2298    /// Must be called from `register()` — the same mod-init window as
2299    /// blocks/items — so the host can declare/patch the dimension before
2300    /// Minecraft's registries freeze. See the `yog-dimensions` crate docs;
2301    /// set `def.generator_type` (via [`YogDimensionDef::generator_type`]) to
2302    /// pick a generator type registered with
2303    /// [`Registry::register_chunk_generator`].
2304    pub fn register_dimension(&mut self, def: &YogDimensionDef) {
2305        let value = Self::json(&def.to_json());
2306        self.content("dimension", &def.id.clone(), &value);
2307    }
2308
2309    /// Register a dimension given as Yog Data, binary — what `yog build`
2310    /// makes of a `.ydef` of kind `dimension` (its `terrain` generated by
2311    /// the runtime itself); the bytes go to the runtime as they are.
2312    pub fn register_dimension_data(&mut self, id: &str, data: &[u8]) {
2313        unsafe { ((*self.api).register_content)(self.ctx(), YogStr::from_str("dimension"), YogStr::from_str(id), data.as_ptr(), data.len()) }
2314    }
2315
2316    /// Register a named, reusable chunk-generator type under
2317    /// `generator_type_id` (e.g. `"mymod:custom_terrain"`) — analogous to
2318    /// how Biomes O'Plenty registers selectable world-type presets. Any
2319    /// dimension (custom or vanilla) can opt into this generator via
2320    /// [`YogDimensionDef::generator_type`]; the platform host may also list
2321    /// registered generator type ids as options on the world-creation screen.
2322    ///
2323    /// `generator` is called once per chunk column that needs generating in
2324    /// any dimension using this type — write whatever terrain logic you want
2325    /// using the [`ChunkWriter`] handle (combine as many noise layers as you
2326    /// like; this crate doesn't prescribe a generation style).
2327    pub fn register_chunk_generator<F>(&mut self, generator_type_id: &str, generator: F)
2328    where
2329        F: Fn(&ChunkWriter) + Send + Sync + 'static,
2330    {
2331        let ud = Self::leak(generator);
2332        let id = YogStr::from_str(generator_type_id);
2333        unsafe {
2334            ((*self.api).register_chunk_generator)(
2335                self.ctx(),
2336                id,
2337                ud,
2338                trampoline_chunk_generator::<F>,
2339            );
2340        }
2341    }
2342
2343    /// Register a menu entry — the host renders a button on vanilla screens
2344    /// (TitleScreen on Fabric, ModListScreen on Forge/NeoForge) that opens `ui_id`.
2345    /// `label` is the human-readable button text (e.g. "Yog Mods").
2346    /// `ui_id` is the UI to open when clicked (e.g. "example:menu").
2347    /// See [`installed_mods`]. During `register()` the list only contains
2348    /// mods loaded before this one.
2349    pub fn installed_mods(&self) -> Vec<ModInfo> {
2350        installed_mods()
2351    }
2352
2353    /// Access the inter-mod communication layer.
2354    ///
2355    /// Allows exporting function pointers from this mod and importing
2356    /// function pointers from other mods.
2357    pub fn interop(&self) -> crate::Interop {
2358        crate::Interop::new(self.api)
2359    }
2360
2361    /// Raw `YogApi` pointer — for passing to interop-imported functions
2362    /// that register content through the C ABI table directly.
2363    pub fn raw_api(&self) -> *const yog_abi::YogApi {
2364        self.api
2365    }
2366
2367    pub fn register_menu_entry(&mut self, label: &str, ui_id: &str) {
2368        let l = YogStr::from_str(label);
2369        let u = YogStr::from_str(ui_id);
2370        unsafe { ((*self.api).register_menu_entry)(self.ctx(), l, u) }
2371    }
2372
2373    /// Register a UI tree with an event callback.
2374    /// `ui_id` is the unique identifier (e.g. "mymod:menu").
2375    /// `handler` receives `(ui_id, event)` for the screen's input: `click:X:Y`,
2376    /// `drag:X:Y`, `release:X:Y`, `scroll:DY`, `key:KEY:MODS` (GLFW key code
2377    /// and modifier bits, on press and repeat) and `char:CODEPOINT` (a typed
2378    /// character). It returns `()` or a `bool`: `true` marks a `key:`/`char:`
2379    /// event as used, so the host skips its default handling of the key
2380    /// (Esc closing the screen, ...) — see [`UiHandled`].
2381    pub fn register_ui<F, R>(&mut self, ui_id: &str, handler: F)
2382    where
2383        F: Fn(&str, &str) -> R + Send + Sync + 'static,
2384        R: UiHandled,
2385    {
2386        let ud = Self::leak(handler);
2387        let id = YogStr::from_str(ui_id);
2388        let empty = YogStr::from_str("{}");
2389        unsafe { ((*self.api).register_ui)(self.ctx(), id, empty, ud, trampoline_ui_event::<F, R>) }
2390    }
2391
2392    // ── scheduler ────────────────────────────────────────────────────────────
2393
2394    pub fn schedule_once<F>(&self, delay_ticks: u64, handler: F)
2395    where
2396        F: Fn(&dyn Server) + Send + Sync + 'static,
2397    {
2398        let ud = Self::leak(handler);
2399        unsafe {
2400            ((*self.api).schedule_once)(self.ctx(), delay_ticks, ud, trampoline_scheduled::<F>);
2401        }
2402    }
2403
2404    pub fn schedule_repeating<F>(&self, period_ticks: u64, handler: F)
2405    where
2406        F: Fn(&dyn Server) + Send + Sync + 'static,
2407    {
2408        let ud = Self::leak(handler);
2409        unsafe {
2410            ((*self.api).schedule_repeating)(
2411                self.ctx(),
2412                period_ticks,
2413                ud,
2414                trampoline_scheduled::<F>,
2415            );
2416        }
2417    }
2418
2419    // ── client-side hooks (ABI minor 10) ─────────────────────────────────────
2420
2421    /// Register a handler called every client tick (render thread, no server).
2422    pub fn on_client_tick<F>(&mut self, handler: F)
2423    where
2424        F: Fn(&ClientTickEvent) + Send + Sync + 'static,
2425    {
2426        let ud = Self::leak(handler);
2427        unsafe { ((*self.api).on_client_tick)(self.ctx(), ud, trampoline_client_tick::<F>) }
2428    }
2429
2430    /// Register a render callback for a specific UI screen (`ui_id`).
2431    ///
2432    /// Called from `YogUIScreen.render()` — i.e. AFTER `renderBackground()` darkens
2433    /// the screen — so your UI draws on top of the dimmed world view.
2434    /// Use this instead of `on_hud_render` for book/inventory screens.
2435    ///
2436    /// Clicks are forwarded as `"click:X:Y"` via the `register_ui` handler so you
2437    /// can do hit-testing on your own stored layout.
2438    pub fn on_ui_render<F>(&mut self, ui_id: &str, handler: F)
2439    where
2440        F: Fn(&GfxContext) + Send + Sync + 'static,
2441    {
2442        let ud = Self::leak(handler);
2443        let id = YogStr::from_str(ui_id);
2444        unsafe { ((*self.api).on_ui_render)(self.ctx(), id, ud, trampoline_hud_render::<F>) }
2445    }
2446
2447    /// Draw the pictures of book pages of type `drawn` whose `drawer` is
2448    /// `drawer` (`"mymod:diagram"`): `handler` gets the page's `data` and
2449    /// the picture's box `[x, y, w, h]` in screen pixels, every frame the
2450    /// page is open.
2451    ///
2452    /// ```text
2453    /// { type: "drawn", drawer: "mymod:diagram", title: "Wiring", height: 64,
2454    ///   caption: "{u|in} → {u|out}", text: "…", data: { nodes: 3 } }
2455    /// ```
2456    pub fn on_book_page<F>(&mut self, drawer: &str, handler: F)
2457    where
2458        F: Fn(&GfxContext, &yog_data::Value, [f32; 4]) + Send + Sync + 'static,
2459    {
2460        let ud = Self::leak(handler);
2461        let id = YogStr::from_str(drawer);
2462        unsafe { ((*self.api).on_book_page)(self.ctx(), id, ud, trampoline_book_page::<F>) }
2463    }
2464
2465    /// A picture under the tooltips of `item` (as Hex Casting's scrolls show
2466    /// their pattern): `size(item, snbt)` says whether a stack — its custom
2467    /// data as SNBT — gets one and its size in GUI pixels; `draw` draws it
2468    /// in the box `[x, y, w, h]` (screen pixels) while the tooltip shows.
2469    pub fn on_item_tooltip<S, D>(&mut self, item: &str, size: S, draw: D)
2470    where
2471        S: Fn(&str, &str) -> Option<(f32, f32)> + Send + Sync + 'static,
2472        D: Fn(&GfxContext, &str, &str, [f32; 4]) + Send + Sync + 'static,
2473    {
2474        let ud = Self::leak(TooltipPicture { size, draw });
2475        let id = YogStr::from_str(item);
2476        unsafe {
2477            ((*self.api).on_item_tooltip)(self.ctx(), id, ud, trampoline_tooltip_size::<S, D>, trampoline_tooltip_draw::<S, D>)
2478        }
2479    }
2480
2481    /// A stack's own name and tooltip, from its custom data (SNBT): `text(item,
2482    /// snbt)` gives `Some((name, lines))` — `name` `None` keeps the item's;
2483    /// `lines` stand instead of the item's description — or `None` for the
2484    /// item's own. A written blueprint names its design:
2485    ///
2486    /// ```ignore
2487    /// registry.on_item_text(Items::BLUEPRINT, |_, snbt| {
2488    ///     let bp = Blueprint::from_nbt(snbt)?;
2489    ///     Some((Some(bp.name.clone()), vec![format!("{} ports", bp.ports)]))
2490    /// });
2491    /// ```
2492    pub fn on_item_text<F>(&mut self, item: &str, text: F)
2493    where
2494        F: Fn(&str, &str) -> Option<(Option<String>, Vec<String>)> + Send + Sync + 'static,
2495    {
2496        let ud = Self::leak(text);
2497        let id = YogStr::from_str(item);
2498        unsafe { ((*self.api).on_item_text)(self.ctx(), id, ud, trampoline_item_text::<F>) }
2499    }
2500
2501    /// Register a handler called every frame when the HUD is rendered.
2502    ///
2503    /// `gfx` provides full GPU pipeline access plus 2D convenience draw calls.
2504    /// `view_proj` and `camera_pos` are zero in HUD context; use `gfx.draw2d()` for HUD elements.
2505    pub fn on_hud_render<F>(&mut self, handler: F)
2506    where
2507        F: Fn(&GfxContext) + Send + Sync + 'static,
2508    {
2509        let ud = Self::leak(handler);
2510        unsafe { ((*self.api).on_hud_render)(self.ctx(), ud, trampoline_hud_render::<F>) }
2511    }
2512
2513    /// Register a handler called every frame at the end of world rendering.
2514    ///
2515    /// `gfx.view_proj()` is the combined projection × view matrix (camera-relative).
2516    /// `gfx.camera_pos()` is the camera world position.
2517    /// To render at world position P, translate by `P - camera_pos` before drawing.
2518    pub fn on_world_render<F>(&mut self, handler: F)
2519    where
2520        F: Fn(&GfxContext) + Send + Sync + 'static,
2521    {
2522        let ud = Self::leak(handler);
2523        unsafe { ((*self.api).on_world_render)(self.ctx(), ud, trampoline_world_render::<F>) }
2524    }
2525
2526    /// Register a handler for keyboard input (client-side).
2527    /// Return `false` to prevent Minecraft from processing the key.
2528    pub fn on_key_press<F>(&mut self, handler: F)
2529    where
2530        F: Fn(&KeyPressEvent) -> bool + Send + Sync + 'static,
2531    {
2532        let ud = Self::leak(handler);
2533        unsafe { ((*self.api).on_key_press)(self.ctx(), ud, trampoline_key_press::<F>) }
2534    }
2535
2536    /// Register a handler called when a GUI screen is opened.
2537    pub fn on_screen_open<F>(&mut self, handler: F)
2538    where
2539        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2540    {
2541        let ud = Self::leak(handler);
2542        unsafe { ((*self.api).on_screen_open)(self.ctx(), ud, trampoline_screen::<F>) }
2543    }
2544
2545    /// Register a handler called when a GUI screen is closed.
2546    pub fn on_screen_close<F>(&mut self, handler: F)
2547    where
2548        F: Fn(&ScreenEvent) + Send + Sync + 'static,
2549    {
2550        let ud = Self::leak(handler);
2551        unsafe { ((*self.api).on_screen_close)(self.ctx(), ud, trampoline_screen::<F>) }
2552    }
2553}
2554
2555unsafe extern "C" fn trampoline_ui_event<F, R>(
2556    ud: *mut c_void,
2557    ui_id: yog_abi::YogStr,
2558    event_id: yog_abi::YogStr,
2559) where
2560    F: Fn(&str, &str) -> R + Send + Sync + 'static,
2561    R: UiHandled,
2562{
2563    let f = unsafe { &*(ud as *const F) };
2564    let ui = unsafe { ui_id.as_str() };
2565    let ev = unsafe { event_id.as_str() };
2566    if guard(false, || f(ui, ev).handled()) {
2567        let api = GLOBAL_API.load(std::sync::atomic::Ordering::Acquire);
2568        if !api.is_null() {
2569            unsafe { ((*api).ui_consume_event)((*api).ctx) }
2570        }
2571    }
2572}
2573
2574unsafe extern "C" fn trampoline_chunk_generator<F>(
2575    ud: *mut c_void,
2576    writer: *const yog_abi::YogChunkWriterApi,
2577) where
2578    F: Fn(&ChunkWriter) + Send + Sync + 'static,
2579{
2580    let f = unsafe { &*(ud as *const F) };
2581    let writer = unsafe { ChunkWriter::from_raw(writer) };
2582    guard((), || f(&writer));
2583}
2584
2585// ── Mod trait ─────────────────────────────────────────────────────────────────
2586
2587/// Implemented by every Yog mod. Called once at startup to register handlers.
2588pub trait Mod {
2589    fn register(registry: &mut Registry);
2590}
2591
2592#[cfg(test)]
2593mod trampoline_tests {
2594    use super::*;
2595    use yog_abi::{YogBlockPos, YogChatEvent, YogCommandEvent, YogPacketEvent};
2596
2597    fn ud<F>(f: &F) -> *mut c_void {
2598        f as *const F as *mut c_void
2599    }
2600
2601    fn chat<F: Fn(&ChatEvent, EventPhase, &dyn Server) -> bool + Send + Sync>(f: &F, ev: &YogChatEvent, phase: u8) -> bool {
2602        unsafe { trampoline_chat::<F>(ud(f), std::ptr::null(), ev, phase) }
2603    }
2604
2605    fn block_break<F: Fn(&BlockBreakEvent, EventPhase, &dyn Server) -> bool + Send + Sync>(f: &F, ev: &YogBlockBreakEvent) -> bool {
2606        unsafe { trampoline_block_break::<F>(ud(f), std::ptr::null(), ev, 0) }
2607    }
2608
2609    fn command<F: Fn(&CommandContext, &dyn Server) -> Option<String> + Send + Sync>(f: &F, ev: &YogCommandEvent, buf: &mut [u8]) -> u32 {
2610        let mut len = 99u32;
2611        unsafe { trampoline_command::<F>(ud(f), std::ptr::null(), ev, buf.as_mut_ptr(), buf.len() as u32, &mut len) };
2612        len
2613    }
2614
2615    fn packet<F: Fn(&PacketEvent, &dyn Server) + Send + Sync>(f: &F, ev: &YogPacketEvent) {
2616        unsafe { trampoline_packet::<F>(ud(f), std::ptr::null(), ev) }
2617    }
2618
2619    #[test]
2620    fn events_arrive_converted_with_their_phase() {
2621        let seen = std::sync::Mutex::new(Vec::new());
2622        let handler = |ev: &ChatEvent, p: EventPhase, _: &dyn Server| {
2623            seen.lock().unwrap().push((ev.player_name.clone(), ev.message.clone(), p));
2624            ev.message != "cancel me"
2625        };
2626        let ev = |msg: &'static str| YogChatEvent {
2627            player: YogStr::from_str("Dev"),
2628            message: YogStr::from_str(msg),
2629            dimension: YogStr::from_str("minecraft:overworld"),
2630        };
2631        assert!(chat(&handler, &ev("hi"), 0));
2632        assert!(!chat(&handler, &ev("cancel me"), 0));
2633        chat(&handler, &ev("after"), 1);
2634        let seen = seen.into_inner().unwrap();
2635        assert_eq!(seen[0], ("Dev".into(), "hi".into(), EventPhase::Pre));
2636        assert_eq!(seen[2].2, EventPhase::Post);
2637    }
2638
2639    #[test]
2640    fn a_panicking_handler_allows_the_action() {
2641        let handler = |_: &BlockBreakEvent, _: EventPhase, _: &dyn Server| -> bool { panic!("mod bug") };
2642        let ev = YogBlockBreakEvent {
2643            player: YogStr::from_str("Dev"),
2644            block: YogStr::from_str("minecraft:stone"),
2645            pos: YogBlockPos { x: 1, y: 2, z: 3 },
2646            dimension: YogStr::from_str("minecraft:overworld"),
2647        };
2648        assert!(block_break(&handler, &ev));
2649    }
2650
2651    #[test]
2652    fn command_replies_fit_the_buffer_whole_characters_only() {
2653        let handler = |c: &CommandContext, _: &dyn Server| Some(format!("{}: привет", c.args));
2654        let ev = YogCommandEvent {
2655            name: YogStr::from_str("hex"),
2656            args: YogStr::from_str("x"),
2657            source: YogStr::from_str("Dev"),
2658            uuid: YogStr::EMPTY,
2659            dimension: YogStr::EMPTY,
2660        };
2661        let mut buf = [0u8; 6];
2662        let len = command(&handler, &ev, &mut buf);
2663        // "x: п" is 5 bytes; "пр" wouldn't fit whole in 6.
2664        assert_eq!(std::str::from_utf8(&buf[..len as usize]), Ok("x: п"));
2665    }
2666
2667    #[test]
2668    fn empty_packets_need_no_payload_pointer() {
2669        let got = std::sync::Mutex::new(None);
2670        let handler = |p: &PacketEvent, _: &dyn Server| *got.lock().unwrap() = Some(p.payload.len());
2671        let ev = YogPacketEvent {
2672            channel: YogStr::from_str("mymod:ping"),
2673            player: YogStr::from_str("Dev"),
2674            payload: std::ptr::null(),
2675            payload_len: 0,
2676        };
2677        packet(&handler, &ev);
2678        assert_eq!(*got.lock().unwrap(), Some(0));
2679    }
2680}