Skip to main content

yog_api/
registry.rs

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