Skip to main content

yog_runtime/
lib.rs

1//! Yog runtime — the native library loaded by the Fabric host.
2//!
3//! Exposes JNI entry points (`Java_dev_yog_NativeBridge_*`) that the host calls,
4//! and a stable C ABI (`YogApi` / `YogServer`) that mods program against.
5//!
6//! Architecture:
7//!   - `YogServer`  — a `#[repr(C)]` table of standalone JNI-calling functions
8//!     that mods call to mutate the world.
9//!   - `YogApi`     — a `#[repr(C)]` table of registration functions; mods call
10//!     them inside `yog_mod_register` to subscribe to events.
11//!   - `RuntimeHandlers` — the runtime's internal event/handler storage.
12//!     Filled during `nativeInit` (write), read-only after. The scheduler sub-
13//!     state uses an inner `Mutex` for safe addition during event dispatch.
14
15use std::collections::HashMap;
16use std::num::NonZeroU32;
17use std::os::raw::c_void;
18use std::path::{Path, PathBuf};
19use std::sync::{Arc, Mutex, OnceLock, RwLock};
20
21use glow::HasContext;
22use jcall::JArg;
23use jni::objects::{JByteArray, JClass, JFloatArray, JString};
24use jni::sys::{jdouble, jfloat, jint, jstring};
25use jni::{JNIEnv, JavaVM};
26use libloading::Symbol;
27use yog_hot_reload::{HotReloader, LoadedModule, ModuleGeneration, ModuleRegistry};
28
29use yog_abi::{
30    ABI_VERSION, YogAdvancementEvent, YogAdvancementFn, YogApi, YogAttackEntityFn, YogBlockBreakFn,
31    YogBlockPos, YogChatFn, YogClientFn, YogCommandFn, YogContainerCloseEvent,
32    YogContainerCloseFn, YogContainerOpenEvent, YogContainerOpenFn, YogCraftEvent, YogCraftFn,
33    YogEntityDamageFn, YogEntityDeathFn, YogEntityInteractEvent, YogEntityInteractFn,
34    YogEntitySpawnFn, YogExplosionEvent, YogExplosionFn, YogGfxApi, YogHudRenderFn, YogItemInsertEvent, YogItemInsertFn, YogItemPickupEvent, YogItemPickupFn, YogKeyPressEvent, YogMachineCraftEvent, YogMachineCraftFn, YogKeyPressFn, YogOwnedStr, YogPacketFn,
35    YogPlaceBlockEvent, YogPlaceBlockFn, YogPlayerDeathEvent, YogPlayerDeathFn, YogPlayerFn,
36    YogPlayerMoveEvent, YogPlayerMoveFn, YogPlayerRespawnEvent, YogPlayerRespawnFn,
37    YogProjectileHitEvent, YogProjectileHitFn, YogScheduledFn, YogScreenFn, YogServer, YogServerFn,
38    YogStr, YogUseBlockFn, YogUseItemFn, YogVec3, YogWorldRenderFn,
39};
40use yog_registry::{BlockDef, ItemDef};
41
42// ── Static globals ────────────────────────────────────────────────────────────
43
44/// Cached JVM handle for any-thread callbacks.
45static JAVA_VM: OnceLock<JavaVM> = OnceLock::new();
46/// Loaded mod libraries, keyed by mod id — owns the safe `dlopen`/`dlclose`
47/// swap lifecycle (see `yog-hot-reload`) instead of a flat keep-alive `Vec`,
48/// so a reload can find "the current generation of this mod" and safely
49/// retire the previous one.
50static HOT_RELOADER: OnceLock<HotReloader<RuntimeModuleRegistry>> = OnceLock::new();
51/// The mod currently inside its own `yog_mod_register` call. Every `api_*`
52/// registration function reads this to tag what it stores with a
53/// `LoadedModule` handle, instead of requiring mods to pass a mod id
54/// through the stable C ABI (an ABI break, and edits to every mod's
55/// source). Valid because a mod's entire registration always happens
56/// synchronously inside one `yog_mod_register` call — see `load_mod_lib`
57/// and, in dev builds, `trigger_hot_reload`.
58static CURRENT_REGISTRATION: Mutex<Option<LoadedModule>> = Mutex::new(None);
59/// Metadata of loaded .yog mods: [id, name, version, authors, description,
60/// name_key, description_key] (the keys empty unless the mod's yog.toml
61/// gives its name/description as `.yres` texts).
62static MOD_INFOS: Mutex<Vec<[String; 7]>> = Mutex::new(Vec::new());
63/// Inter-mod symbol registry: mod_id → (symbol_name → function pointer).
64/// Filled during `yog_mod_register` (export calls), read during import calls.
65static INTEROP_SYMBOLS: OnceLock<Mutex<HashMap<String, HashMap<String, usize>>>> = OnceLock::new();
66/// Stable server table (populated once in nativeInit, then read-only).
67static SERVER: OnceLock<YogServer> = OnceLock::new();
68/// Stable api table. Mods capture this pointer at registration (yog-api's
69/// `installed_mods()` calls through it later, e.g. from UI render) — so it
70/// must outlive `nativeInit`, not live on its stack. `ctx` inside points at
71/// `HANDLERS`' own `RwLock`, published *before* any mod registers (unlike
72/// the old design, where it pointed at a temporary pre-move `Box` that
73/// went stale the instant `nativeInit` finished) — so it stays valid for a
74/// hot-reload's later re-registration too.
75static API_TABLE: OnceLock<YogApi> = OnceLock::new();
76/// All registered handlers + content. A `RwLock`, not a plain value: unlike
77/// the original one-shot-then-immutable design, a hot-reload needs to
78/// append fresh entries for a reloaded mod after this has long been
79/// published. Read sites (`handlers()`) take a read guard; registration
80/// (initial or reload) takes a write guard — both deref straight through to
81/// `RuntimeHandlers`, so existing `handlers().field` call sites are
82/// unaffected by this type change.
83static HANDLERS: OnceLock<RwLock<RuntimeHandlers>> = OnceLock::new();
84
85// ── OpenGL context (client-side, render thread only) ─────────────────────────
86
87struct GlCtx(glow::Context);
88unsafe impl Send for GlCtx {}
89unsafe impl Sync for GlCtx {}
90
91/// Initialized by `nativeGlInit` on the render thread.  `None` on dedicated server.
92static GL: OnceLock<GlCtx> = OnceLock::new();
93
94// Raw GL function pointers for GL_ARB_get_program_binary (not exposed by glow 0.13).
95// Captured during the glow loader callback in `nativeGlInit`.
96// `None` when the extension is unavailable (very old drivers).
97static GL_GET_PROGRAM_BINARY: OnceLock<Option<usize>> = OnceLock::new();
98static GL_PROGRAM_BINARY: OnceLock<Option<usize>> = OnceLock::new();
99static GL_GET_PROGRAM_IV: OnceLock<Option<usize>> = OnceLock::new();
100
101// ── Handler storage ───────────────────────────────────────────────────────────
102
103#[derive(Debug, Clone)]
104pub struct UiLayer {
105    pub id: String,
106    pub parent: Option<String>,
107    pub modal: bool,
108    pub pause_game: bool,
109    pub visible: bool,
110    pub enabled: bool,
111    pub z_index: i32,
112}
113
114/// One command registration: owning module, typed-args schema (if any),
115/// user data and callback.
116/// A tooltip picture's mod, user data, size and draw callbacks.
117type TooltipEntry = (LoadedModule, *mut c_void, yog_abi::YogTooltipSizeFn, yog_abi::YogTooltipDrawFn);
118type ItemTextEntry = (LoadedModule, *mut c_void, yog_abi::YogItemTextFn);
119type CommandEntry = (LoadedModule, Option<String>, *mut c_void, YogCommandFn);
120
121// Every callback table below is tagged with the `LoadedModule` that
122// registered it (see `current_registration()`), so a hot-reload's dispatch
123// sites can skip a retiring module's stale entries (`LoadedModule::
124// is_retiring()`) before they're physically swept by `RuntimeModuleRegistry
125// ::purge`. Content registries — `items`/`blocks`/`sound_groups`/`inventories`/`books`/
126// `recipes`/`dimensions`/`startup_grants`/`menu_entries` — are deliberately
127// NOT tagged: they're one-time definitions copied into Minecraft's own
128// registries at startup, not callbacks invoked later, and Minecraft itself
129// has no live registry-unregister mechanism to hot-reload them against
130// regardless of what this crate does.
131#[derive(Default)]
132struct RuntimeHandlers {
133    block_break: Vec<(LoadedModule, *mut c_void, YogBlockBreakFn)>,
134    chat: Vec<(LoadedModule, *mut c_void, YogChatFn)>,
135    player_join: Vec<(LoadedModule, *mut c_void, YogPlayerFn)>,
136    player_leave: Vec<(LoadedModule, *mut c_void, YogPlayerFn)>,
137    use_item: Vec<(LoadedModule, *mut c_void, YogUseItemFn)>,
138    use_block: Vec<(LoadedModule, *mut c_void, YogUseBlockFn)>,
139    attack_entity: Vec<(LoadedModule, *mut c_void, YogAttackEntityFn)>,
140    entity_damage: Vec<(LoadedModule, *mut c_void, YogEntityDamageFn)>,
141    entity_death: Vec<(LoadedModule, *mut c_void, YogEntityDeathFn)>,
142    entity_spawn: Vec<(LoadedModule, *mut c_void, YogEntitySpawnFn)>,
143    player_place_block: Vec<(LoadedModule, *mut c_void, YogPlaceBlockFn)>,
144    player_death: Vec<(LoadedModule, *mut c_void, YogPlayerDeathFn)>,
145    player_respawn: Vec<(LoadedModule, *mut c_void, YogPlayerRespawnFn)>,
146    advancement: Vec<(LoadedModule, *mut c_void, YogAdvancementFn)>,
147    entity_interact: Vec<(LoadedModule, *mut c_void, YogEntityInteractFn)>,
148    item_craft: Vec<(LoadedModule, *mut c_void, YogCraftFn)>,
149    machine_craft: Vec<(LoadedModule, *mut c_void, YogMachineCraftFn)>,
150    explosion: Vec<(LoadedModule, *mut c_void, YogExplosionFn)>,
151    item_pickup: Vec<(LoadedModule, *mut c_void, YogItemPickupFn)>,
152    item_insert: Vec<(LoadedModule, *mut c_void, YogItemInsertFn)>,
153    player_move: Vec<(LoadedModule, *mut c_void, YogPlayerMoveFn)>,
154    container_open: Vec<(LoadedModule, *mut c_void, YogContainerOpenFn)>,
155    container_close: Vec<(LoadedModule, *mut c_void, YogContainerCloseFn)>,
156    projectile_hit: Vec<(LoadedModule, *mut c_void, YogProjectileHitFn)>,
157    client_tick: Vec<(LoadedModule, *mut c_void, YogClientFn)>,
158    hud_render: Vec<(LoadedModule, *mut c_void, YogHudRenderFn)>,
159    body: Vec<(LoadedModule, *mut c_void, yog_abi::YogBodyFn)>,
160    camera: Vec<(LoadedModule, *mut c_void, yog_abi::YogCameraFn)>,
161    travel: Vec<(LoadedModule, *mut c_void, yog_abi::YogTravelFn)>,
162    loot: Vec<(LoadedModule, *mut c_void, yog_abi::YogLootFn)>,
163    world_render: Vec<(LoadedModule, *mut c_void, YogWorldRenderFn)>,
164    key_press: Vec<(LoadedModule, *mut c_void, YogKeyPressFn)>,
165    screen_open: Vec<(LoadedModule, *mut c_void, YogScreenFn)>,
166    screen_close: Vec<(LoadedModule, *mut c_void, YogScreenFn)>,
167    server_tick: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
168    server_started: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
169    server_stopping: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
170    /// All handlers registered under one command name, in registration order.
171    /// `schema` is `None` for a plain `on_command` (bare, zero-argument)
172    /// registration and `Some(schema)` for `on_typed_command`. Kept as a
173    /// `Vec` (not a single slot) so a mod can register several subcommands —
174    /// e.g. differing arg counts, or several bare/typed registrations sharing
175    /// one top-level name — without later registrations silently clobbering
176    /// earlier ones (see `nativeOnCommand`, which tries each entry whose
177    /// schema's arg count matches the actual invocation, in order, until one
178    /// produces a reply).
179    commands: HashMap<String, Vec<CommandEntry>>,
180    /// (namespace, name, the recipe in Yog's own format).
181    recipes: Vec<(String, String, yog_data::Value)>,
182    packets: HashMap<String, (LoadedModule, *mut c_void, YogPacketFn)>,
183    client_packets: HashMap<String, (LoadedModule, *mut c_void, YogPacketFn)>,
184    items: Vec<ItemDef>,
185    /// Mods' entity types, as Yog Data (the host reads them whole).
186    entities: Vec<yog_data::Value>,
187    /// Mods' attributes, mob effects and potions, as Yog Data (read whole too).
188    attributes: Vec<yog_data::Value>,
189    effects: Vec<yog_data::Value>,
190    potions: Vec<yog_data::Value>,
191    /// Ticks of mods' entities, by type.
192    entity_ticks: HashMap<String, Vec<(LoadedModule, *mut c_void, yog_abi::YogEntityTickFn)>>,
193    blocks: Vec<BlockDef>,
194    /// The content blob the hosts read (`nativeContent`), built once —
195    /// dropped when more content registers.
196    content_blob: Mutex<Option<Arc<Vec<u8>>>>,
197    /// Mods' sound groups by id; a block's `sound` is one of these or built in.
198    sound_groups: HashMap<String, yog_registry::SoundGroup>,
199    /// Mods' tool and armor materials by id (the game's are built in).
200    tool_materials: HashMap<String, yog_registry::ToolMaterial>,
201    /// Placed features added to biomes (an ore's): for the hosts that add them in code.
202    biome_features: Vec<yog_registry::BiomeFeature>,
203    armor_materials: HashMap<String, yog_registry::ArmorMaterial>,
204    inventories: Vec<yog_inventory::InventoryDef>,
205    /// The ids of the registered books (their renderers are `book_renderers`).
206    books: std::collections::HashSet<String>,
207    book_renderers: Mutex<HashMap<String, yog_book::BookRenderer>>,
208    /// Declared dimension-type defs: id -> `YogDimensionDef` JSON. Actual
209    /// `LevelStem`/`ServerLevel` creation is a host (Java) responsibility —
210    /// see `yog-dimensions` crate docs.
211    dimensions: HashMap<String, yog_data::Value>,
212    chunk_generators: HashMap<String, (LoadedModule, *mut c_void, yog_abi::YogChunkGeneratorFn)>,
213    /// Dimensions' `terrain`s (`.ydef`), generated here: by the dimension's id,
214    /// which is its `generator_type`.
215    terrains: HashMap<String, Arc<yog_worldgen::Generator>>,
216    ui_handlers: HashMap<String, (LoadedModule, *mut c_void, yog_abi::YogUIEventFn)>,
217    ui_render_handlers: HashMap<String, Vec<(LoadedModule, *mut c_void, YogHudRenderFn)>>,
218    /// Book pages' pictures (`BookPage::Drawn`), by drawer id.
219    page_drawers: HashMap<String, (LoadedModule, *mut c_void, yog_abi::YogPageDrawFn)>,
220    /// Pictures in item tooltips, by item id: the first that answers draws.
221    item_tooltips: HashMap<String, Vec<TooltipEntry>>,
222    /// Stacks' own names and tooltip lines, by item.
223    item_texts: HashMap<String, Vec<ItemTextEntry>>,
224    menu_entries: Vec<(String, String)>, // (label, ui_id) for vanilla screen buttons
225    pub active_uis: Mutex<Vec<UiLayer>>,
226    startup_grants: Vec<yog_registry::StartupGrant>,
227    /// Players whose startup grants are pending: (name, uuid, ticks_waited).
228    /// Granting happens on a server tick after join — giving items directly in
229    /// the join callback fails for the host of a freshly created world.
230    pending_grants: Mutex<Vec<(String, String, u32)>>,
231    scheduler: Mutex<SchedulerState>,
232}
233
234// All fn ptrs are C-ABI; ud pointers are from Box::into_raw of Send+Sync closures.
235unsafe impl Send for RuntimeHandlers {}
236unsafe impl Sync for RuntimeHandlers {}
237
238#[derive(Default)]
239struct SchedulerState {
240    once_tasks: Vec<OnceTask>,
241    repeating_tasks: Vec<RepeatingTask>,
242}
243
244impl SchedulerState {
245    /// One server tick: the tasks due now — once tasks whose delay ran out
246    /// (`schedule_once(d)`: `d` ticks later, 0 and 1 meaning the next tick),
247    /// repeating ones whose period came round (`schedule_repeating(p)`:
248    /// every `p` ticks, 0 meaning every tick). Once tasks fired are gone.
249    fn due(&mut self) -> Vec<(LoadedModule, *mut c_void, YogScheduledFn)> {
250        let mut out = Vec::new();
251        self.once_tasks.retain_mut(|t| {
252            if t.delay_remaining <= 1 {
253                out.push((t.module.clone(), t.ud, t.f));
254                false
255            } else {
256                t.delay_remaining -= 1;
257                true
258            }
259        });
260        for t in &mut self.repeating_tasks {
261            t.ticks_left = t.ticks_left.saturating_sub(1);
262            if t.ticks_left == 0 {
263                out.push((t.module.clone(), t.ud, t.f));
264                t.ticks_left = t.period.max(1);
265            }
266        }
267        out
268    }
269}
270
271struct OnceTask {
272    module: LoadedModule,
273    delay_remaining: u64,
274    ud: *mut c_void,
275    f: YogScheduledFn,
276}
277struct RepeatingTask {
278    module: LoadedModule,
279    period: u64,
280    ticks_left: u64,
281    ud: *mut c_void,
282    f: YogScheduledFn,
283}
284
285unsafe impl Send for SchedulerState {}
286unsafe impl Sync for SchedulerState {}
287unsafe impl Send for OnceTask {}
288unsafe impl Send for RepeatingTask {}
289
290/// A mod callback, tagged with the module that registered it.
291type Entry<F> = (LoadedModule, *mut c_void, F);
292
293/// Calls `call(ud, f)` for every entry whose module is still live, until
294/// one returns `false`; whether none did.
295fn each_while<F: Copy>(entries: &[Entry<F>], mut call: impl FnMut(*mut c_void, F) -> bool) -> bool {
296    for (module, ud, f) in entries {
297        if module.is_retiring() {
298            continue;
299        }
300        let Some(_call) = module.enter() else {
301            continue;
302        };
303        if !call(*ud, *f) {
304            return false;
305        }
306    }
307    true
308}
309
310/// Calls `call(ud, f)` for every entry whose module is still live (a
311/// post-phase handler's result is ignored).
312fn each<F: Copy, R>(entries: &[Entry<F>], mut call: impl FnMut(*mut c_void, F) -> R) {
313    each_while(entries, |ud, f| {
314        call(ud, f);
315        true
316    });
317}
318
319/// Pre-phase dispatch: whether every live handler allows the action. The
320/// first `false` cancels it and skips the rest; a panicking mod allows it.
321fn allowed<F: Copy>(entries: &[Entry<F>], call: impl FnMut(*mut c_void, F) -> bool) -> bool {
322    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| each_while(entries, call)))
323        .unwrap_or(true)
324}
325
326fn handlers() -> std::sync::RwLockReadGuard<'static, RuntimeHandlers> {
327    HANDLERS
328        .get()
329        .expect("yog: nativeInit not called yet")
330        .read()
331        .expect("handlers lock poisoned")
332}
333
334fn current_registration() -> LoadedModule {
335    CURRENT_REGISTRATION
336        .lock()
337        .unwrap()
338        .clone()
339        .expect("a yog-runtime api_* function was called outside of yog_mod_register")
340}
341
342fn hot_reloader() -> &'static HotReloader<RuntimeModuleRegistry> {
343    HOT_RELOADER.get().expect("yog: nativeInit not called yet")
344}
345
346/// The `yog-hot-reload` host contract: `retarget` needs no work here because
347/// `LoadedModule::is_retiring()` already makes a superseded generation's
348/// dispatch-table entries inert (every `handlers().<field>` loop checks it)
349/// the instant `HotReloader::reload` calls `retire` on the old module —
350/// well before this is even invoked. `purge` is the actual safety-net
351/// sweep, dropping every entry tagged with a retired generation right
352/// before its library is hard-unloaded.
353/// Runs `$body` with `$list` bound to each per-event handler list of `$h`.
354macro_rules! for_each_handler_list {
355    ($h:expr_2021, |$list:ident| $body:expr_2021) => {{
356        {
357            let $list = &mut $h.block_break;
358            $body;
359        }
360        {
361            let $list = &mut $h.chat;
362            $body;
363        }
364        {
365            let $list = &mut $h.player_join;
366            $body;
367        }
368        {
369            let $list = &mut $h.player_leave;
370            $body;
371        }
372        {
373            let $list = &mut $h.use_item;
374            $body;
375        }
376        {
377            let $list = &mut $h.use_block;
378            $body;
379        }
380        {
381            let $list = &mut $h.attack_entity;
382            $body;
383        }
384        {
385            let $list = &mut $h.entity_damage;
386            $body;
387        }
388        {
389            let $list = &mut $h.entity_death;
390            $body;
391        }
392        {
393            let $list = &mut $h.entity_spawn;
394            $body;
395        }
396        {
397            let $list = &mut $h.player_place_block;
398            $body;
399        }
400        {
401            let $list = &mut $h.player_death;
402            $body;
403        }
404        {
405            let $list = &mut $h.player_respawn;
406            $body;
407        }
408        {
409            let $list = &mut $h.advancement;
410            $body;
411        }
412        {
413            let $list = &mut $h.entity_interact;
414            $body;
415        }
416        {
417            let $list = &mut $h.item_craft;
418            $body;
419        }
420        {
421            let $list = &mut $h.machine_craft;
422            $body;
423        }
424        {
425            let $list = &mut $h.explosion;
426            $body;
427        }
428        {
429            let $list = &mut $h.item_pickup;
430            $body;
431        }
432        {
433            let $list = &mut $h.item_insert;
434            $body;
435        }
436        {
437            let $list = &mut $h.player_move;
438            $body;
439        }
440        {
441            let $list = &mut $h.container_open;
442            $body;
443        }
444        {
445            let $list = &mut $h.container_close;
446            $body;
447        }
448        {
449            let $list = &mut $h.projectile_hit;
450            $body;
451        }
452        {
453            let $list = &mut $h.client_tick;
454            $body;
455        }
456        {
457            let $list = &mut $h.hud_render;
458            $body;
459        }
460        {
461            let $list = &mut $h.body;
462            $body;
463        }
464        {
465            let $list = &mut $h.camera;
466            $body;
467        }
468        {
469            let $list = &mut $h.travel;
470            $body;
471        }
472        {
473            let $list = &mut $h.loot;
474            $body;
475        }
476        {
477            let $list = &mut $h.world_render;
478            $body;
479        }
480        {
481            let $list = &mut $h.key_press;
482            $body;
483        }
484        {
485            let $list = &mut $h.screen_open;
486            $body;
487        }
488        {
489            let $list = &mut $h.screen_close;
490            $body;
491        }
492        {
493            let $list = &mut $h.server_tick;
494            $body;
495        }
496        {
497            let $list = &mut $h.server_started;
498            $body;
499        }
500        {
501            let $list = &mut $h.server_stopping;
502            $body;
503        }
504    }};
505}
506
507struct RuntimeModuleRegistry;
508
509impl ModuleRegistry for RuntimeModuleRegistry {
510    fn retarget(&self, _mod_id: &str, _from: ModuleGeneration, _to: ModuleGeneration) {}
511
512    fn purge(&self, generation: ModuleGeneration) {
513        let Some(lock) = HANDLERS.get() else { return };
514        let mut h = lock.write().expect("handlers lock poisoned");
515        let h = &mut *h;
516        for_each_handler_list!(h, |list| list
517            .retain(|(m, ..)| m.generation() != generation));
518        for entries in h.commands.values_mut() {
519            entries.retain(|(m, ..)| m.generation() != generation);
520        }
521        h.packets.retain(|_, (m, ..)| m.generation() != generation);
522        h.client_packets
523            .retain(|_, (m, ..)| m.generation() != generation);
524        h.chunk_generators
525            .retain(|_, (m, ..)| m.generation() != generation);
526        h.ui_handlers
527            .retain(|_, (m, ..)| m.generation() != generation);
528        for entries in h.ui_render_handlers.values_mut() {
529            entries.retain(|(m, ..)| m.generation() != generation);
530        }
531        h.page_drawers
532            .retain(|_, (m, ..)| m.generation() != generation);
533        for entries in h.item_texts.values_mut() {
534            entries.retain(|(m, ..)| m.generation() != generation);
535        }
536        for entries in h.entity_ticks.values_mut() {
537            entries.retain(|(m, ..)| m.generation() != generation);
538        }
539        for entries in h.item_tooltips.values_mut() {
540            entries.retain(|(m, ..)| m.generation() != generation);
541        }
542        h.scheduler
543            .lock()
544            .expect("scheduler poisoned")
545            .once_tasks
546            .retain(|t| t.module.generation() != generation);
547        h.scheduler
548            .lock()
549            .expect("scheduler poisoned")
550            .repeating_tasks
551            .retain(|t| t.module.generation() != generation);
552    }
553}
554
555// ── JNI helpers ──────────────────────────────────────────────────────────────
556
557fn guard(label: &str, f: impl FnOnce()) {
558    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err() {
559        yog_logging::error!("a mod panicked handling `{}` (ignored)", label);
560    }
561}
562
563/// Reads a Java string, returning `$or` (default: `Default::default()`)
564/// from the enclosing function when it can't be read.
565macro_rules! jstr {
566    ($env:expr_2021, $s:expr_2021) => {
567        jstr!($env, $s, Default::default())
568    };
569    ($env:expr_2021, $s:expr_2021, $or:expr_2021) => {
570        match $env.get_string(&$s) {
571            Ok(s) => String::from(s),
572            Err(_) => return $or,
573        }
574    };
575}
576
577fn get_env() -> Option<jni::AttachGuard<'static>> {
578    JAVA_VM.get()?.attach_current_thread().ok()
579}
580
581/// `<class>.<name>(args...)` on this thread's env, `Option<R>` — see
582/// [`jcall!`]; `None` without a JVM too.
583macro_rules! host {
584    ($class:literal, $name:literal, [$($arg:expr_2021),* $(,)?]) => {
585        match $crate::get_env() {
586            Some(mut env) => $crate::jcall::jcall!(&mut env, $class, $name, [$($arg),*]),
587            None => None,
588        }
589    };
590}
591
592/// `NativeBridge.<name>(args...)` — see [`host!`].
593macro_rules! bridge {
594    ($name:literal, [$($arg:expr_2021),* $(,)?]) => {
595        host!("dev/yog/NativeBridge", $name, [$($arg),*])
596    };
597}
598
599/// A host string reply handed to a mod (`None`/`null` → [`YogOwnedStr::NONE`]).
600fn owned(s: Option<String>) -> YogOwnedStr {
601    s.map_or(YogOwnedStr::NONE, YogOwnedStr::from_string)
602}
603
604/// The first `N` tab-separated values of a host reply.
605fn parse_tsv<T: std::str::FromStr, const N: usize>(s: &str) -> Option<[T; N]> {
606    let values: Vec<T> = s
607        .split('\t')
608        .take(N)
609        .map(|v| v.parse().ok())
610        .collect::<Option<_>>()?;
611    values.try_into().ok()
612}
613
614// ── Free-str allocator used by YogOwnedStr ────────────────────────────────────
615
616unsafe extern "C" fn yog_free_str(ptr: *mut u8, len: u32) {
617    unsafe {
618        if !ptr.is_null() {
619            drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
620                ptr,
621                len as usize,
622            )));
623        }
624    }
625}
626
627// ── YogServer standalone functions (one per action) ───────────────────────────
628//
629// ctx is unused here — all state is in the JAVA_VM static.
630
631unsafe extern "C" fn srv_broadcast(_ctx: *mut c_void, msg: YogStr) {
632    unsafe {
633        let _: Option<()> = bridge!("broadcast", [S(msg)]);
634    }
635}
636
637unsafe extern "C" fn srv_get_block(
638    _ctx: *mut c_void,
639    dim: YogStr,
640    pos: YogBlockPos,
641) -> YogOwnedStr {
642    unsafe { owned(bridge!("getBlock", [S(dim), I(pos.x), I(pos.y), I(pos.z)])) }
643}
644
645unsafe extern "C" fn srv_set_block(
646    _ctx: *mut c_void,
647    dim: YogStr,
648    pos: YogBlockPos,
649    block: YogStr,
650) -> bool {
651    unsafe {
652        bridge!("setBlock", [S(dim), I(pos.x), I(pos.y), I(pos.z), S(block)]).unwrap_or(false)
653    }
654}
655
656unsafe extern "C" fn srv_world_time(_ctx: *mut c_void, dim: YogStr, out: *mut i64) -> bool {
657    unsafe {
658        match bridge!("worldTime", [S(dim)]) {
659            Some(v) if v != i64::MIN => {
660                *out = v;
661                true
662            }
663            _ => false,
664        }
665    }
666}
667
668unsafe extern "C" fn srv_set_time(_ctx: *mut c_void, dim: YogStr, time: i64) -> bool {
669    unsafe { bridge!("worldSetTime", [S(dim), J(time)]).unwrap_or(false) }
670}
671
672unsafe extern "C" fn srv_is_raining(_ctx: *mut c_void, dim: YogStr) -> bool {
673    unsafe { bridge!("worldIsRaining", [S(dim)]).unwrap_or(false) }
674}
675
676unsafe extern "C" fn srv_set_weather(
677    _ctx: *mut c_void,
678    dim: YogStr,
679    raining: bool,
680    dur: i32,
681) -> bool {
682    unsafe { bridge!("worldSetWeather", [S(dim), Z(raining), I(dur)]).unwrap_or(false) }
683}
684
685unsafe extern "C" fn srv_give_item(
686    _ctx: *mut c_void,
687    player: YogStr,
688    item: YogStr,
689    count: u32,
690) -> bool {
691    unsafe { bridge!("giveItem", [S(player), S(item), I(count as i32)]).unwrap_or(false) }
692}
693
694unsafe extern "C" fn srv_player_teleport(_ctx: *mut c_void, player: YogStr, pos: YogVec3) -> bool {
695    unsafe { bridge!("teleport", [S(player), D(pos.x), D(pos.y), D(pos.z)]).unwrap_or(false) }
696}
697
698unsafe extern "C" fn srv_send_to_player(
699    _ctx: *mut c_void,
700    player: YogStr,
701    channel: YogStr,
702    data: *const u8,
703    len: u32,
704) -> bool {
705    unsafe {
706        bridge!(
707            "sendToPlayer",
708            [
709                S(player),
710                S(channel),
711                Bytes(std::slice::from_raw_parts(data, len as usize))
712            ]
713        )
714        .unwrap_or(false)
715    }
716}
717
718unsafe extern "C" fn srv_send_to_server(
719    _ctx: *mut c_void,
720    channel: YogStr,
721    data: *const u8,
722    len: u32,
723) -> bool {
724    unsafe {
725        host!(
726            "dev/yog/YogClient",
727            "sendToServer",
728            [
729                S(channel),
730                Bytes(std::slice::from_raw_parts(data, len as usize))
731            ]
732        )
733        .unwrap_or(false)
734    }
735}
736
737unsafe extern "C" fn srv_kick_player(_ctx: *mut c_void, player: YogStr, reason: YogStr) -> bool {
738    unsafe { bridge!("kickPlayer", [S(player), S(reason)]).unwrap_or(false) }
739}
740
741unsafe extern "C" fn srv_set_gamemode(_ctx: *mut c_void, player: YogStr, mode: YogStr) -> bool {
742    unsafe { bridge!("setGamemode", [S(player), S(mode)]).unwrap_or(false) }
743}
744
745unsafe extern "C" fn srv_send_title(
746    _ctx: *mut c_void,
747    player: YogStr,
748    title: YogStr,
749    sub: YogStr,
750    fi: i32,
751    stay: i32,
752    fo: i32,
753) -> bool {
754    unsafe {
755        bridge!(
756            "sendTitle",
757            [S(player), S(title), S(sub), I(fi), I(stay), I(fo)]
758        )
759        .unwrap_or(false)
760    }
761}
762
763unsafe extern "C" fn srv_send_actionbar(_ctx: *mut c_void, player: YogStr, msg: YogStr) -> bool {
764    unsafe { bridge!("sendActionbar", [S(player), S(msg)]).unwrap_or(false) }
765}
766
767unsafe extern "C" fn srv_play_sound(
768    _ctx: *mut c_void,
769    dim: YogStr,
770    pos: YogVec3,
771    sound: YogStr,
772    vol: f32,
773    pitch: f32,
774) -> bool {
775    unsafe {
776        bridge!(
777            "playSound",
778            [
779                S(dim),
780                D(pos.x),
781                D(pos.y),
782                D(pos.z),
783                S(sound),
784                F(vol),
785                F(pitch)
786            ]
787        )
788        .unwrap_or(false)
789    }
790}
791
792unsafe extern "C" fn srv_play_sound_player(
793    _ctx: *mut c_void,
794    player: YogStr,
795    sound: YogStr,
796    vol: f32,
797    pitch: f32,
798) -> bool {
799    unsafe {
800        bridge!("playSoundToPlayer", [S(player), S(sound), F(vol), F(pitch)]).unwrap_or(false)
801    }
802}
803
804unsafe extern "C" fn srv_entity_teleport(_ctx: *mut c_void, uuid: YogStr, pos: YogVec3) -> bool {
805    unsafe { bridge!("entityTeleport", [S(uuid), D(pos.x), D(pos.y), D(pos.z)]).unwrap_or(false) }
806}
807
808unsafe extern "C" fn srv_entity_rotation(
809    _ctx: *mut c_void,
810    uuid: YogStr,
811    out: *mut YogVec3,
812) -> bool {
813    unsafe {
814        let Some(s): Option<String> = bridge!("entityRotation", [S(uuid)]) else {
815            return false;
816        };
817        match parse_tsv::<f64, 2>(&s) {
818            Some([yaw, pitch]) => {
819                *out = YogVec3 {
820                    x: yaw,
821                    y: pitch,
822                    z: 0.0,
823                };
824                true
825            }
826            None => false,
827        }
828    }
829}
830
831unsafe extern "C" fn srv_entity_position(
832    _ctx: *mut c_void,
833    uuid: YogStr,
834    out: *mut YogVec3,
835) -> bool {
836    unsafe {
837        let Some(s): Option<String> = bridge!("entityPosition", [S(uuid)]) else {
838            return false;
839        };
840        match parse_tsv::<f64, 3>(&s) {
841            Some([x, y, z]) => {
842                *out = YogVec3 { x, y, z };
843                true
844            }
845            None => false,
846        }
847    }
848}
849
850unsafe extern "C" fn srv_entity_health(_ctx: *mut c_void, uuid: YogStr, out: *mut f32) -> bool {
851    unsafe {
852        match bridge!("entityHealth", [S(uuid)]) {
853            Some(v) if !f64::is_nan(v) => {
854                *out = v as f32;
855                true
856            }
857            _ => false,
858        }
859    }
860}
861
862unsafe extern "C" fn srv_entity_set_health(_ctx: *mut c_void, uuid: YogStr, hp: f32) -> bool {
863    unsafe { bridge!("entitySetHealth", [S(uuid), D(hp as f64)]).unwrap_or(false) }
864}
865
866unsafe extern "C" fn srv_entity_kill(_ctx: *mut c_void, uuid: YogStr) -> bool {
867    unsafe { bridge!("entityKill", [S(uuid)]).unwrap_or(false) }
868}
869
870unsafe extern "C" fn srv_spawn_entity(
871    _ctx: *mut c_void,
872    type_id: YogStr,
873    dim: YogStr,
874    pos: YogVec3,
875) -> YogOwnedStr {
876    unsafe {
877        owned(bridge!(
878            "spawnEntity",
879            [S(type_id), S(dim), D(pos.x), D(pos.y), D(pos.z)]
880        ))
881    }
882}
883
884unsafe extern "C" fn srv_entity_add_effect(
885    _ctx: *mut c_void,
886    uuid: YogStr,
887    fx: YogStr,
888    dur: i32,
889    amp: u8,
890    particles: bool,
891) -> bool {
892    unsafe {
893        bridge!(
894            "entityAddEffect",
895            [S(uuid), S(fx), I(dur), I(amp as i32), Z(particles)]
896        )
897        .unwrap_or(false)
898    }
899}
900
901unsafe extern "C" fn srv_entity_remove_effect(_ctx: *mut c_void, uuid: YogStr, fx: YogStr) -> bool {
902    unsafe { bridge!("entityRemoveEffect", [S(uuid), S(fx)]).unwrap_or(false) }
903}
904
905unsafe extern "C" fn srv_entity_clear_effects(_ctx: *mut c_void, uuid: YogStr) -> bool {
906    unsafe { bridge!("entityClearEffects", [S(uuid)]).unwrap_or(false) }
907}
908
909unsafe extern "C" fn srv_entity_velocity(
910    _ctx: *mut c_void,
911    uuid: YogStr,
912    out: *mut YogVec3,
913) -> bool {
914    unsafe {
915        let Some(s): Option<String> = bridge!("entityVelocity", [S(uuid)]) else {
916            return false;
917        };
918        match parse_tsv::<f64, 3>(&s) {
919            Some([x, y, z]) => {
920                *out = YogVec3 { x, y, z };
921                true
922            }
923            None => false,
924        }
925    }
926}
927
928unsafe extern "C" fn srv_entity_set_velocity(
929    _ctx: *mut c_void,
930    uuid: YogStr,
931    vel: YogVec3,
932) -> bool {
933    unsafe {
934        bridge!("entitySetVelocity", [S(uuid), D(vel.x), D(vel.y), D(vel.z)]).unwrap_or(false)
935    }
936}
937
938unsafe extern "C" fn srv_entity_add_velocity(
939    _ctx: *mut c_void,
940    uuid: YogStr,
941    vel: YogVec3,
942) -> bool {
943    unsafe {
944        bridge!("entityAddVelocity", [S(uuid), D(vel.x), D(vel.y), D(vel.z)]).unwrap_or(false)
945    }
946}
947
948unsafe extern "C" fn srv_has_item_tag(_ctx: *mut c_void, item: YogStr, tag: YogStr) -> bool {
949    unsafe { bridge!("hasItemTag", [S(item), S(tag)]).unwrap_or(false) }
950}
951
952unsafe extern "C" fn srv_has_block_tag(_ctx: *mut c_void, block: YogStr, tag: YogStr) -> bool {
953    unsafe { bridge!("hasBlockTag", [S(block), S(tag)]).unwrap_or(false) }
954}
955
956unsafe extern "C" fn srv_drop_loot(
957    _ctx: *mut c_void,
958    table: YogStr,
959    dim: YogStr,
960    pos: YogVec3,
961) -> bool {
962    unsafe {
963        bridge!("dropLoot", [S(table), S(dim), D(pos.x), D(pos.y), D(pos.z)]).unwrap_or(false)
964    }
965}
966
967unsafe extern "C" fn srv_scoreboard_get(
968    _ctx: *mut c_void,
969    obj: YogStr,
970    player: YogStr,
971    out: *mut i32,
972) -> bool {
973    unsafe {
974        match bridge!("scoreboardGet", [S(obj), S(player)]) {
975            Some(v) if v != i32::MIN => {
976                *out = v;
977                true
978            }
979            _ => false,
980        }
981    }
982}
983
984unsafe extern "C" fn srv_scoreboard_set(
985    _ctx: *mut c_void,
986    obj: YogStr,
987    player: YogStr,
988    score: i32,
989) -> bool {
990    unsafe { bridge!("scoreboardSet", [S(obj), S(player), I(score)]).unwrap_or(false) }
991}
992
993unsafe extern "C" fn srv_scoreboard_add(
994    _ctx: *mut c_void,
995    obj: YogStr,
996    player: YogStr,
997    delta: i32,
998    out: *mut i32,
999) -> bool {
1000    unsafe {
1001        match bridge!("scoreboardAdd", [S(obj), S(player), I(delta)]) {
1002            Some(v) if v != i32::MIN => {
1003                *out = v;
1004                true
1005            }
1006            _ => false,
1007        }
1008    }
1009}
1010
1011unsafe extern "C" fn srv_bossbar_create(
1012    _ctx: *mut c_void,
1013    id: YogStr,
1014    title: YogStr,
1015    color: YogStr,
1016    style: YogStr,
1017) -> bool {
1018    unsafe { bridge!("bossbarCreate", [S(id), S(title), S(color), S(style)]).unwrap_or(false) }
1019}
1020
1021unsafe extern "C" fn srv_bossbar_remove(_ctx: *mut c_void, id: YogStr) -> bool {
1022    unsafe { bridge!("bossbarRemove", [S(id)]).unwrap_or(false) }
1023}
1024
1025unsafe extern "C" fn srv_bossbar_set_title(_ctx: *mut c_void, id: YogStr, title: YogStr) -> bool {
1026    unsafe { bridge!("bossbarSetTitle", [S(id), S(title)]).unwrap_or(false) }
1027}
1028
1029unsafe extern "C" fn srv_bossbar_set_progress(
1030    _ctx: *mut c_void,
1031    id: YogStr,
1032    progress: f32,
1033) -> bool {
1034    unsafe { bridge!("bossbarSetProgress", [S(id), F(progress)]).unwrap_or(false) }
1035}
1036
1037unsafe extern "C" fn srv_bossbar_set_color(_ctx: *mut c_void, id: YogStr, color: YogStr) -> bool {
1038    unsafe { bridge!("bossbarSetColor", [S(id), S(color)]).unwrap_or(false) }
1039}
1040
1041unsafe extern "C" fn srv_bossbar_add_player(_ctx: *mut c_void, id: YogStr, player: YogStr) -> bool {
1042    unsafe { bridge!("bossbarAddPlayer", [S(id), S(player)]).unwrap_or(false) }
1043}
1044
1045unsafe extern "C" fn srv_bossbar_remove_player(
1046    _ctx: *mut c_void,
1047    id: YogStr,
1048    player: YogStr,
1049) -> bool {
1050    unsafe { bridge!("bossbarRemovePlayer", [S(id), S(player)]).unwrap_or(false) }
1051}
1052
1053unsafe extern "C" fn srv_bossbar_set_visible(_ctx: *mut c_void, id: YogStr, visible: bool) -> bool {
1054    unsafe { bridge!("bossbarSetVisible", [S(id), Z(visible)]).unwrap_or(false) }
1055}
1056
1057unsafe extern "C" fn srv_get_block_nbt(
1058    _ctx: *mut c_void,
1059    dim: YogStr,
1060    pos: YogBlockPos,
1061) -> YogOwnedStr {
1062    unsafe {
1063        owned(bridge!(
1064            "getBlockNbt",
1065            [S(dim), I(pos.x), I(pos.y), I(pos.z)]
1066        ))
1067    }
1068}
1069
1070unsafe extern "C" fn srv_set_block_nbt(
1071    _ctx: *mut c_void,
1072    dim: YogStr,
1073    pos: YogBlockPos,
1074    snbt: YogStr,
1075) -> bool {
1076    unsafe {
1077        bridge!(
1078            "setBlockNbt",
1079            [S(dim), I(pos.x), I(pos.y), I(pos.z), S(snbt)]
1080        )
1081        .unwrap_or(false)
1082    }
1083}
1084
1085unsafe extern "C" fn srv_get_inventory_slot(
1086    _ctx: *mut c_void,
1087    dim: YogStr,
1088    pos: yog_abi::YogBlockPos,
1089    slot: u32,
1090) -> YogOwnedStr {
1091    unsafe {
1092        owned(bridge!(
1093            "getInventorySlot",
1094            [S(dim), I(pos.x), I(pos.y), I(pos.z), I(slot as i32)]
1095        ))
1096    }
1097}
1098
1099unsafe extern "C" fn srv_set_inventory_slot(
1100    _ctx: *mut c_void,
1101    dim: YogStr,
1102    pos: yog_abi::YogBlockPos,
1103    slot: u32,
1104    item_id: YogStr,
1105    count: u32,
1106) -> bool {
1107    unsafe {
1108        bridge!(
1109            "setInventorySlot",
1110            [
1111                S(dim),
1112                I(pos.x),
1113                I(pos.y),
1114                I(pos.z),
1115                I(slot as i32),
1116                S(item_id),
1117                I(count as i32)
1118            ]
1119        )
1120        .unwrap_or(false)
1121    }
1122}
1123
1124unsafe extern "C" fn srv_player_inventory(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1125    unsafe { owned(bridge!("playerInventory", [S(player)])) }
1126}
1127
1128unsafe extern "C" fn srv_player_set_slot(
1129    _ctx: *mut c_void,
1130    player: YogStr,
1131    slot: u32,
1132    item_id: YogStr,
1133    count: u32,
1134) -> bool {
1135    unsafe {
1136        bridge!(
1137            "playerSetSlot",
1138            [S(player), I(slot as i32), S(item_id), I(count as i32)]
1139        )
1140        .unwrap_or(false)
1141    }
1142}
1143
1144unsafe extern "C" fn srv_player_teleport_dim(
1145    _ctx: *mut c_void,
1146    player: YogStr,
1147    dim: YogStr,
1148    pos: YogVec3,
1149) -> bool {
1150    unsafe {
1151        bridge!(
1152            "teleportToDim",
1153            [S(player), S(dim), D(pos.x), D(pos.y), D(pos.z)]
1154        )
1155        .unwrap_or(false)
1156    }
1157}
1158
1159unsafe extern "C" fn srv_entity_teleport_dim(
1160    _ctx: *mut c_void,
1161    uuid: YogStr,
1162    dim: YogStr,
1163    pos: YogVec3,
1164) -> bool {
1165    unsafe {
1166        bridge!(
1167            "entityTeleportToDim",
1168            [S(uuid), S(dim), D(pos.x), D(pos.y), D(pos.z)]
1169        )
1170        .unwrap_or(false)
1171    }
1172}
1173
1174unsafe extern "C" fn srv_online_players(_ctx: *mut c_void) -> YogOwnedStr {
1175    unsafe { owned(bridge!("onlinePlayers", [])) }
1176}
1177
1178unsafe extern "C" fn srv_world_entity_count(
1179    _ctx: *mut c_void,
1180    dim: YogStr,
1181    entity_type: YogStr,
1182) -> i32 {
1183    unsafe { bridge!("worldEntityCount", [S(dim), S(entity_type)]).unwrap_or(-1) }
1184}
1185
1186unsafe extern "C" fn srv_game_dir(_ctx: *mut c_void) -> YogOwnedStr {
1187    unsafe { owned(bridge!("gameDir", [])) }
1188}
1189
1190unsafe extern "C" fn srv_world_dir(_ctx: *mut c_void) -> YogOwnedStr {
1191    unsafe { owned(bridge!("worldDir", [])) }
1192}
1193
1194unsafe extern "C" fn srv_entity_get_nbt(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
1195    unsafe { owned(bridge!("entityGetNbt", [S(uuid)])) }
1196}
1197
1198unsafe extern "C" fn srv_entity_set_nbt(_ctx: *mut c_void, uuid: YogStr, snbt: YogStr) -> bool {
1199    unsafe { bridge!("entitySetNbt", [S(uuid), S(snbt)]).unwrap_or(false) }
1200}
1201
1202unsafe extern "C" fn srv_spawn_particles(
1203    _ctx: *mut c_void,
1204    dim: YogStr,
1205    pos: YogVec3,
1206    particle_type: YogStr,
1207    count: i32,
1208    dx: f64,
1209    dy: f64,
1210    dz: f64,
1211    speed: f64,
1212) -> bool {
1213    unsafe {
1214        bridge!(
1215            "spawnParticles",
1216            [
1217                S(dim),
1218                D(pos.x),
1219                D(pos.y),
1220                D(pos.z),
1221                S(particle_type),
1222                I(count),
1223                D(dx),
1224                D(dy),
1225                D(dz),
1226                D(speed)
1227            ]
1228        )
1229        .unwrap_or(false)
1230    }
1231}
1232
1233unsafe extern "C" fn srv_entity_attribute_value(_ctx: *mut c_void, uuid: YogStr, attr: YogStr) -> f64 {
1234    unsafe { bridge!("entityAttributeValue", [S(uuid), S(attr)]).unwrap_or(f64::NAN) }
1235}
1236
1237unsafe extern "C" fn api_client_attribute_value(_ctx: *mut c_void, attr: YogStr) -> f64 {
1238    unsafe { host!("dev/yog/YogClientApi", "attributeValue", [S(attr)]).unwrap_or(f64::NAN) }
1239}
1240
1241unsafe extern "C" fn srv_advancement_grant(_ctx: *mut c_void, uuid: YogStr, id: YogStr) -> bool {
1242    unsafe { bridge!("advancementGrant", [S(uuid), S(id)]).unwrap_or(false) }
1243}
1244
1245unsafe extern "C" fn srv_advancement_done(_ctx: *mut c_void, uuid: YogStr, id: YogStr) -> bool {
1246    unsafe { bridge!("advancementDone", [S(uuid), S(id)]).unwrap_or(false) }
1247}
1248
1249/// Whether this client's player has advancement `id` — also what books ask
1250/// of their locked entries (see `nativeInit`).
1251fn client_advancement_done(id: &str) -> bool {
1252    unsafe { host!("dev/yog/YogClientApi", "advancementDone", [JArg::S(YogStr::from_str(id))]).unwrap_or(false) }
1253}
1254
1255unsafe extern "C" fn api_client_advancement_done(_ctx: *mut c_void, id: YogStr) -> bool {
1256    client_advancement_done(unsafe { id.as_str() })
1257}
1258
1259unsafe extern "C" fn srv_entity_attribute_get(
1260    _ctx: *mut c_void,
1261    uuid: YogStr,
1262    attr: YogStr,
1263) -> f64 {
1264    unsafe { bridge!("entityAttributeGet", [S(uuid), S(attr)]).unwrap_or(f64::NAN) }
1265}
1266
1267unsafe extern "C" fn srv_entity_attribute_set(
1268    _ctx: *mut c_void,
1269    uuid: YogStr,
1270    attr: YogStr,
1271    value: f64,
1272) -> bool {
1273    unsafe { bridge!("entityAttributeSet", [S(uuid), S(attr), D(value)]).unwrap_or(false) }
1274}
1275
1276unsafe extern "C" fn srv_get_held_item_nbt(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1277    unsafe { owned(bridge!("getHeldItemNbt", [S(player)])) }
1278}
1279
1280unsafe extern "C" fn srv_set_held_item_nbt(
1281    _ctx: *mut c_void,
1282    player: YogStr,
1283    snbt: YogStr,
1284) -> bool {
1285    unsafe { bridge!("setHeldItemNbt", [S(player), S(snbt)]).unwrap_or(false) }
1286}
1287
1288unsafe extern "C" fn srv_get_offhand_item_nbt(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1289    unsafe { owned(bridge!("getOffhandItemNbt", [S(player)])) }
1290}
1291
1292unsafe extern "C" fn srv_set_offhand_item_nbt(
1293    _ctx: *mut c_void,
1294    player: YogStr,
1295    snbt: YogStr,
1296) -> bool {
1297    unsafe { bridge!("setOffhandItemNbt", [S(player), S(snbt)]).unwrap_or(false) }
1298}
1299
1300unsafe extern "C" fn srv_get_slot_item(
1301    _ctx: *mut c_void,
1302    player: YogStr,
1303    slot: u32,
1304) -> YogOwnedStr {
1305    unsafe { owned(bridge!("getSlotItem", [S(player), I(slot as i32)])) }
1306}
1307
1308unsafe extern "C" fn srv_set_slot_item(
1309    _ctx: *mut c_void,
1310    player: YogStr,
1311    slot: u32,
1312    item_id: YogStr,
1313    count: u32,
1314    snbt: YogStr,
1315) -> bool {
1316    unsafe {
1317        bridge!(
1318            "setSlotItem",
1319            [
1320                S(player),
1321                I(slot as i32),
1322                S(item_id),
1323                I(count as i32),
1324                S(snbt)
1325            ]
1326        )
1327        .unwrap_or(false)
1328    }
1329}
1330
1331// ── ABI minor 14 — low-level GPU pipeline ────────────────────────────────────
1332//
1333// All raw GL calls go through `glow::Context` stored in GL.
1334// `draw2d_*` functions still call JNI (NativeDraw) for MC text/texture rendering.
1335// Everything is called on the render thread — no synchronization needed.
1336
1337// ── helpers ───────────────────────────────────────────────────────────────────
1338
1339fn gl_draw_mode(mode: u8) -> u32 {
1340    match mode {
1341        1 => glow::LINES,
1342        2 => glow::LINE_STRIP,
1343        3 => glow::TRIANGLE_STRIP,
1344        4 => glow::TRIANGLE_FAN,
1345        _ => glow::TRIANGLES,
1346    }
1347}
1348
1349fn gl_attr_type(dtype: u8) -> u32 {
1350    match dtype {
1351        1 => glow::UNSIGNED_BYTE,
1352        2 => glow::INT,
1353        3 => glow::UNSIGNED_INT,
1354        _ => glow::FLOAT,
1355    }
1356}
1357
1358unsafe fn compile_shader(gl: &glow::Context, stage: u32, src: &str) -> Option<glow::NativeShader> {
1359    unsafe {
1360        let sh = gl.create_shader(stage).ok()?;
1361        gl.shader_source(sh, src);
1362        gl.compile_shader(sh);
1363        if !gl.get_shader_compile_status(sh) {
1364            yog_logging::error!("yog-gfx shader compile: {}", gl.get_shader_info_log(sh));
1365            gl.delete_shader(sh);
1366            return None;
1367        }
1368        Some(sh)
1369    }
1370}
1371
1372// ── GPU buffers ───────────────────────────────────────────────────────────────
1373
1374unsafe extern "C" fn gfx_buf_create() -> u32 {
1375    unsafe {
1376        let Some(g) = GL.get() else { return 0 };
1377        g.0.create_buffer().map(|b| b.0.get()).unwrap_or(0)
1378    }
1379}
1380
1381unsafe extern "C" fn gfx_buf_delete(handle: u32) {
1382    unsafe {
1383        let Some(g) = GL.get() else { return };
1384        let Some(n) = NonZeroU32::new(handle) else {
1385            return;
1386        };
1387        g.0.delete_buffer(glow::NativeBuffer(n));
1388    }
1389}
1390
1391unsafe extern "C" fn gfx_buf_data(handle: u32, bytes: *const u8, len: u32, dynamic: bool) {
1392    unsafe {
1393        let Some(g) = GL.get() else { return };
1394        let Some(n) = NonZeroU32::new(handle) else {
1395            return;
1396        };
1397        let gl = &g.0;
1398        let data = std::slice::from_raw_parts(bytes, len as usize);
1399        let usage = if dynamic {
1400            glow::DYNAMIC_DRAW
1401        } else {
1402            glow::STATIC_DRAW
1403        };
1404        gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
1405        gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, data, usage);
1406        gl.bind_buffer(glow::ARRAY_BUFFER, None);
1407    }
1408}
1409
1410unsafe extern "C" fn gfx_buf_subdata(handle: u32, offset: u32, bytes: *const u8, len: u32) {
1411    unsafe {
1412        let Some(g) = GL.get() else { return };
1413        let Some(n) = NonZeroU32::new(handle) else {
1414            return;
1415        };
1416        let gl = &g.0;
1417        let data = std::slice::from_raw_parts(bytes, len as usize);
1418        gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
1419        gl.buffer_sub_data_u8_slice(glow::ARRAY_BUFFER, offset as i32, data);
1420        gl.bind_buffer(glow::ARRAY_BUFFER, None);
1421    }
1422}
1423
1424// ── Vertex arrays ─────────────────────────────────────────────────────────────
1425
1426unsafe extern "C" fn gfx_vao_create() -> u32 {
1427    unsafe {
1428        let Some(g) = GL.get() else { return 0 };
1429        g.0.create_vertex_array().map(|v| v.0.get()).unwrap_or(0)
1430    }
1431}
1432
1433unsafe extern "C" fn gfx_vao_delete(handle: u32) {
1434    unsafe {
1435        let Some(g) = GL.get() else { return };
1436        let Some(n) = NonZeroU32::new(handle) else {
1437            return;
1438        };
1439        g.0.delete_vertex_array(glow::NativeVertexArray(n));
1440    }
1441}
1442
1443unsafe extern "C" fn gfx_vao_attrib(
1444    vao: u32,
1445    vbo: u32,
1446    index: u32,
1447    components: u8,
1448    dtype: u8,
1449    normalized: bool,
1450    stride: u32,
1451    offset: u32,
1452) {
1453    unsafe {
1454        let Some(g) = GL.get() else { return };
1455        let (Some(vn), Some(bn)) = (NonZeroU32::new(vao), NonZeroU32::new(vbo)) else {
1456            return;
1457        };
1458        let gl = &g.0;
1459        gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
1460        gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(bn)));
1461        let gl_type = gl_attr_type(dtype);
1462        if dtype == 2 || dtype == 3 {
1463            gl.vertex_attrib_pointer_i32(
1464                index,
1465                components as i32,
1466                gl_type,
1467                stride as i32,
1468                offset as i32,
1469            );
1470        } else {
1471            gl.vertex_attrib_pointer_f32(
1472                index,
1473                components as i32,
1474                gl_type,
1475                normalized,
1476                stride as i32,
1477                offset as i32,
1478            );
1479        }
1480        gl.enable_vertex_attrib_array(index);
1481        gl.bind_vertex_array(None);
1482    }
1483}
1484
1485unsafe extern "C" fn gfx_vao_set_ebo(vao: u32, ebo: u32) {
1486    unsafe {
1487        let Some(g) = GL.get() else { return };
1488        let (Some(vn), Some(en)) = (NonZeroU32::new(vao), NonZeroU32::new(ebo)) else {
1489            return;
1490        };
1491        let gl = &g.0;
1492        gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
1493        gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(glow::NativeBuffer(en)));
1494        gl.bind_vertex_array(None);
1495    }
1496}
1497
1498// ── Shader programs ───────────────────────────────────────────────────────────
1499
1500/// Returns a path under `~/.cache/yog/shaders/<hash>.ysc` for the given GLSL source pair,
1501/// creating the directory if needed.  Returns `None` if the home directory is unknown.
1502fn shader_cache_path(vert: &str, frag: &str) -> Option<PathBuf> {
1503    use std::hash::{Hash, Hasher};
1504    let mut h = std::collections::hash_map::DefaultHasher::new();
1505    vert.hash(&mut h);
1506    frag.hash(&mut h);
1507    let hash = h.finish();
1508    let dir = std::env::var("HOME")
1509        .map(|home| {
1510            PathBuf::from(home)
1511                .join(".cache")
1512                .join("yog")
1513                .join("shaders")
1514        })
1515        .ok()?;
1516    std::fs::create_dir_all(&dir).ok()?;
1517    Some(dir.join(format!("{hash:016x}.ysc")))
1518}
1519
1520/// Try restoring a program from a binary blob (`[4 LE bytes: GL format][binary…]`).
1521/// Returns `Some(handle)` if the driver accepts the binary, `None` otherwise.
1522///
1523/// Uses `glProgramBinary` (GL 4.1 / ARB_get_program_binary) via the raw pointer
1524/// captured in `nativeGlInit`.  Returns `None` if the extension is unavailable.
1525unsafe fn load_shader_binary(gl: &glow::Context, data: &[u8]) -> Option<glow::NativeProgram> {
1526    unsafe {
1527        if data.len() < 4 {
1528            return None;
1529        }
1530        type ProgramBinaryFn = unsafe extern "system" fn(u32, u32, *const c_void, i32);
1531        let fn_ptr = (*GL_PROGRAM_BINARY.get()?)?;
1532        let program_binary: ProgramBinaryFn = std::mem::transmute(fn_ptr);
1533
1534        let fmt = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
1535        let prog = gl.create_program().ok()?;
1536        program_binary(
1537            prog.0.get(),
1538            fmt,
1539            data[4..].as_ptr() as *const c_void,
1540            (data.len() - 4) as i32,
1541        );
1542        if gl.get_program_link_status(prog) {
1543            Some(prog)
1544        } else {
1545            gl.delete_program(prog);
1546            None
1547        }
1548    }
1549}
1550
1551/// Read the compiled binary of a linked program.  Returns empty `Vec` if unsupported.
1552unsafe fn get_shader_binary(prog: glow::NativeProgram) -> (Vec<u8>, u32) {
1553    unsafe {
1554        type GetProgramivFn = unsafe extern "system" fn(u32, u32, *mut i32);
1555        type GetProgramBinaryFn =
1556            unsafe extern "system" fn(u32, i32, *mut i32, *mut u32, *mut c_void);
1557
1558        let Some(get_iv_raw) = GL_GET_PROGRAM_IV.get().and_then(|v| *v) else {
1559            return (vec![], 0);
1560        };
1561        let Some(get_bin_raw) = GL_GET_PROGRAM_BINARY.get().and_then(|v| *v) else {
1562            return (vec![], 0);
1563        };
1564        let get_program_iv: GetProgramivFn = std::mem::transmute(get_iv_raw);
1565        let get_program_binary: GetProgramBinaryFn = std::mem::transmute(get_bin_raw);
1566
1567        // Query binary size via glGetProgramiv(GL_PROGRAM_BINARY_LENGTH).
1568        const PROGRAM_BINARY_LENGTH: u32 = 0x8741;
1569        let mut size: i32 = 0;
1570        get_program_iv(prog.0.get(), PROGRAM_BINARY_LENGTH, &mut size);
1571        if size <= 0 {
1572            return (vec![], 0);
1573        }
1574
1575        let mut buf = vec![0u8; size as usize];
1576        let mut actual_len: i32 = 0;
1577        let mut fmt: u32 = 0;
1578        get_program_binary(
1579            prog.0.get(),
1580            size,
1581            &mut actual_len,
1582            &mut fmt,
1583            buf.as_mut_ptr() as *mut c_void,
1584        );
1585        buf.truncate(actual_len.max(0) as usize);
1586        (buf, fmt)
1587    }
1588}
1589
1590unsafe extern "C" fn gfx_prog_create(vert: YogStr, frag: YogStr, out: *mut u32) -> bool {
1591    unsafe {
1592        let Some(g) = GL.get() else { return false };
1593        let gl = &g.0;
1594        let vert_s = vert.as_str();
1595        let frag_s = frag.as_str();
1596
1597        // Fast path: binary shader cache — avoids GLSL re-compilation on subsequent launches.
1598        let cache_path = shader_cache_path(vert_s, frag_s);
1599        if let Some(ref path) = cache_path
1600            && let Ok(data) = std::fs::read(path)
1601        {
1602            if let Some(prog) = load_shader_binary(gl, &data) {
1603                *out = prog.0.get();
1604                return true;
1605            }
1606            // Cache stale (driver updated?); remove and fall through to GLSL compile.
1607            let _ = std::fs::remove_file(path);
1608        }
1609
1610        // GLSL compile path.
1611        let vs = match compile_shader(gl, glow::VERTEX_SHADER, vert_s) {
1612            Some(s) => s,
1613            None => return false,
1614        };
1615        let fs = match compile_shader(gl, glow::FRAGMENT_SHADER, frag_s) {
1616            Some(s) => s,
1617            None => {
1618                gl.delete_shader(vs);
1619                return false;
1620            }
1621        };
1622        let prog = match gl.create_program() {
1623            Ok(p) => p,
1624            Err(e) => {
1625                yog_logging::error!("yog-gfx: create_program: {}", e);
1626                gl.delete_shader(vs);
1627                gl.delete_shader(fs);
1628                return false;
1629            }
1630        };
1631        gl.attach_shader(prog, vs);
1632        gl.attach_shader(prog, fs);
1633        gl.link_program(prog);
1634        gl.detach_shader(prog, vs);
1635        gl.detach_shader(prog, fs);
1636        gl.delete_shader(vs);
1637        gl.delete_shader(fs);
1638        if !gl.get_program_link_status(prog) {
1639            yog_logging::error!("yog-gfx: shader link: {}", gl.get_program_info_log(prog));
1640            gl.delete_program(prog);
1641            return false;
1642        }
1643
1644        // Persist binary so the next launch skips GLSL compilation entirely.
1645        if let Some(ref path) = cache_path {
1646            let (binary, fmt) = get_shader_binary(prog);
1647            if !binary.is_empty() {
1648                let mut blob = fmt.to_le_bytes().to_vec();
1649                blob.extend_from_slice(&binary);
1650                let _ = std::fs::write(path, &blob);
1651            }
1652        }
1653
1654        *out = prog.0.get();
1655        true
1656    }
1657}
1658
1659unsafe extern "C" fn gfx_prog_delete(handle: u32) {
1660    unsafe {
1661        let Some(g) = GL.get() else { return };
1662        let Some(n) = NonZeroU32::new(handle) else {
1663            return;
1664        };
1665        g.0.delete_program(glow::NativeProgram(n));
1666    }
1667}
1668
1669macro_rules! with_prog {
1670    ($handle:expr_2021, |$gl:ident, $prog:ident, $loc:ident ($name:expr_2021)| $body:expr_2021) => {{
1671        let Some(g) = GL.get() else { return };
1672        let Some(n) = NonZeroU32::new($handle) else {
1673            return;
1674        };
1675        let $gl = &g.0;
1676        let $prog = glow::NativeProgram(n);
1677        $gl.use_program(Some($prog));
1678        let $loc = $gl.get_uniform_location($prog, $name.as_str());
1679        $body
1680    }};
1681}
1682
1683unsafe extern "C" fn gfx_prog_uniform_1i(prog: u32, name: YogStr, v: i32) {
1684    unsafe {
1685        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_i32(loc.as_ref(), v));
1686    }
1687}
1688unsafe extern "C" fn gfx_prog_uniform_1f(prog: u32, name: YogStr, v: f32) {
1689    unsafe {
1690        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_f32(loc.as_ref(), v));
1691    }
1692}
1693unsafe extern "C" fn gfx_prog_uniform_2f(prog: u32, name: YogStr, x: f32, y: f32) {
1694    unsafe {
1695        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_2_f32(
1696            loc.as_ref(),
1697            x,
1698            y
1699        ));
1700    }
1701}
1702unsafe extern "C" fn gfx_prog_uniform_3f(prog: u32, name: YogStr, x: f32, y: f32, z: f32) {
1703    unsafe {
1704        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_3_f32(
1705            loc.as_ref(),
1706            x,
1707            y,
1708            z
1709        ));
1710    }
1711}
1712unsafe extern "C" fn gfx_prog_uniform_4f(prog: u32, name: YogStr, x: f32, y: f32, z: f32, w: f32) {
1713    unsafe {
1714        with_prog!(prog, |gl, _p, loc(name)| gl.uniform_4_f32(
1715            loc.as_ref(),
1716            x,
1717            y,
1718            z,
1719            w
1720        ));
1721    }
1722}
1723unsafe extern "C" fn gfx_prog_uniform_mat4(prog: u32, name: YogStr, col_major: *const f32) {
1724    unsafe {
1725        with_prog!(prog, |gl, _p, loc(name)| {
1726            let data = std::slice::from_raw_parts(col_major, 16);
1727            gl.uniform_matrix_4_f32_slice(loc.as_ref(), false, data);
1728        });
1729    }
1730}
1731
1732// ── Textures ──────────────────────────────────────────────────────────────────
1733
1734unsafe extern "C" fn gfx_tex_create(w: u32, h: u32, rgba: *const u8, linear: bool) -> u32 {
1735    unsafe {
1736        let Some(g) = GL.get() else { return 0 };
1737        let gl = &g.0;
1738        let tex = match gl.create_texture() {
1739            Ok(t) => t,
1740            Err(_) => return 0,
1741        };
1742        gl.bind_texture(glow::TEXTURE_2D, Some(tex));
1743        let filter = if linear { glow::LINEAR } else { glow::NEAREST };
1744        gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, filter as i32);
1745        gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, filter as i32);
1746        gl.tex_parameter_i32(
1747            glow::TEXTURE_2D,
1748            glow::TEXTURE_WRAP_S,
1749            glow::CLAMP_TO_EDGE as i32,
1750        );
1751        gl.tex_parameter_i32(
1752            glow::TEXTURE_2D,
1753            glow::TEXTURE_WRAP_T,
1754            glow::CLAMP_TO_EDGE as i32,
1755        );
1756        let pixels = std::slice::from_raw_parts(rgba, (w * h * 4) as usize);
1757        // The game leaves its own unpacking (row length, skips) set from its
1758        // atlas uploads: read with those, a tight buffer is overrun.
1759        unpack_tightly(gl);
1760        gl.tex_image_2d(
1761            glow::TEXTURE_2D,
1762            0,
1763            glow::RGBA8 as i32,
1764            w as i32,
1765            h as i32,
1766            0,
1767            glow::RGBA,
1768            glow::UNSIGNED_BYTE,
1769            glow::PixelUnpackData::Slice(Some(pixels)),
1770        );
1771        gl.bind_texture(glow::TEXTURE_2D, None);
1772        tex.0.get()
1773    }
1774}
1775
1776/// Pixel unpacking as a tightly packed client buffer needs it.
1777unsafe fn unpack_tightly(gl: &glow::Context) {
1778    unsafe {
1779        gl.bind_buffer(glow::PIXEL_UNPACK_BUFFER, None);
1780        gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, 0);
1781        gl.pixel_store_i32(glow::UNPACK_SKIP_ROWS, 0);
1782        gl.pixel_store_i32(glow::UNPACK_SKIP_PIXELS, 0);
1783        gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 4);
1784    }
1785}
1786
1787unsafe extern "C" fn gfx_tex_delete(handle: u32) {
1788    unsafe {
1789        let Some(g) = GL.get() else { return };
1790        let Some(n) = NonZeroU32::new(handle) else {
1791            return;
1792        };
1793        g.0.delete_texture(glow::NativeTexture(n));
1794    }
1795}
1796
1797unsafe extern "C" fn gfx_tex_bind(unit: u32, handle: u32) {
1798    unsafe {
1799        let Some(g) = GL.get() else { return };
1800        let gl = &g.0;
1801        gl.active_texture(glow::TEXTURE0 + unit);
1802        match NonZeroU32::new(handle) {
1803            Some(n) => gl.bind_texture(glow::TEXTURE_2D, Some(glow::NativeTexture(n))),
1804            None => gl.bind_texture(glow::TEXTURE_2D, None),
1805        }
1806    }
1807}
1808
1809unsafe extern "C" fn gfx_tex_from_mc(id: YogStr) -> u32 {
1810    unsafe { host!("dev/yog/NativeDraw", "getMcTextureId", [S(id)]).map_or(0, |id: i32| id as u32) }
1811}
1812
1813// ── Draw calls ────────────────────────────────────────────────────────────────
1814
1815unsafe extern "C" fn gfx_draw_arrays(vao: u32, prog: u32, mode: u8, first: u32, count: u32) {
1816    unsafe {
1817        let Some(g) = GL.get() else { return };
1818        let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else {
1819            return;
1820        };
1821        let gl = &g.0;
1822        gl.use_program(Some(glow::NativeProgram(pn)));
1823        gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
1824        gl.draw_arrays(gl_draw_mode(mode), first as i32, count as i32);
1825        gl.bind_vertex_array(None);
1826    }
1827}
1828
1829unsafe extern "C" fn gfx_draw_elements(
1830    vao: u32,
1831    ebo: u32,
1832    prog: u32,
1833    mode: u8,
1834    count: u32,
1835    u32_idx: bool,
1836) {
1837    unsafe {
1838        let Some(g) = GL.get() else { return };
1839        let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else {
1840            return;
1841        };
1842        let gl = &g.0;
1843        gl.use_program(Some(glow::NativeProgram(pn)));
1844        gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
1845        // EBO is stored in the VAO; ebo param is informational for safety but not re-bound here.
1846        let _ = ebo;
1847        let idx_type = if u32_idx {
1848            glow::UNSIGNED_INT
1849        } else {
1850            glow::UNSIGNED_SHORT
1851        };
1852        gl.draw_elements(gl_draw_mode(mode), count as i32, idx_type, 0);
1853        gl.bind_vertex_array(None);
1854    }
1855}
1856
1857// ── Render state ──────────────────────────────────────────────────────────────
1858
1859unsafe extern "C" fn gfx_set_blend(enabled: bool, src: u32, dst: u32) {
1860    unsafe {
1861        let Some(g) = GL.get() else { return };
1862        let gl = &g.0;
1863        if enabled {
1864            gl.enable(glow::BLEND);
1865            gl.blend_func(src, dst);
1866        } else {
1867            gl.disable(glow::BLEND);
1868        }
1869    }
1870}
1871
1872unsafe extern "C" fn gfx_set_depth(test: bool, write: bool) {
1873    unsafe {
1874        let Some(g) = GL.get() else { return };
1875        let gl = &g.0;
1876        if test {
1877            gl.enable(glow::DEPTH_TEST);
1878        } else {
1879            gl.disable(glow::DEPTH_TEST);
1880        }
1881        gl.depth_mask(write);
1882        // Disable face culling: our 2D quads use CW winding (back-face) due to y-flip.
1883        if !test {
1884            gl.disable(glow::CULL_FACE);
1885        }
1886    }
1887}
1888
1889unsafe extern "C" fn gfx_set_scissor(x: i32, y: i32, w: i32, h: i32) {
1890    unsafe {
1891        let Some(g) = GL.get() else { return };
1892        let gl = &g.0;
1893        gl.enable(glow::SCISSOR_TEST);
1894        gl.scissor(x, y, w, h);
1895    }
1896}
1897
1898unsafe extern "C" fn gfx_clear_scissor() {
1899    unsafe {
1900        let Some(g) = GL.get() else { return };
1901        g.0.disable(glow::SCISSOR_TEST);
1902    }
1903}
1904
1905unsafe extern "C" fn gfx_set_viewport(x: i32, y: i32, w: i32, h: i32) {
1906    unsafe {
1907        let Some(g) = GL.get() else { return };
1908        g.0.viewport(x, y, w, h);
1909    }
1910}
1911
1912// ── 2D convenience (JNI — uses MC's DrawContext / text renderer) ──────────────
1913
1914unsafe extern "C" fn gfx_draw2d_rect(x1: f32, y1: f32, x2: f32, y2: f32, color: u32) {
1915    unsafe {
1916        let _: Option<()> = host!(
1917            "dev/yog/NativeDraw",
1918            "drawRect",
1919            [F(x1), F(y1), F(x2), F(y2), I(color as i32)]
1920        );
1921    }
1922}
1923
1924unsafe extern "C" fn gfx_draw2d_gradient(
1925    x1: f32,
1926    y1: f32,
1927    x2: f32,
1928    y2: f32,
1929    top: u32,
1930    bottom: u32,
1931) {
1932    unsafe {
1933        let _: Option<()> = host!(
1934            "dev/yog/NativeDraw",
1935            "drawGradientRect",
1936            [F(x1), F(y1), F(x2), F(y2), I(top as i32), I(bottom as i32)]
1937        );
1938    }
1939}
1940
1941unsafe extern "C" fn gfx_draw2d_text(text: YogStr, x: f32, y: f32, color: u32, shadow: bool) {
1942    unsafe {
1943        let _: Option<()> = host!(
1944            "dev/yog/NativeDraw",
1945            "drawText",
1946            [S(text), F(x), F(y), I(color as i32), Z(shadow)]
1947        );
1948    }
1949}
1950
1951unsafe extern "C" fn gfx_draw2d_text_font(
1952    text: YogStr,
1953    font: YogStr,
1954    x: f32,
1955    y: f32,
1956    color: u32,
1957    shadow: bool,
1958) {
1959    unsafe {
1960        let _: Option<()> = host!(
1961            "dev/yog/NativeDraw",
1962            "drawTextFont",
1963            [S(text), S(font), F(x), F(y), I(color as i32), Z(shadow)]
1964        );
1965    }
1966}
1967
1968unsafe extern "C" fn gfx_draw2d_text_scaled(
1969    text: YogStr,
1970    font: YogStr,
1971    x: f32,
1972    y: f32,
1973    scale: f32,
1974    color: u32,
1975    shadow: bool,
1976) {
1977    unsafe {
1978        let _: Option<()> = host!(
1979            "dev/yog/NativeDraw",
1980            "drawTextScaled",
1981            [S(text), S(font), F(x), F(y), F(scale), I(color as i32), Z(shadow)]
1982        );
1983    }
1984}
1985
1986unsafe extern "C" fn gfx_draw2d_blocks(blocks: YogStr, x: f32, y: f32, w: f32, h: f32, yaw: f32, pitch: f32) {
1987    if w <= 0.0 || h <= 0.0 {
1988        return;
1989    }
1990    unsafe {
1991        let _: Option<()> = host!(
1992            "dev/yog/NativeDraw",
1993            "drawBlocks",
1994            [S(blocks), F(x), F(y), F(w), F(h), F(yaw), F(pitch)]
1995        );
1996    }
1997}
1998
1999unsafe extern "C" fn gfx_text_width(text: YogStr, font: YogStr) -> f32 {
2000    unsafe { host!("dev/yog/NativeDraw", "textWidth", [S(text), S(font)]).unwrap_or(0.0) }
2001}
2002
2003unsafe extern "C" fn gfx_draw2d_item(id: YogStr, x: f32, y: f32, size: f32) {
2004    unsafe {
2005        let _: Option<()> = host!(
2006            "dev/yog/NativeDraw",
2007            "drawItem",
2008            [S(id), F(x), F(y), F(size)]
2009        );
2010    }
2011}
2012
2013// ── Static GFX function table (function pointers only — per-frame data filled at call time) ──
2014
2015static GFX_FN_TABLE: YogGfxApi = YogGfxApi {
2016    // Per-frame fields zeroed in the static; actual values are set on the stack per render call.
2017    screen_w: 0,
2018    screen_h: 0,
2019    delta_tick: 0.0,
2020    scale_factor: 1.0,
2021    view_proj: [0.0; 16],
2022    camera_pos: [0.0; 3],
2023    player_pos: [0.0; 3],
2024    _pad1: 0.0,
2025    buf_create: gfx_buf_create,
2026    buf_delete: gfx_buf_delete,
2027    buf_data: gfx_buf_data,
2028    buf_subdata: gfx_buf_subdata,
2029    vao_create: gfx_vao_create,
2030    vao_delete: gfx_vao_delete,
2031    vao_attrib: gfx_vao_attrib,
2032    vao_set_ebo: gfx_vao_set_ebo,
2033    prog_create: gfx_prog_create,
2034    prog_delete: gfx_prog_delete,
2035    prog_uniform_1i: gfx_prog_uniform_1i,
2036    prog_uniform_1f: gfx_prog_uniform_1f,
2037    prog_uniform_2f: gfx_prog_uniform_2f,
2038    prog_uniform_3f: gfx_prog_uniform_3f,
2039    prog_uniform_4f: gfx_prog_uniform_4f,
2040    prog_uniform_mat4: gfx_prog_uniform_mat4,
2041    tex_create: gfx_tex_create,
2042    tex_delete: gfx_tex_delete,
2043    tex_bind: gfx_tex_bind,
2044    tex_from_mc: gfx_tex_from_mc,
2045    draw_arrays: gfx_draw_arrays,
2046    draw_elements: gfx_draw_elements,
2047    set_blend: gfx_set_blend,
2048    set_depth: gfx_set_depth,
2049    set_scissor: gfx_set_scissor,
2050    clear_scissor: gfx_clear_scissor,
2051    set_viewport: gfx_set_viewport,
2052    draw2d_rect: gfx_draw2d_rect,
2053    draw2d_gradient: gfx_draw2d_gradient,
2054    draw2d_text: gfx_draw2d_text,
2055    draw2d_item: gfx_draw2d_item,
2056    draw2d_text_font: gfx_draw2d_text_font,
2057    text_width: gfx_text_width,
2058    draw2d_image: images::gfx_draw2d_image,
2059    image_size: images::gfx_image_size,
2060    draw2d_svg: svg::gfx_draw2d_svg,
2061    draw2d_entity: svg::gfx_draw2d_entity,
2062    draw2d_text_scaled: gfx_draw2d_text_scaled,
2063    draw2d_blocks: gfx_draw2d_blocks,
2064};
2065
2066// ── YogApi registration functions ─────────────────────────────────────────────
2067//
2068// ctx is *const RwLock<RuntimeHandlers> (cast from *mut c_void) — see
2069// `current_registration()` for how each entry gets tagged with the
2070// `LoadedModule` that's registering it.
2071
2072macro_rules! api_event {
2073    ($name:ident, $field:ident, $fn_ty:ty) => {
2074        unsafe extern "C" fn $name(ctx: *mut c_void, ud: *mut c_void, h: $fn_ty) {
2075            unsafe {
2076                let mut handlers = handlers_mut(ctx);
2077                handlers.$field.push((current_registration(), ud, h));
2078            }
2079        }
2080    };
2081}
2082
2083api_event!(api_on_block_break, block_break, YogBlockBreakFn);
2084api_event!(api_on_chat, chat, YogChatFn);
2085api_event!(api_on_player_join, player_join, YogPlayerFn);
2086api_event!(api_on_player_leave, player_leave, YogPlayerFn);
2087api_event!(api_on_use_item, use_item, YogUseItemFn);
2088api_event!(api_on_use_block, use_block, YogUseBlockFn);
2089api_event!(api_on_attack_entity, attack_entity, YogAttackEntityFn);
2090api_event!(api_on_entity_damage, entity_damage, YogEntityDamageFn);
2091api_event!(api_on_entity_death, entity_death, YogEntityDeathFn);
2092api_event!(api_on_entity_spawn, entity_spawn, YogEntitySpawnFn);
2093api_event!(
2094    api_on_player_place_block,
2095    player_place_block,
2096    YogPlaceBlockFn
2097);
2098api_event!(api_on_player_death, player_death, YogPlayerDeathFn);
2099api_event!(api_on_player_respawn, player_respawn, YogPlayerRespawnFn);
2100api_event!(api_on_advancement, advancement, YogAdvancementFn);
2101api_event!(api_on_entity_interact, entity_interact, YogEntityInteractFn);
2102api_event!(api_on_item_craft, item_craft, YogCraftFn);
2103api_event!(api_on_machine_craft, machine_craft, YogMachineCraftFn);
2104api_event!(api_on_explosion, explosion, YogExplosionFn);
2105api_event!(api_on_item_pickup, item_pickup, YogItemPickupFn);
2106api_event!(api_on_item_insert, item_insert, YogItemInsertFn);
2107api_event!(api_on_player_move, player_move, YogPlayerMoveFn);
2108api_event!(api_on_container_open, container_open, YogContainerOpenFn);
2109api_event!(api_on_container_close, container_close, YogContainerCloseFn);
2110api_event!(api_on_projectile_hit, projectile_hit, YogProjectileHitFn);
2111api_event!(api_on_client_tick, client_tick, YogClientFn);
2112api_event!(api_on_hud_render, hud_render, YogHudRenderFn);
2113api_event!(api_on_world_render, world_render, YogWorldRenderFn);
2114api_event!(api_on_key_press, key_press, YogKeyPressFn);
2115api_event!(api_on_screen_open, screen_open, YogScreenFn);
2116api_event!(api_on_screen_close, screen_close, YogScreenFn);
2117api_event!(api_on_server_tick, server_tick, YogServerFn);
2118api_event!(api_on_server_started, server_started, YogServerFn);
2119api_event!(api_on_server_stopping, server_stopping, YogServerFn);
2120
2121unsafe extern "C" fn api_on_packet(
2122    ctx: *mut c_void,
2123    channel: YogStr,
2124    ud: *mut c_void,
2125    h: YogPacketFn,
2126) {
2127    unsafe {
2128        let mut handlers = handlers_mut(ctx);
2129        handlers
2130            .packets
2131            .insert(channel.as_str().to_owned(), (current_registration(), ud, h));
2132    }
2133}
2134
2135unsafe extern "C" fn api_on_client_packet(
2136    ctx: *mut c_void,
2137    channel: YogStr,
2138    ud: *mut c_void,
2139    h: YogPacketFn,
2140) {
2141    unsafe {
2142        let mut handlers = handlers_mut(ctx);
2143        handlers
2144            .client_packets
2145            .insert(channel.as_str().to_owned(), (current_registration(), ud, h));
2146    }
2147}
2148
2149unsafe extern "C" fn api_register_command(
2150    ctx: *mut c_void,
2151    name: YogStr,
2152    ud: *mut c_void,
2153    h: YogCommandFn,
2154) {
2155    unsafe {
2156        let mut handlers = handlers_mut(ctx);
2157        handlers
2158            .commands
2159            .entry(name.as_str().to_owned())
2160            .or_default()
2161            .push((current_registration(), None, ud, h));
2162    }
2163}
2164
2165unsafe extern "C" fn api_register_typed_command(
2166    ctx: *mut c_void,
2167    name: YogStr,
2168    schema: YogStr,
2169    ud: *mut c_void,
2170    h: YogCommandFn,
2171) {
2172    unsafe {
2173        let mut handlers = handlers_mut(ctx);
2174        let n = name.as_str().to_owned();
2175        handlers.commands.entry(n).or_default().push((
2176            current_registration(),
2177            Some(schema.as_str().to_owned()),
2178            ud,
2179            h,
2180        ));
2181    }
2182}
2183
2184/// The handlers a registration call writes into: `ctx` is the
2185/// `RwLock<RuntimeHandlers>` the runtime handed the mod's `yog_mod_register`.
2186/// A poisoned lock (a mod panicked mid-registration) is taken as it is —
2187/// one mod's panic doesn't stop the others registering.
2188///
2189/// # Safety
2190/// `ctx` must be that registration context.
2191unsafe fn handlers_mut<'a>(ctx: *mut c_void) -> std::sync::RwLockWriteGuard<'a, RuntimeHandlers> {
2192    unsafe { (*(ctx as *const RwLock<RuntimeHandlers>)).write().unwrap_or_else(|e| e.into_inner()) }
2193}
2194
2195/// `register_content`: content of `kind` named `id`, its definition a Yog
2196/// Data blob — the one way mods hand the runtime what the hosts register.
2197unsafe extern "C" fn api_register_content(ctx: *mut c_void, kind: YogStr, id: YogStr, data: *const u8, len: usize) {
2198    unsafe {
2199        let kind = kind.as_str();
2200        let id = id.as_str().to_owned();
2201        let bytes = if data.is_null() || len == 0 { &[][..] } else { std::slice::from_raw_parts(data, len) };
2202        // Borrowed: strings stay in `bytes`, only what's kept is copied.
2203        let arena = yog_data::Bump::new();
2204        let value = match yog_data::binary::decode_ref(bytes, &arena) {
2205            Ok(v) => v,
2206            Err(e) => {
2207                yog_logging::warn!("{kind} {id}: not Yog Data: {e}");
2208                return;
2209            }
2210        };
2211        register_content(&mut handlers_mut(ctx), kind, id, &value);
2212    }
2213}
2214
2215/// Stores content of `kind` (see `register_content` in yog-abi).
2216fn register_content(h: &mut RuntimeHandlers, kind: &str, id: String, value: &yog_data::ValueRef) {
2217    *h.content_blob.get_mut().unwrap_or_else(|e| e.into_inner()) = None;
2218    fn read<T: yog_data::Schema>(kind: &str, id: &str, v: &yog_data::ValueRef) -> Option<T> {
2219        match yog_data::read_ref_value::<T>(v) {
2220            Ok(value) => Some(value),
2221            Err(problems) => {
2222                let list: Vec<String> = problems.iter().map(|p| format!("{}: {}", p.path, p.message)).collect();
2223                yog_logging::warn!("{kind} {id}: {}", list.join("; "));
2224                None
2225            }
2226        }
2227    }
2228    let none_if_empty = |s: &mut Option<String>| {
2229        if s.as_deref() == Some("") {
2230            *s = None;
2231        }
2232    };
2233    match kind {
2234        "item" => {
2235            if let Some(mut d) = read::<ItemDef>(kind, &id, value) {
2236                none_if_empty(&mut d.name);
2237                none_if_empty(&mut d.tooltip);
2238                h.items.push(d);
2239            }
2240        }
2241        "block" => {
2242            if let Some(mut d) = read::<BlockDef>(kind, &id, value) {
2243                none_if_empty(&mut d.name);
2244                none_if_empty(&mut d.sound);
2245                none_if_empty(&mut d.inventory_id);
2246                h.blocks.push(d);
2247            }
2248        }
2249        "entity" => {
2250            if read::<yog_registry::EntityDef>(kind, &id, value).is_some() {
2251                h.entities.push(value.to_value());
2252            }
2253        }
2254        "attribute" => {
2255            if read::<yog_registry::AttributeDef>(kind, &id, value).is_some() {
2256                h.attributes.push(value.to_value());
2257            }
2258        }
2259        "effect" => {
2260            if read::<yog_registry::EffectDef>(kind, &id, value).is_some() {
2261                h.effects.push(value.to_value());
2262            }
2263        }
2264        "potion" => {
2265            if read::<yog_registry::PotionDef>(kind, &id, value).is_some() {
2266                h.potions.push(value.to_value());
2267            }
2268        }
2269        "biome_feature" => {
2270            if let Some(f) = read::<yog_registry::BiomeFeature>(kind, &id, value) {
2271                h.biome_features.push(f);
2272            }
2273        }
2274        "tool_material" => {
2275            if let Some(m) = read::<yog_registry::ToolMaterial>(kind, &id, value) {
2276                h.tool_materials.insert(m.id.clone(), m);
2277            }
2278        }
2279        "armor_material" => {
2280            if let Some(m) = read::<yog_registry::ArmorMaterial>(kind, &id, value) {
2281                h.armor_materials.insert(m.id.clone(), m);
2282            }
2283        }
2284        "sound_group" => {
2285            if let Some(g) = read::<yog_registry::SoundGroup>(kind, &id, value) {
2286                h.sound_groups.insert(g.id.clone(), g);
2287            }
2288        }
2289        "inventory" => {
2290            if let Some(d) = read::<yog_inventory::InventoryDef>(kind, &id, value) {
2291                h.inventories.push(d);
2292            }
2293        }
2294        "startup_grant" => {
2295            if let Some(mut g) = read::<yog_registry::StartupGrant>(kind, &id, value) {
2296                none_if_empty(&mut g.book);
2297                none_if_empty(&mut g.command);
2298                h.startup_grants.push(g);
2299            }
2300        }
2301        "recipe" => {
2302            let (ns, name) = id.split_once(':').unwrap_or(("minecraft", &id));
2303            let recipe = value.to_value();
2304            // Feed the recipe to the books already registered (their recipe pages).
2305            for r in h.book_renderers.lock().unwrap().values_mut() {
2306                r.add_recipe(format!("{ns}:{name}"), &recipe);
2307            }
2308            h.recipes.push((ns.to_string(), name.to_string(), recipe));
2309        }
2310        "book" => {
2311            // Read by its schema; the renderer draws it without a round trip to Java.
2312            if let Some(mut book) = read::<yog_book::Book>(kind, &id, value) {
2313                // Entries about mods that aren't here aren't shown.
2314                book.entries.retain(|e| e.requires.iter().all(|m| mod_loaded(m)));
2315                h.books.insert(id.clone());
2316                let mut renderer = yog_book::BookRenderer::new(book);
2317                // i18n books carry translation keys; shown in the game language.
2318                renderer.set_translator(translate);
2319                // Recipes may register before the book — replay them into the renderer.
2320                for (ns, name, recipe) in &h.recipes {
2321                    renderer.add_recipe(format!("{ns}:{name}"), recipe);
2322                }
2323                h.book_renderers.get_mut().unwrap_or_else(|e| e.into_inner()).insert(id, renderer);
2324            }
2325        }
2326        "dimension" => {
2327            yog_logging::info!("registered dimension type: {}", id);
2328            let mut def = value.to_value();
2329            // The terrain stays here; the host gets the dimension, its generator this one.
2330            if let Some(t) = value.get("terrain") {
2331                let Some(terrain) = read::<yog_worldgen::Terrain>(kind, &id, t) else { return };
2332                if let yog_data::Value::Map(m) = &mut def {
2333                    m.remove("terrain");
2334                    m.insert("generator_type", yog_data::Value::from(id.as_str()));
2335                }
2336                h.terrains.insert(id.clone(), Arc::new(yog_worldgen::Generator::new(terrain)));
2337            }
2338            h.dimensions.insert(id, def);
2339        }
2340        other => yog_logging::warn!("unknown kind of content `{other}` ({id}) — this runtime doesn't know it"),
2341    }
2342}
2343
2344
2345
2346
2347unsafe extern "C" fn api_schedule_once(
2348    ctx: *mut c_void,
2349    delay_ticks: u64,
2350    ud: *mut c_void,
2351    h: YogScheduledFn,
2352) {
2353    unsafe {
2354        let handlers = handlers_mut(ctx);
2355        handlers
2356            .scheduler
2357            .lock()
2358            .expect("scheduler poisoned")
2359            .once_tasks
2360            .push(OnceTask {
2361                module: current_registration(),
2362                delay_remaining: delay_ticks,
2363                ud,
2364                f: h,
2365            });
2366    }
2367}
2368
2369unsafe extern "C" fn api_schedule_repeating(
2370    ctx: *mut c_void,
2371    period_ticks: u64,
2372    ud: *mut c_void,
2373    h: YogScheduledFn,
2374) {
2375    unsafe {
2376        let handlers = handlers_mut(ctx);
2377        handlers
2378            .scheduler
2379            .lock()
2380            .expect("scheduler poisoned")
2381            .repeating_tasks
2382            .push(RepeatingTask {
2383                module: current_registration(),
2384                period: period_ticks,
2385                ticks_left: period_ticks.max(1),
2386                ud,
2387                f: h,
2388            });
2389    }
2390}
2391
2392
2393
2394
2395unsafe extern "C" fn api_register_chunk_generator(
2396    ctx: *mut c_void,
2397    id: YogStr,
2398    ud: *mut c_void,
2399    h: yog_abi::YogChunkGeneratorFn,
2400) {
2401    unsafe {
2402        let mut handlers = handlers_mut(ctx);
2403        let id = id.as_str().to_owned();
2404        yog_logging::info!("registered chunk generator for dimension: {}", id);
2405        handlers
2406            .chunk_generators
2407            .insert(id, (current_registration(), ud, h));
2408    }
2409}
2410
2411unsafe extern "C" fn api_register_ui(
2412    ctx: *mut c_void,
2413    ui_id: YogStr,
2414    _layout_json: YogStr,
2415    ud: *mut c_void,
2416    h: yog_abi::YogUIEventFn,
2417) {
2418    unsafe {
2419        let mut handlers = handlers_mut(ctx);
2420        let id = ui_id.as_str().to_owned();
2421        handlers
2422            .ui_handlers
2423            .insert(id.clone(), (current_registration(), ud, h));
2424        yog_logging::info!("registered UI handler: {}", id);
2425    }
2426}
2427
2428unsafe extern "C" fn api_on_ui_render(
2429    ctx: *mut c_void,
2430    ui_id: YogStr,
2431    ud: *mut c_void,
2432    h: YogHudRenderFn,
2433) {
2434    unsafe {
2435        let mut handlers = handlers_mut(ctx);
2436        let id = ui_id.as_str().to_owned();
2437        handlers
2438            .ui_render_handlers
2439            .entry(id)
2440            .or_default()
2441            .push((current_registration(), ud, h));
2442    }
2443}
2444
2445unsafe extern "C" fn api_on_book_page(
2446    ctx: *mut c_void,
2447    drawer: YogStr,
2448    ud: *mut c_void,
2449    f: yog_abi::YogPageDrawFn,
2450) {
2451    unsafe {
2452        let mut handlers = handlers_mut(ctx);
2453        handlers
2454            .page_drawers
2455            .insert(drawer.as_str().to_owned(), (current_registration(), ud, f));
2456    }
2457}
2458
2459unsafe extern "C" fn api_on_item_tooltip(
2460    ctx: *mut c_void,
2461    item: YogStr,
2462    ud: *mut c_void,
2463    size: yog_abi::YogTooltipSizeFn,
2464    draw: yog_abi::YogTooltipDrawFn,
2465) {
2466    unsafe {
2467        let mut handlers = handlers_mut(ctx);
2468        handlers
2469            .item_tooltips
2470            .entry(item.as_str().to_owned())
2471            .or_default()
2472            .push((current_registration(), ud, size, draw));
2473    }
2474}
2475
2476unsafe extern "C" fn api_on_entity_tick(ctx: *mut c_void, entity_type: YogStr, ud: *mut c_void, f: yog_abi::YogEntityTickFn) {
2477    unsafe {
2478        handlers_mut(ctx).entity_ticks.entry(entity_type.as_str().to_owned()).or_default().push((current_registration(), ud, f));
2479    }
2480}
2481
2482/// `nativeOnEntityTick(String type, String uuid)`: a tick of a mod's entity.
2483#[unsafe(no_mangle)]
2484pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityTick<'l>(
2485    mut env: JNIEnv<'l>,
2486    _class: JClass<'l>,
2487    entity_type: JString<'l>,
2488    uuid: JString<'l>,
2489) {
2490    let (t, u) = (jstr!(env, entity_type), jstr!(env, uuid));
2491    let entries = handlers().entity_ticks.get(&t).cloned().unwrap_or_default();
2492    let srv = srv_ptr();
2493    guard("on_entity_tick", || each(&entries, |ud, f| unsafe { f(ud, srv, YogStr::from_str(&u)) }));
2494}
2495
2496unsafe extern "C" fn api_on_item_text(ctx: *mut c_void, item: YogStr, ud: *mut c_void, f: yog_abi::YogItemTextFn) {
2497    unsafe {
2498        handlers_mut(ctx).item_texts.entry(item.as_str().to_owned()).or_default().push((current_registration(), ud, f));
2499    }
2500}
2501
2502unsafe extern "C" fn copy_text(sink: *mut c_void, text: YogStr) {
2503    // SAFETY: `sink` is the `String` `item_text` passes; `text` is valid for the call.
2504    unsafe { (*(sink as *mut String)).push_str(text.as_str()) }
2505}
2506
2507/// A stack's own name and tooltip lines (`name\nline…`), from the first
2508/// mod that gives them; `None`: the item's own.
2509fn item_text(item: &str, snbt: &str) -> Option<String> {
2510    let entries = handlers().item_texts.get(item).cloned().unwrap_or_default();
2511    for (module, ud, f) in entries {
2512        let Some(_call) = module.enter() else { continue };
2513        let mut out = String::new();
2514        let mut given = false;
2515        guard("item_text", || unsafe {
2516            given = f(ud, YogStr::from_str(item), YogStr::from_str(snbt), &mut out as *mut String as *mut c_void, copy_text);
2517        });
2518        if given {
2519            return Some(out);
2520        }
2521    }
2522    None
2523}
2524
2525#[unsafe(no_mangle)]
2526pub extern "system" fn Java_dev_yog_NativeBridge_nativeItemText<'l>(
2527    mut env: JNIEnv<'l>,
2528    _class: JClass<'l>,
2529    item: JString<'l>,
2530    snbt: JString<'l>,
2531) -> jstring {
2532    let item: String = env.get_string(&item).map(String::from).unwrap_or_default();
2533    let snbt: String = env.get_string(&snbt).map(String::from).unwrap_or_default();
2534    match item_text(&item, &snbt) {
2535        Some(t) => env.new_string(t).map(JString::into_raw).unwrap_or(std::ptr::null_mut()),
2536        None => std::ptr::null_mut(),
2537    }
2538}
2539
2540// ── Machines (ABI 2.5) ───────────────────────────────────────────────────────
2541
2542/// A machine's event about recipe `found`.
2543fn machine_event<'a>(
2544    m: &'a yog_inventory::Machine,
2545    def: &'a str,
2546    found: &'a machine::Found,
2547    dim: &'a str,
2548    pos: YogBlockPos,
2549    player: &'a str,
2550) -> YogMachineCraftEvent {
2551    YogMachineCraftEvent {
2552        machine: YogStr::from_str(def),
2553        kind: YogStr::from_str(&m.kind),
2554        recipe: YogStr::from_str(&found.recipe),
2555        result_item: YogStr::from_str(&found.result),
2556        result_count: found.count,
2557        values: YogStr::from_str(&found.values),
2558        pos,
2559        dimension: YogStr::from_str(dim),
2560        player: YogStr::from_str(player),
2561    }
2562}
2563
2564/// The recipe machine `def` at `pos` makes of `items` (by inventory slot,
2565/// `""` empty): the first that fits and every mod allows; `recipe` only it.
2566fn machine_recipe(def: &str, dim: &str, pos: YogBlockPos, items: &[String], recipe: Option<&str>) -> Option<machine::Found> {
2567    let h = handlers();
2568    let m = h.inventories.iter().find(|d| d.id == def)?.machine.as_ref()?;
2569    let has_tag = |item: &str, tag: &str| unsafe { srv_has_item_tag(std::ptr::null_mut(), YogStr::from_str(item), YogStr::from_str(tag)) };
2570    let recipes = h.recipes.iter().map(|(ns, name, r)| (format!("{ns}:{name}"), r)).filter(|(id, _)| recipe.is_none_or(|r| r == id));
2571    let srv = srv_ptr();
2572    machine::find(m, recipes, items, &has_tag).find(|found| {
2573        let ev = machine_event(m, def, found, dim, pos, "");
2574        allowed(&h.machine_craft, |ud, f| unsafe { f(ud, srv, &ev, 0) })
2575    })
2576}
2577
2578/// What machine `def` at `x y z` makes of `items` (`\n`-joined, by slot):
2579/// `recipe\nresult\ncount`, or null.
2580#[unsafe(no_mangle)]
2581pub extern "system" fn Java_dev_yog_NativeBridge_nativeMachineResult<'l>(
2582    mut env: JNIEnv<'l>,
2583    _class: JClass<'l>,
2584    def: JString<'l>,
2585    dimension: JString<'l>,
2586    x: jint,
2587    y: jint,
2588    z: jint,
2589    items: JString<'l>,
2590) -> jstring {
2591    let (def, d, items) = (jstr!(env, def, std::ptr::null_mut()), jstr!(env, dimension, std::ptr::null_mut()), jstr!(env, items, std::ptr::null_mut()));
2592    let items: Vec<String> = items.split('\n').map(str::to_string).collect();
2593    let mut found = None;
2594    guard("machine_result", || found = machine_recipe(&def, &d, YogBlockPos { x, y, z }, &items, None));
2595    match found {
2596        Some(f) => env.new_string(format!("{}\n{}\n{}", f.recipe, f.result, f.count)).map(JString::into_raw).unwrap_or(std::ptr::null_mut()),
2597        None => std::ptr::null_mut(),
2598    }
2599}
2600
2601/// `player` took machine `def`'s result, made by `recipe` of `items` (the
2602/// ingredients still in): whether it may — then the mods take their share.
2603#[unsafe(no_mangle)]
2604#[allow(clippy::too_many_arguments)]
2605pub extern "system" fn Java_dev_yog_NativeBridge_nativeMachineCraft<'l>(
2606    mut env: JNIEnv<'l>,
2607    _class: JClass<'l>,
2608    def: JString<'l>,
2609    recipe: JString<'l>,
2610    dimension: JString<'l>,
2611    x: jint,
2612    y: jint,
2613    z: jint,
2614    items: JString<'l>,
2615    player: JString<'l>,
2616) -> jni::sys::jboolean {
2617    let (def, recipe, d, items, player) =
2618        (jstr!(env, def, 0), jstr!(env, recipe, 0), jstr!(env, dimension, 0), jstr!(env, items, 0), jstr!(env, player, 0));
2619    let items: Vec<String> = items.split('\n').map(str::to_string).collect();
2620    let pos = YogBlockPos { x, y, z };
2621    let mut made = false;
2622    guard("machine_craft", || {
2623        let Some(found) = machine_recipe(&def, &d, pos, &items, Some(&recipe)) else { return };
2624        let h = handlers();
2625        let Some(m) = h.inventories.iter().find(|i| i.id == def).and_then(|i| i.machine.as_ref()) else { return };
2626        let ev = machine_event(m, &def, &found, &d, pos, &player);
2627        let srv = srv_ptr();
2628        each(&h.machine_craft, |ud, f| unsafe { f(ud, srv, &ev, 1) });
2629        made = true;
2630    });
2631    made as jni::sys::jboolean
2632}
2633
2634/// The Yog mods being loaded, by id (all of them, before the first registers).
2635static YOG_MOD_IDS: RwLock<std::collections::BTreeSet<String>> = RwLock::new(std::collections::BTreeSet::new());
2636
2637/// Whether mod `id` is loaded: a Yog mod, else one in the host's list
2638/// (Fabric's, Forge's, NeoForge's).
2639fn mod_loaded(id: &str) -> bool {
2640    YOG_MOD_IDS.read().unwrap_or_else(|e| e.into_inner()).contains(id)
2641        || HOT_RELOADER.get().is_some_and(|r| r.all_active().iter().any(|(m, _)| m == id))
2642        // SAFETY: a host call with a string argument, on the calling thread.
2643        || unsafe { bridge!("isModLoaded", [JArg::S(YogStr::from_str(id))]) }.unwrap_or(false)
2644}
2645
2646unsafe extern "C" fn api_is_mod_loaded(_ctx: *mut c_void, id: YogStr) -> bool {
2647    unsafe { mod_loaded(id.as_str()) }
2648}
2649
2650unsafe extern "C" fn api_java_call(_ctx: *mut c_void, expr: YogStr, args: YogStr) -> YogOwnedStr {
2651    unsafe {
2652        let args = match yog_data::text::parse_value(args.as_str()) {
2653            Ok(v) => v,
2654            Err(e) => {
2655                yog_logging::warn!("java_call {}: its arguments aren't Yog Data: {}", expr.as_str(), e.message);
2656                return YogOwnedStr::NONE;
2657            }
2658        };
2659        let bytes = yog_data::binary::encode(&args);
2660        let out: Option<Vec<u8>> = host!("dev/yog/data/YogJava", "call", [JArg::S(expr), JArg::Bytes(&bytes)]);
2661        match out.map(|b| yog_data::binary::decode(&b)) {
2662            Some(Ok(v)) => YogOwnedStr::from_string(yog_data::text::to_string(&v)),
2663            _ => YogOwnedStr::NONE,
2664        }
2665    }
2666}
2667
2668/// Strip TSV separators so one mod can't corrupt the line format.
2669fn tsv_clean(v: &str) -> String {
2670    v.replace(['\t', '\n', '\r'], " ")
2671}
2672
2673unsafe extern "C" fn api_ui_open(_ctx: *mut c_void, ui_id: YogStr, modal: bool, pause: bool) {
2674    unsafe {
2675        if ui_id.as_str().is_empty() {
2676            return;
2677        }
2678        // Java side schedules onto the render thread; no-op on dedicated servers.
2679        let _: Option<()> = bridge!("openUI", [S(ui_id), Z(modal), Z(pause)]);
2680    }
2681}
2682
2683unsafe extern "C" fn api_ui_close(_ctx: *mut c_void, ui_id: YogStr) {
2684    unsafe {
2685        // Java side defers onto the render thread (after the current event) and
2686        // checks the open screen is that Yog UI; no-op on dedicated servers.
2687        let _: Option<()> = bridge!("closeUI", [S(ui_id)]);
2688    }
2689}
2690
2691unsafe extern "C" fn api_ui_consume_event(_ctx: *mut c_void) {
2692    ui_jni::consume_event();
2693}
2694
2695unsafe extern "C" fn api_translate(_ctx: *mut c_void, key: YogStr) -> YogOwnedStr {
2696    unsafe { translate(key.as_str()).map_or(YogOwnedStr::NONE, YogOwnedStr::from_string) }
2697}
2698
2699/// The game's text for translation `key` in the current language — `None`
2700/// when no lang file has it (or there's no JVM).
2701fn translate(key: &str) -> Option<String> {
2702    if key.is_empty() {
2703        return None;
2704    }
2705    unsafe { bridge!("translate", [S(YogStr::from_str(key))]) }
2706}
2707
2708unsafe extern "C" fn api_mods_list(_ctx: *mut c_void) -> YogOwnedStr {
2709    unsafe {
2710        let mut lines: Vec<String> = Vec::new();
2711        let infos = MOD_INFOS.lock().expect("mod infos lock poisoned").clone();
2712        for m in &infos {
2713            // A `.yres` name/description shows in the player's language.
2714            let localized = |text: &str, key: &str| {
2715                translate(key).map_or_else(|| text.to_string(), |t| tsv_clean(&t))
2716            };
2717            lines.push(format!(
2718                "yog\t{}\t{}\t{}\t{}\t{}",
2719                m[0],
2720                localized(&m[1], &m[5]),
2721                m[2],
2722                m[3],
2723                localized(&m[4], &m[6])
2724            ));
2725        }
2726        // Loader-side (Java) mods, if the host provides them.
2727        let platform: Option<String> = bridge!("listPlatformMods", []);
2728        for line in platform.iter().flat_map(|s| s.lines()) {
2729            if !line.trim().is_empty() {
2730                lines.push(format!("platform\t{line}"));
2731            }
2732        }
2733        YogOwnedStr::from_string(lines.join("\n"))
2734    }
2735}
2736
2737unsafe extern "C" fn api_register_menu_entry(ctx: *mut c_void, label: YogStr, ui_id: YogStr) {
2738    unsafe {
2739        let mut handlers = handlers_mut(ctx);
2740        let l = label.as_str().to_owned();
2741        let u = ui_id.as_str().to_owned();
2742        handlers.menu_entries.push((l, u));
2743    }
2744}
2745
2746// ── World queries & effects (ABI minor 1) ────────────────────────────────────
2747//
2748// Each of these forwards to a `NativeBridge` static of the same shape; the JNI
2749// signature is derived from the argument list so the two cannot drift apart.
2750
2751fn vec_args(v: YogVec3) -> [JArg<'static>; 3] {
2752    [JArg::D(v.x), JArg::D(v.y), JArg::D(v.z)]
2753}
2754
2755fn pos_args(p: YogBlockPos) -> [JArg<'static>; 3] {
2756    [JArg::I(p.x), JArg::I(p.y), JArg::I(p.z)]
2757}
2758
2759unsafe extern "C" fn srv_entity_info(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
2760    unsafe { owned(bridge!("entityInfo", [JArg::S(uuid)])) }
2761}
2762
2763unsafe extern "C" fn srv_entities_in_box(
2764    _ctx: *mut c_void,
2765    dim: YogStr,
2766    min: YogVec3,
2767    max: YogVec3,
2768) -> YogOwnedStr {
2769    unsafe {
2770        let [a, b, c] = vec_args(min);
2771        let [d, e, f] = vec_args(max);
2772        owned(bridge!("entitiesInBox", [JArg::S(dim), a, b, c, d, e, f]))
2773    }
2774}
2775
2776unsafe extern "C" fn srv_raycast_block(
2777    _ctx: *mut c_void,
2778    dim: YogStr,
2779    from: YogVec3,
2780    to: YogVec3,
2781) -> YogOwnedStr {
2782    unsafe {
2783        let [a, b, c] = vec_args(from);
2784        let [d, e, f] = vec_args(to);
2785        owned(bridge!("raycastBlock", [JArg::S(dim), a, b, c, d, e, f]))
2786    }
2787}
2788
2789unsafe extern "C" fn srv_raycast_entity(
2790    _ctx: *mut c_void,
2791    dim: YogStr,
2792    from: YogVec3,
2793    to: YogVec3,
2794    exclude: YogStr,
2795) -> YogOwnedStr {
2796    unsafe {
2797        let [a, b, c] = vec_args(from);
2798        let [d, e, f] = vec_args(to);
2799        owned(bridge!(
2800            "raycastEntity",
2801            [JArg::S(dim), a, b, c, d, e, f, JArg::S(exclude)]
2802        ))
2803    }
2804}
2805
2806unsafe extern "C" fn srv_block_info(
2807    _ctx: *mut c_void,
2808    dim: YogStr,
2809    pos: YogBlockPos,
2810) -> YogOwnedStr {
2811    unsafe {
2812        let [x, y, z] = pos_args(pos);
2813        owned(bridge!("blockInfo", [JArg::S(dim), x, y, z]))
2814    }
2815}
2816
2817unsafe extern "C" fn srv_break_block(
2818    _ctx: *mut c_void,
2819    dim: YogStr,
2820    pos: YogBlockPos,
2821    drop: bool,
2822    breaker: YogStr,
2823) -> bool {
2824    unsafe {
2825        let [x, y, z] = pos_args(pos);
2826        bridge!(
2827            "breakBlock",
2828            [JArg::S(dim), x, y, z, JArg::Z(drop), JArg::S(breaker)]
2829        )
2830        .unwrap_or(false)
2831    }
2832}
2833
2834unsafe extern "C" fn srv_place_block_from_slot(
2835    _ctx: *mut c_void,
2836    player: YogStr,
2837    slot: u32,
2838    dim: YogStr,
2839    pos: YogBlockPos,
2840) -> bool {
2841    unsafe {
2842        let [x, y, z] = pos_args(pos);
2843        bridge!(
2844            "placeBlockFromSlot",
2845            [JArg::S(player), JArg::I(slot as i32), JArg::S(dim), x, y, z]
2846        )
2847        .unwrap_or(false)
2848    }
2849}
2850
2851unsafe extern "C" fn srv_bonemeal(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> bool {
2852    unsafe {
2853        let [x, y, z] = pos_args(pos);
2854        bridge!("bonemeal", [JArg::S(dim), x, y, z]).unwrap_or(false)
2855    }
2856}
2857
2858unsafe extern "C" fn srv_explode(
2859    _ctx: *mut c_void,
2860    dim: YogStr,
2861    pos: YogVec3,
2862    power: f32,
2863    fire: bool,
2864    source: YogStr,
2865) -> bool {
2866    unsafe {
2867        let [x, y, z] = vec_args(pos);
2868        bridge!(
2869            "explode",
2870            [
2871                JArg::S(dim),
2872                x,
2873                y,
2874                z,
2875                JArg::F(power),
2876                JArg::Z(fire),
2877                JArg::S(source),
2878            ]
2879        )
2880        .unwrap_or(false)
2881    }
2882}
2883
2884unsafe extern "C" fn srv_tellraw(_ctx: *mut c_void, player: YogStr, json: YogStr) -> bool {
2885    unsafe { bridge!("tellraw", [JArg::S(player), JArg::S(json)]).unwrap_or(false) }
2886}
2887
2888unsafe extern "C" fn srv_entity_damage(
2889    _ctx: *mut c_void,
2890    uuid: YogStr,
2891    amount: f32,
2892    damage_type: YogStr,
2893    attacker: YogStr,
2894) -> bool {
2895    unsafe {
2896        bridge!(
2897            "entityDamage",
2898            [
2899                JArg::S(uuid),
2900                JArg::F(amount),
2901                JArg::S(damage_type),
2902                JArg::S(attacker),
2903            ]
2904        )
2905        .unwrap_or(false)
2906    }
2907}
2908
2909unsafe extern "C" fn srv_entity_set_fire_ticks(
2910    _ctx: *mut c_void,
2911    uuid: YogStr,
2912    ticks: i32,
2913) -> bool {
2914    unsafe { bridge!("entitySetFireTicks", [JArg::S(uuid), JArg::I(ticks)]).unwrap_or(false) }
2915}
2916
2917unsafe extern "C" fn srv_player_add_xp(_ctx: *mut c_void, player: YogStr, amount: i32) -> bool {
2918    unsafe { bridge!("playerAddXp", [JArg::S(player), JArg::I(amount)]).unwrap_or(false) }
2919}
2920
2921unsafe extern "C" fn srv_player_set_may_fly(
2922    _ctx: *mut c_void,
2923    player: YogStr,
2924    may_fly: bool,
2925) -> bool {
2926    unsafe { bridge!("playerSetMayFly", [JArg::S(player), JArg::Z(may_fly)]).unwrap_or(false) }
2927}
2928
2929unsafe extern "C" fn srv_player_info(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
2930    unsafe { owned(bridge!("playerInfo", [JArg::S(player)])) }
2931}
2932
2933unsafe extern "C" fn srv_spawn_item(
2934    _ctx: *mut c_void,
2935    dim: YogStr,
2936    pos: YogVec3,
2937    vel: YogVec3,
2938    item_id: YogStr,
2939    count: u32,
2940    snbt: YogStr,
2941) -> YogOwnedStr {
2942    unsafe {
2943        let [a, b, c] = vec_args(pos);
2944        let [d, e, f] = vec_args(vel);
2945        owned(bridge!(
2946            "spawnItem",
2947            [
2948                JArg::S(dim),
2949                a,
2950                b,
2951                c,
2952                d,
2953                e,
2954                f,
2955                JArg::S(item_id),
2956                JArg::I(count as i32),
2957                JArg::S(snbt),
2958            ]
2959        ))
2960    }
2961}
2962
2963unsafe extern "C" fn srv_item_entity_stack(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
2964    unsafe { owned(bridge!("itemEntityStack", [JArg::S(uuid)])) }
2965}
2966
2967unsafe extern "C" fn srv_actionbar_json(_ctx: *mut c_void, player: YogStr, json: YogStr) -> bool {
2968    unsafe { bridge!("actionbarJson", [JArg::S(player), JArg::S(json)]).unwrap_or(false) }
2969}
2970
2971unsafe extern "C" fn srv_use_item_on_block(
2972    _ctx: *mut c_void,
2973    dim: YogStr,
2974    pos: YogBlockPos,
2975    face: u8,
2976    item_id: YogStr,
2977    player: YogStr,
2978) -> bool {
2979    unsafe {
2980        let [x, y, z] = pos_args(pos);
2981        bridge!(
2982            "useItemOnBlock",
2983            [
2984                JArg::S(dim),
2985                x,
2986                y,
2987                z,
2988                JArg::I(face as i32),
2989                JArg::S(item_id),
2990                JArg::S(player),
2991            ]
2992        )
2993        .unwrap_or(false)
2994    }
2995}
2996
2997unsafe extern "C" fn srv_pour_fluid(
2998    _ctx: *mut c_void,
2999    dim: YogStr,
3000    pos: YogBlockPos,
3001    bucket_item_id: YogStr,
3002) -> bool {
3003    unsafe {
3004        let [x, y, z] = pos_args(pos);
3005        bridge!(
3006            "pourFluid",
3007            [JArg::S(dim), x, y, z, JArg::S(bucket_item_id)]
3008        )
3009        .unwrap_or(false)
3010    }
3011}
3012
3013unsafe extern "C" fn srv_has_entity_tag(
3014    _ctx: *mut c_void,
3015    entity_type: YogStr,
3016    tag: YogStr,
3017) -> bool {
3018    unsafe { bridge!("hasEntityTag", [JArg::S(entity_type), JArg::S(tag)]).unwrap_or(false) }
3019}
3020
3021unsafe extern "C" fn srv_item_block(_ctx: *mut c_void, item_id: YogStr) -> YogOwnedStr {
3022    unsafe { owned(bridge!("itemBlock", [JArg::S(item_id)])) }
3023}
3024
3025unsafe extern "C" fn srv_place_feature(
3026    _ctx: *mut c_void,
3027    dim: YogStr,
3028    pos: YogBlockPos,
3029    feature_id: YogStr,
3030) -> bool {
3031    unsafe {
3032        let [x, y, z] = pos_args(pos);
3033        bridge!("placeFeature", [JArg::S(dim), x, y, z, JArg::S(feature_id)]).unwrap_or(false)
3034    }
3035}
3036
3037unsafe extern "C" fn srv_item_entity_set_stack(
3038    _ctx: *mut c_void,
3039    uuid: YogStr,
3040    item_id: YogStr,
3041    count: u32,
3042    snbt: YogStr,
3043) -> bool {
3044    unsafe {
3045        bridge!(
3046            "itemEntitySetStack",
3047            [
3048                JArg::S(uuid),
3049                JArg::S(item_id),
3050                JArg::I(count as i32),
3051                JArg::S(snbt),
3052            ]
3053        )
3054        .unwrap_or(false)
3055    }
3056}
3057
3058// ── Table constructors ────────────────────────────────────────────────────────
3059
3060fn build_server_table() -> YogServer {
3061    YogServer {
3062        ctx: std::ptr::null_mut(),
3063        abi_version: ABI_VERSION,
3064        size: std::mem::size_of::<YogServer>() as u32,
3065        free_str: yog_free_str,
3066        broadcast: srv_broadcast,
3067        get_block: srv_get_block,
3068        set_block: srv_set_block,
3069        world_time: srv_world_time,
3070        set_time: srv_set_time,
3071        is_raining: srv_is_raining,
3072        set_weather: srv_set_weather,
3073        give_item: srv_give_item,
3074        player_teleport: srv_player_teleport,
3075        send_to_player: srv_send_to_player,
3076        send_to_server: srv_send_to_server,
3077        kick_player: srv_kick_player,
3078        set_gamemode: srv_set_gamemode,
3079        send_title: srv_send_title,
3080        send_actionbar: srv_send_actionbar,
3081        play_sound: srv_play_sound,
3082        play_sound_player: srv_play_sound_player,
3083        entity_teleport: srv_entity_teleport,
3084        entity_position: srv_entity_position,
3085        entity_rotation: srv_entity_rotation,
3086        entity_health: srv_entity_health,
3087        entity_set_health: srv_entity_set_health,
3088        entity_kill: srv_entity_kill,
3089        spawn_entity: srv_spawn_entity,
3090        entity_add_effect: srv_entity_add_effect,
3091        entity_remove_effect: srv_entity_remove_effect,
3092        entity_clear_effects: srv_entity_clear_effects,
3093        entity_velocity: srv_entity_velocity,
3094        entity_set_velocity: srv_entity_set_velocity,
3095        entity_add_velocity: srv_entity_add_velocity,
3096        has_item_tag: srv_has_item_tag,
3097        has_block_tag: srv_has_block_tag,
3098        drop_loot: srv_drop_loot,
3099        scoreboard_get: srv_scoreboard_get,
3100        scoreboard_set: srv_scoreboard_set,
3101        scoreboard_add: srv_scoreboard_add,
3102        bossbar_create: srv_bossbar_create,
3103        bossbar_remove: srv_bossbar_remove,
3104        bossbar_set_title: srv_bossbar_set_title,
3105        bossbar_set_progress: srv_bossbar_set_progress,
3106        bossbar_set_color: srv_bossbar_set_color,
3107        bossbar_add_player: srv_bossbar_add_player,
3108        bossbar_remove_player: srv_bossbar_remove_player,
3109        bossbar_set_visible: srv_bossbar_set_visible,
3110        game_dir: srv_game_dir,
3111        get_block_nbt: srv_get_block_nbt,
3112        set_block_nbt: srv_set_block_nbt,
3113        get_inventory_slot: srv_get_inventory_slot,
3114        set_inventory_slot: srv_set_inventory_slot,
3115        player_inventory: srv_player_inventory,
3116        player_set_slot: srv_player_set_slot,
3117        player_teleport_dim: srv_player_teleport_dim,
3118        entity_teleport_dim: srv_entity_teleport_dim,
3119        online_players: srv_online_players,
3120        world_entity_count: srv_world_entity_count,
3121        entity_get_nbt: srv_entity_get_nbt,
3122        entity_set_nbt: srv_entity_set_nbt,
3123        spawn_particles: srv_spawn_particles,
3124        entity_attribute_get: srv_entity_attribute_get,
3125        entity_attribute_set: srv_entity_attribute_set,
3126        get_held_item_nbt: srv_get_held_item_nbt,
3127        set_held_item_nbt: srv_set_held_item_nbt,
3128        get_offhand_item_nbt: srv_get_offhand_item_nbt,
3129        set_offhand_item_nbt: srv_set_offhand_item_nbt,
3130        get_slot_item: srv_get_slot_item,
3131        set_slot_item: srv_set_slot_item,
3132        entity_info: srv_entity_info,
3133        entities_in_box: srv_entities_in_box,
3134        raycast_block: srv_raycast_block,
3135        raycast_entity: srv_raycast_entity,
3136        block_info: srv_block_info,
3137        break_block: srv_break_block,
3138        place_block_from_slot: srv_place_block_from_slot,
3139        bonemeal: srv_bonemeal,
3140        explode: srv_explode,
3141        tellraw: srv_tellraw,
3142        entity_damage: srv_entity_damage,
3143        entity_set_fire_ticks: srv_entity_set_fire_ticks,
3144        player_add_xp: srv_player_add_xp,
3145        player_set_may_fly: srv_player_set_may_fly,
3146        player_info: srv_player_info,
3147        spawn_item: srv_spawn_item,
3148        item_entity_stack: srv_item_entity_stack,
3149        item_entity_set_stack: srv_item_entity_set_stack,
3150        actionbar_json: srv_actionbar_json,
3151        use_item_on_block: srv_use_item_on_block,
3152        pour_fluid: srv_pour_fluid,
3153        has_entity_tag: srv_has_entity_tag,
3154        item_block: srv_item_block,
3155        place_feature: srv_place_feature,
3156        set_item_cooldown: srv_set_item_cooldown,
3157        entity_vehicle: srv_entity_vehicle,
3158        entity_passengers: srv_entity_passengers,
3159        entity_mount: srv_entity_mount,
3160        entity_dismount: srv_entity_dismount,
3161        redstone_power: srv_redstone_power,
3162        entity_set_dimensions: srv_entity_set_dimensions,
3163        entity_data_set: entity_data::srv_entity_data_set,
3164        entity_data_get: entity_data::srv_entity_data_get,
3165        world_dir: srv_world_dir,
3166        entity_attribute_value: srv_entity_attribute_value,
3167        advancement_grant: srv_advancement_grant,
3168        advancement_done: srv_advancement_done,
3169        entity_set_fall_distance: srv_entity_set_fall_distance,
3170        redstone_signal: srv_redstone_signal,
3171        set_redstone_output: srv_set_redstone_output,
3172        get_block_state: srv_get_block_state,
3173        set_block_state: srv_set_block_state,
3174        world_is_thundering: srv_world_is_thundering,
3175        world_set_thunder: srv_world_set_thunder,
3176        fill_region: srv_fill_region,
3177        scan_region: srv_scan_region,
3178    }
3179}
3180
3181// ── ABI minor 3 ──────────────────────────────────────────────────────────────
3182
3183unsafe extern "C" fn srv_set_item_cooldown(_ctx: *mut c_void, player: YogStr, item_id: YogStr, ticks: i32) -> bool {
3184    unsafe { bridge!("setItemCooldown", [S(player), S(item_id), I(ticks)]).unwrap_or(false) }
3185}
3186
3187unsafe extern "C" fn srv_entity_vehicle(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
3188    unsafe { owned(bridge!("entityVehicle", [S(uuid)])) }
3189}
3190
3191unsafe extern "C" fn srv_entity_passengers(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
3192    unsafe { owned(bridge!("entityPassengers", [S(uuid)])) }
3193}
3194
3195unsafe extern "C" fn srv_entity_mount(_ctx: *mut c_void, rider: YogStr, vehicle: YogStr, force: bool) -> bool {
3196    unsafe { bridge!("entityMount", [S(rider), S(vehicle), Z(force)]).unwrap_or(false) }
3197}
3198
3199unsafe extern "C" fn srv_entity_dismount(_ctx: *mut c_void, uuid: YogStr) -> bool {
3200    unsafe { bridge!("entityDismount", [S(uuid)]).unwrap_or(false) }
3201}
3202
3203/// The server's hitbox now, the clients' through entity data.
3204unsafe extern "C" fn srv_entity_set_dimensions(_ctx: *mut c_void, uuid: YogStr, w: f32, h: f32, eye: f32) -> bool {
3205    let found: bool = unsafe { bridge!("entitySetDimensions", [S(uuid), F(w), F(h), F(eye)]).unwrap_or(false) };
3206    if found {
3207        let value = (w >= 0.0).then(|| entity_data::encode_dims(w, h, eye));
3208        entity_data::set(unsafe { uuid.as_str() }, entity_data::DIMENSIONS, value.as_deref(), false);
3209    }
3210    found
3211}
3212
3213unsafe extern "C" fn srv_entity_set_fall_distance(_ctx: *mut c_void, uuid: YogStr, distance: f32) -> bool {
3214    unsafe { bridge!("entitySetFallDistance", [S(uuid), F(distance)]).unwrap_or(false) }
3215}
3216
3217unsafe extern "C" fn srv_redstone_signal(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> i32 {
3218    unsafe { bridge!("redstoneSignal", [S(dim), I(pos.x), I(pos.y), I(pos.z)]).unwrap_or(-1) }
3219}
3220
3221unsafe extern "C" fn srv_redstone_power(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> i32 {
3222    unsafe { bridge!("redstonePower", [S(dim), I(pos.x), I(pos.y), I(pos.z)]).unwrap_or(-1) }
3223}
3224
3225unsafe extern "C" fn srv_set_redstone_output(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos, level: i32) -> bool {
3226    unsafe { bridge!("setRedstoneOutput", [S(dim), I(pos.x), I(pos.y), I(pos.z), I(level)]).unwrap_or(false) }
3227}
3228
3229unsafe extern "C" fn srv_get_block_state(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> YogOwnedStr {
3230    unsafe { owned(bridge!("getBlockState", [S(dim), I(pos.x), I(pos.y), I(pos.z)])) }
3231}
3232
3233unsafe extern "C" fn srv_set_block_state(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos, state: YogStr) -> bool {
3234    unsafe { bridge!("setBlockState", [S(dim), I(pos.x), I(pos.y), I(pos.z), S(state)]).unwrap_or(false) }
3235}
3236
3237unsafe extern "C" fn srv_world_is_thundering(_ctx: *mut c_void, dim: YogStr) -> bool {
3238    unsafe { bridge!("worldIsThundering", [S(dim)]).unwrap_or(false) }
3239}
3240
3241unsafe extern "C" fn srv_world_set_thunder(_ctx: *mut c_void, dim: YogStr, thundering: bool, duration_ticks: i32) -> bool {
3242    unsafe { bridge!("worldSetThunder", [S(dim), Z(thundering), I(duration_ticks)]).unwrap_or(false) }
3243}
3244
3245unsafe extern "C" fn srv_fill_region(
3246    _ctx: *mut c_void,
3247    dim: YogStr,
3248    from: YogBlockPos,
3249    to: YogBlockPos,
3250    state: YogStr,
3251) -> i32 {
3252    unsafe {
3253        bridge!(
3254            "fillRegion",
3255            [S(dim), I(from.x), I(from.y), I(from.z), I(to.x), I(to.y), I(to.z), S(state)]
3256        )
3257        .unwrap_or(-1)
3258    }
3259}
3260
3261unsafe extern "C" fn srv_scan_region(_ctx: *mut c_void, dim: YogStr, from: YogBlockPos, to: YogBlockPos) -> YogOwnedStr {
3262    unsafe { owned(bridge!("scanRegion", [S(dim), I(from.x), I(from.y), I(from.z), I(to.x), I(to.y), I(to.z)])) }
3263}
3264
3265// ── Inter-mod communication ──────────────────────────────────────────────────
3266
3267unsafe extern "C" fn interop_export_impl(
3268    _ctx: *mut c_void,
3269    mod_id: YogStr,
3270    symbol: YogStr,
3271    ptr: *const c_void,
3272) {
3273    unsafe {
3274        let mod_id = mod_id.as_str();
3275        let sym = symbol.as_str();
3276        let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3277        registry
3278            .lock()
3279            .expect("interop symbols lock poisoned")
3280            .entry(mod_id.to_string())
3281            .or_default()
3282            .insert(sym.to_string(), ptr as usize);
3283    }
3284}
3285
3286unsafe extern "C" fn interop_import_impl(
3287    _ctx: *mut c_void,
3288    mod_id: YogStr,
3289    symbol: YogStr,
3290) -> *const c_void {
3291    unsafe {
3292        let mod_id = mod_id.as_str();
3293        let sym = symbol.as_str();
3294        let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3295        registry
3296            .lock()
3297            .expect("interop symbols lock poisoned")
3298            .get(mod_id)
3299            .and_then(|m: &HashMap<String, usize>| m.get(sym))
3300            .map(|&ptr| ptr as *const c_void)
3301            .unwrap_or(std::ptr::null())
3302    }
3303}
3304
3305fn build_api_table(ctx: *const RwLock<RuntimeHandlers>, server: *const YogServer) -> YogApi {
3306    YogApi {
3307        abi_version: ABI_VERSION,
3308        size: std::mem::size_of::<YogApi>() as u32,
3309        ctx: ctx as *mut c_void,
3310        server,
3311        on_block_break: api_on_block_break,
3312        on_chat: api_on_chat,
3313        on_player_join: api_on_player_join,
3314        on_player_leave: api_on_player_leave,
3315        on_use_item: api_on_use_item,
3316        on_use_block: api_on_use_block,
3317        on_attack_entity: api_on_attack_entity,
3318        on_entity_damage: api_on_entity_damage,
3319        on_entity_death: api_on_entity_death,
3320        on_entity_spawn: api_on_entity_spawn,
3321        on_player_place_block: api_on_player_place_block,
3322        on_player_death: api_on_player_death,
3323        on_player_respawn: api_on_player_respawn,
3324        on_advancement: api_on_advancement,
3325        on_entity_interact: api_on_entity_interact,
3326        on_item_craft: api_on_item_craft,
3327        on_explosion: api_on_explosion,
3328        on_item_pickup: api_on_item_pickup,
3329        on_item_insert: api_on_item_insert,
3330        on_player_move: api_on_player_move,
3331        on_container_open: api_on_container_open,
3332        on_container_close: api_on_container_close,
3333        on_projectile_hit: api_on_projectile_hit,
3334        on_server_tick: api_on_server_tick,
3335        on_server_started: api_on_server_started,
3336        on_server_stopping: api_on_server_stopping,
3337        on_packet: api_on_packet,
3338        on_client_packet: api_on_client_packet,
3339        register_command: api_register_command,
3340        register_typed_command: api_register_typed_command,
3341        register_content: api_register_content,
3342        schedule_once: api_schedule_once,
3343        schedule_repeating: api_schedule_repeating,
3344        on_client_tick: api_on_client_tick,
3345        on_hud_render: api_on_hud_render,
3346        on_key_press: api_on_key_press,
3347        on_screen_open: api_on_screen_open,
3348        on_screen_close: api_on_screen_close,
3349        on_world_render: api_on_world_render,
3350        register_ui: api_register_ui,
3351        on_ui_render: api_on_ui_render,
3352        register_menu_entry: api_register_menu_entry,
3353        mods_list: api_mods_list,
3354        free_str: yog_free_str,
3355        ui_open: api_ui_open,
3356        interop_export: interop_export_impl,
3357        interop_import: interop_import_impl,
3358        register_chunk_generator: api_register_chunk_generator,
3359        ui_close: api_ui_close,
3360        ui_consume_event: api_ui_consume_event,
3361        translate: api_translate,
3362        ui_open_flags: client_api::api_ui_open_flags,
3363        client_play_sound: client_api::api_client_play_sound,
3364        client_stop_sound: client_api::api_client_stop_sound,
3365        client_held_item: client_api::api_client_held_item,
3366        client_set_block_tint: client_api::api_client_set_block_tint,
3367        client_key_down: client_api::api_client_key_down,
3368        on_book_page: api_on_book_page,
3369        on_item_tooltip: api_on_item_tooltip,
3370        is_mod_loaded: api_is_mod_loaded,
3371        java_call: api_java_call,
3372        on_item_text: api_on_item_text,
3373        client_body_track: body::api_client_body_track,
3374        client_body_track_type: body::api_client_body_track_type,
3375        client_set_dimensions: body::api_client_set_dimensions,
3376        client_entity_data: entity_data::api_client_entity_data,
3377        on_body: body::api_on_body,
3378        on_camera: body::api_on_camera,
3379        on_travel: body::api_on_travel,
3380        on_machine_craft: api_on_machine_craft,
3381        on_entity_tick: api_on_entity_tick,
3382        on_loot: loot::api_on_loot,
3383        client_attribute_value: api_client_attribute_value,
3384        client_advancement_done: api_client_advancement_done,
3385    }
3386}
3387
3388// ── Mod loading ───────────────────────────────────────────────────────────────
3389
3390fn platform_tag() -> String {
3391    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
3392}
3393
3394type AbiVersionFn = unsafe extern "C" fn() -> u32;
3395/// Second arg is a null-terminated C string: the mod's `id` from its manifest.
3396type RegisterFn = unsafe extern "C" fn(*const YogApi, *const std::os::raw::c_char);
3397
3398fn load_mods(dir: &Path, api: &YogApi) {
3399    let entries = match std::fs::read_dir(dir) {
3400        Ok(e) => e,
3401        Err(_) => {
3402            yog_logging::info!("no mods directory at {} — none loaded", dir.display());
3403            return;
3404        }
3405    };
3406
3407    // First pass: collect (mod_id, dependencies, archive_path)
3408    struct ModMeta {
3409        id: String,
3410        deps: Vec<String>,
3411        yog_path: PathBuf,
3412    }
3413    let mut metas: Vec<ModMeta> = Vec::new();
3414    for entry in entries.flatten() {
3415        let path = entry.path();
3416        if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3417            continue;
3418        }
3419        let info = read_mod_info(&path);
3420        let deps = read_mod_deps(&path);
3421        metas.push(ModMeta {
3422            id: info[0].clone(),
3423            deps,
3424            yog_path: path,
3425        });
3426    }
3427
3428    // Topological sort by dependencies (Kahn's algorithm)
3429    let ids: Vec<String> = metas.iter().map(|m| m.id.clone()).collect();
3430    // Known before any registers: a mod's optional integrations with a Yog
3431    // mod loaded after it still see it.
3432    YOG_MOD_IDS.write().unwrap_or_else(|e| e.into_inner()).extend(ids.iter().cloned());
3433    let deps_list: Vec<Vec<String>> = metas.iter().map(|m| m.deps.clone()).collect();
3434    let sorted = match topo_sort_mods(&ids, &deps_list) {
3435        Some(v) => v,
3436        None => {
3437            yog_logging::error!("circular dependency detected — loading in file order");
3438            (0..metas.len()).collect()
3439        }
3440    };
3441
3442    let mut loaded: Vec<LoadedModule> = Vec::new();
3443    for idx in sorted {
3444        let meta = &metas[idx];
3445        let lib_path = match extract_yog(&meta.yog_path) {
3446            Some(p) => p,
3447            None => {
3448                yog_logging::error!(
3449                    "no native for {} in {}",
3450                    platform_tag(),
3451                    meta.yog_path.display()
3452                );
3453                continue;
3454            }
3455        };
3456        if let Some(module) = load_mod_lib(&lib_path, api, &meta.id) {
3457            loaded.push(module);
3458            #[cfg(feature = "dev")]
3459            registrations::record(&meta.id, &meta.yog_path);
3460            MOD_INFOS
3461                .lock()
3462                .expect("mod infos lock poisoned")
3463                .push(read_mod_info(&meta.yog_path));
3464        }
3465    }
3466    yog_logging::info!("loaded {} mod(s) from {}", loaded.len(), dir.display());
3467
3468    // Final import resolution pass — after all mods loaded, each mod's pending
3469    // imports can be resolved against the now-complete interop table.
3470    resolve_all_imports(api, &loaded);
3471}
3472
3473/// After all mods loaded, call `__yog_resolve_imports_final` on each library
3474/// to resolve any imports that weren't satisfied during initial registration.
3475fn resolve_all_imports(api: &YogApi, loaded: &[LoadedModule]) {
3476    for module in loaded {
3477        module.with_library(|lib| unsafe {
3478            type ResolveFn = unsafe extern "C" fn(*const YogApi);
3479            if let Ok(resolve) = lib.get::<ResolveFn>(b"__yog_resolve_imports_final") {
3480                resolve(api as *const YogApi);
3481            }
3482        });
3483    }
3484}
3485
3486/// Kahn's algorithm — returns indices in dependency order, or None on cycle.
3487fn topo_sort_mods(ids: &[String], deps_list: &[Vec<String>]) -> Option<Vec<usize>> {
3488    let n = ids.len();
3489    let name_to_idx: HashMap<&str, usize> = ids
3490        .iter()
3491        .enumerate()
3492        .map(|(i, id)| (id.as_str(), i))
3493        .collect();
3494    let mut in_degree = vec![0u32; n];
3495    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
3496    for (i, deps) in deps_list.iter().enumerate() {
3497        for dep in deps {
3498            if let Some(&j) = name_to_idx.get(dep.as_str()) {
3499                adj[j].push(i);
3500                in_degree[i] += 1;
3501            }
3502        }
3503    }
3504    let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
3505    let mut order = Vec::with_capacity(n);
3506    while let Some(u) = queue.pop() {
3507        order.push(u);
3508        for &v in &adj[u] {
3509            in_degree[v] -= 1;
3510            if in_degree[v] == 0 {
3511                queue.push(v);
3512            }
3513        }
3514    }
3515    if order.len() == n { Some(order) } else { None }
3516}
3517
3518/// Loads `path` as a fresh generation of `mod_id` via the shared
3519/// `HotReloader`, validates its ABI, and calls its `yog_mod_register` —
3520/// tagging every handler it registers with the returned `LoadedModule` (see
3521/// `current_registration()`). On any failure the module (if it got as far
3522/// as being tracked by the `HotReloader`) is retired immediately: nothing
3523/// can be executing inside a library that never successfully registered,
3524/// so this always hard-unloads right away rather than lingering.
3525fn load_mod_lib(path: &Path, api: &YogApi, mod_id: &str) -> Option<LoadedModule> {
3526    let module = match unsafe { hot_reloader().load_initial(mod_id, path) } {
3527        Ok(m) => m,
3528        Err(e) => {
3529            yog_logging::error!("failed to load {}: {}", path.display(), e);
3530            return None;
3531        }
3532    };
3533
3534    let abi = module.with_library(|lib| unsafe {
3535        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
3536        Some(abi())
3537    });
3538    match abi.flatten() {
3539        Some(v) if yog_abi::compatible(v) => {}
3540        Some(v) => {
3541            yog_logging::error!(
3542                "{}: ABI {} incompatible with runtime ABI {}",
3543                path.display(),
3544                v,
3545                ABI_VERSION
3546            );
3547            module.retire(|| {});
3548            return None;
3549        }
3550        None => {
3551            yog_logging::error!("{} is not a Yog mod (no yog_abi_version)", path.display());
3552            module.retire(|| {});
3553            return None;
3554        }
3555    }
3556
3557    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
3558        yog_logging::error!("{}: {}", path.display(), e);
3559        module.retire(|| {});
3560        return None;
3561    }
3562
3563    Some(module)
3564}
3565
3566/// Calls a loaded module's `yog_mod_register`, tagging everything it
3567/// registers with `module` via `CURRENT_REGISTRATION` for the duration of
3568/// the call — used for both a mod's initial load and a later hot-reload.
3569fn invoke_mod_register(module: &LoadedModule, api: &YogApi, mod_id: &str) -> Result<(), String> {
3570    module
3571        .with_library(|lib| unsafe {
3572            let register: Symbol<RegisterFn> = lib
3573                .get(b"yog_mod_register")
3574                .map_err(|_| "missing yog_mod_register".to_string())?;
3575            let mod_id_c = std::ffi::CString::new(mod_id).unwrap();
3576            *CURRENT_REGISTRATION.lock().unwrap() = Some(module.clone());
3577            register(api as *const YogApi, mod_id_c.as_ptr());
3578            *CURRENT_REGISTRATION.lock().unwrap() = None;
3579            Ok(())
3580        })
3581        .unwrap_or_else(|| Err("module was unloaded before registration could run".to_string()))
3582}
3583
3584/// Metadata for a mod file: [id, name, version, authors, description,
3585/// name_key, description_key].
3586/// For .yog archives this comes from the bundled yog.toml; bare native libs
3587/// fall back to the file stem.
3588fn read_mod_info(path: &Path) -> [String; 7] {
3589    let stem = path
3590        .file_stem()
3591        .map(|s| s.to_string_lossy().into_owned())
3592        .unwrap_or_default();
3593    let mut info = [
3594        stem.clone(),
3595        stem,
3596        String::new(),
3597        String::new(),
3598        String::new(),
3599        String::new(),
3600        String::new(),
3601    ];
3602    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3603        return info;
3604    }
3605    let Some(text) = (|| {
3606        let file = std::fs::File::open(path).ok()?;
3607        let mut archive = zip::ZipArchive::new(file).ok()?;
3608        let mut entry = archive.by_name("yog.toml").ok()?;
3609        let mut text = String::new();
3610        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
3611        Some(text)
3612    })() else {
3613        return info;
3614    };
3615    // Minimal parse — enough for id/name/version/description/authors without
3616    // pulling in a TOML dependency. Source manifests keep these under [mod];
3617    // the packaged manifest (written by yog-cli) has them at top level, so
3618    // keys before any section header count too.
3619    let mut in_mod = true;
3620    for line in text.lines() {
3621        let line = line.trim();
3622        if line.starts_with('[') {
3623            in_mod = line == "[mod]";
3624            continue;
3625        }
3626        if !in_mod {
3627            continue;
3628        }
3629        let Some((key, value)) = line.split_once('=') else {
3630            continue;
3631        };
3632        let key = key.trim();
3633        let value = value.trim();
3634        let unquote = |v: &str| v.trim().trim_matches('"').to_string();
3635        match key {
3636            "id" => info[0] = tsv_clean(&unquote(value)),
3637            "name" => info[1] = tsv_clean(&unquote(value)),
3638            "version" => info[2] = tsv_clean(&unquote(value)),
3639            "description" => info[4] = tsv_clean(&unquote(value)),
3640            "name_key" => info[5] = unquote(value),
3641            "description_key" => info[6] = unquote(value),
3642            "authors" => {
3643                let list = value.trim_start_matches('[').trim_end_matches(']');
3644                let authors: Vec<String> = list
3645                    .split(',')
3646                    .map(unquote)
3647                    .filter(|a| !a.is_empty())
3648                    .collect();
3649                info[3] = tsv_clean(&authors.join(", "));
3650            }
3651            _ => {}
3652        }
3653    }
3654    info
3655}
3656
3657/// Parse `[dependencies]` section from yog.toml inside a .yog archive.
3658fn read_mod_deps(path: &Path) -> Vec<String> {
3659    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3660        return Vec::new();
3661    }
3662    let text = (|| {
3663        let file = std::fs::File::open(path).ok()?;
3664        let mut archive = zip::ZipArchive::new(file).ok()?;
3665        let mut entry = archive.by_name("yog.toml").ok()?;
3666        let mut text = String::new();
3667        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
3668        Some(text)
3669    })();
3670    let Some(text) = text else { return Vec::new() };
3671    let mut deps = Vec::new();
3672    let mut in_deps = false;
3673    for line in text.lines() {
3674        let line = line.trim();
3675        if line.starts_with('[') {
3676            in_deps = line == "[dependencies]";
3677            continue;
3678        }
3679        if !in_deps {
3680            continue;
3681        }
3682        // `mod_id = "1.0"` or `mod_id = "*"` — we only care about the key (mod_id)
3683        if let Some((key, _)) = line.split_once('=') {
3684            deps.push(key.trim().to_string());
3685        }
3686    }
3687    deps
3688}
3689
3690fn extract_yog(path: &Path) -> Option<PathBuf> {
3691    let file = std::fs::File::open(path).ok()?;
3692    let mut archive = zip::ZipArchive::new(file).ok()?;
3693    let prefix = format!("natives/{}/", platform_tag());
3694    let mut entry_name = None;
3695    for i in 0..archive.len() {
3696        let f = archive.by_index(i).ok()?;
3697        let name = f.name().ok()?;
3698        if name.starts_with(&prefix) && !name.ends_with('/') {
3699            entry_name = Some(name.to_string());
3700            break;
3701        }
3702    }
3703    let entry_name = entry_name?;
3704    let ext = Path::new(&entry_name)
3705        .extension()
3706        .and_then(|e| e.to_str())
3707        .unwrap_or("bin");
3708    let stem = path.file_stem()?.to_string_lossy().into_owned();
3709    // A fresh name per extraction: a hot reload must never truncate the
3710    // library the game still has mapped, and `dlopen` of an already-loaded
3711    // path would just hand back the old module.
3712    static EXTRACTIONS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3713    let n = EXTRACTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3714    let out =
3715        std::env::temp_dir().join(format!("yog-{}-{}-{}.{}", stem, std::process::id(), n, ext));
3716    let mut entry = archive.by_name(&entry_name).ok()?;
3717    let mut out_file = std::fs::File::create(&out).ok()?;
3718    std::io::copy(&mut entry, &mut out_file).ok()?;
3719    Some(out)
3720}
3721
3722// ── Dispatcher helpers ────────────────────────────────────────────────────────
3723
3724fn srv_ptr() -> *const YogServer {
3725    SERVER.get().expect("yog: SERVER not initialised") as *const YogServer
3726}
3727
3728// ── JNI entry points ──────────────────────────────────────────────────────────
3729
3730#[unsafe(no_mangle)]
3731pub extern "system" fn Java_dev_yog_NativeBridge_nativeInit<'l>(
3732    mut env: JNIEnv<'l>,
3733    _class: JClass<'l>,
3734    mods_dir: JString<'l>,
3735) {
3736    if let Ok(vm) = env.get_java_vm() {
3737        let _ = JAVA_VM.set(vm);
3738    }
3739
3740    let dir = env
3741        .get_string(&mods_dir)
3742        .map(String::from)
3743        .unwrap_or_default();
3744
3745    // Build YogServer and store in static (gets a stable address).
3746    let _ = SERVER.set(build_server_table());
3747    let server_ptr = SERVER.get().unwrap() as *const YogServer;
3748
3749    // Publish HANDLERS *before* any mod registers — its address is then
3750    // `'static`-stable for the runtime's entire lifetime, unlike the old
3751    // design (a temporary heap `Box` moved into `HANDLERS` only after
3752    // `nativeInit` returned, silently invalidating the `ctx` pointer any
3753    // later re-registration — e.g. a hot-reload — would have needed).
3754    let handlers_lock = HANDLERS.get_or_init(|| RwLock::new(RuntimeHandlers::default()));
3755    let handlers_ptr = handlers_lock as *const RwLock<RuntimeHandlers>;
3756
3757    let api: &'static YogApi = API_TABLE.get_or_init(|| build_api_table(handlers_ptr, server_ptr));
3758
3759    let _ = HOT_RELOADER.get_or_init(|| HotReloader::new(RuntimeModuleRegistry));
3760    // A book's entries an advancement unlocks wait for this client's player to have it.
3761    yog_book::set_unlocked(client_advancement_done);
3762
3763    guard("mod loading", || {
3764        load_mods(Path::new(&dir), api);
3765    });
3766
3767    #[cfg(feature = "dev")]
3768    control_socket::start_if_requested();
3769
3770    yog_logging::info!("runtime initialised — the gate is open.");
3771}
3772
3773/// Rebuilds and re-registers `mod_id` from a freshly built `.yog` at
3774/// `new_yog_path`: extracts the current platform's native, loads it as a
3775/// new generation via the shared `HotReloader` (which retires the previous
3776/// generation per its hybrid soft/hard-unload policy — hard-unloaded right
3777/// away if nothing's mid-call, deferred otherwise), then calls its
3778/// `yog_mod_register` again so its handlers get tagged under the new
3779/// generation. How this actually gets triggered — a keybind, a file-watch,
3780/// an IDE-driven socket — is a separate, later concern; this only needs to
3781/// work correctly once called.
3782#[cfg(feature = "dev")]
3783pub(crate) fn trigger_hot_reload(mod_id: &str, new_yog_path: &Path) -> bool {
3784    let Some(native_path) = extract_yog(new_yog_path) else {
3785        yog_logging::error!(
3786            "hot-reload {}: no native for {} in {}",
3787            mod_id,
3788            platform_tag(),
3789            new_yog_path.display()
3790        );
3791        return false;
3792    };
3793
3794    let api = API_TABLE.get().expect("yog: nativeInit not called yet");
3795
3796    let module = match unsafe { hot_reloader().reload(mod_id, &native_path) } {
3797        Ok(m) => m,
3798        Err(e) => {
3799            yog_logging::error!(
3800                "hot-reload {}: failed to load {}: {}",
3801                mod_id,
3802                native_path.display(),
3803                e
3804            );
3805            return false;
3806        }
3807    };
3808
3809    let abi = module.with_library(|lib| unsafe {
3810        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
3811        Some(abi())
3812    });
3813    match abi.flatten() {
3814        Some(v) if yog_abi::compatible(v) => {}
3815        other => {
3816            yog_logging::error!(
3817                "hot-reload {}: ABI {:?} incompatible with runtime ABI {} — mod has no active handlers until a compatible reload succeeds",
3818                mod_id,
3819                other,
3820                ABI_VERSION
3821            );
3822            return false;
3823        }
3824    }
3825
3826    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
3827        yog_logging::error!("hot-reload {}: {}", mod_id, e);
3828        return false;
3829    }
3830
3831    yog_logging::info!("hot-reloaded mod {}", mod_id);
3832    true
3833}
3834
3835#[unsafe(no_mangle)]
3836pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreak<'l>(
3837    mut env: JNIEnv<'l>,
3838    _class: JClass<'l>,
3839    player: JString<'l>,
3840    block: JString<'l>,
3841    x: jint,
3842    y: jint,
3843    z: jint,
3844    dimension: JString<'l>,
3845) {
3846    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
3847    let ev = yog_abi::YogBlockBreakEvent {
3848        player: YogStr::from_str(&p),
3849        block: YogStr::from_str(&b),
3850        pos: YogBlockPos { x, y, z },
3851        dimension: YogStr::from_str(&d),
3852    };
3853    let srv = srv_ptr();
3854    guard("on_block_break", || {
3855        each(&handlers().block_break, |ud, f| unsafe {
3856            f(ud, srv, &ev, 1)
3857        });
3858    });
3859}
3860
3861#[unsafe(no_mangle)]
3862pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChat<'l>(
3863    mut env: JNIEnv<'l>,
3864    _class: JClass<'l>,
3865    player: JString<'l>,
3866    message: JString<'l>,
3867    dimension: JString<'l>,
3868) {
3869    let (p, m, d) = (
3870        jstr!(env, player),
3871        jstr!(env, message),
3872        jstr!(env, dimension),
3873    );
3874    let ev = yog_abi::YogChatEvent {
3875        player: YogStr::from_str(&p),
3876        message: YogStr::from_str(&m),
3877        dimension: YogStr::from_str(&d),
3878    };
3879    let srv = srv_ptr();
3880    guard("on_chat", || {
3881        each(&handlers().chat, |ud, f| unsafe { f(ud, srv, &ev, 1) });
3882    });
3883}
3884
3885#[unsafe(no_mangle)]
3886pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerJoin<'l>(
3887    mut env: JNIEnv<'l>,
3888    _class: JClass<'l>,
3889    player: JString<'l>,
3890    uuid: JString<'l>,
3891    dimension: JString<'l>,
3892) {
3893    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
3894    let ev = yog_abi::YogPlayerEvent {
3895        player: YogStr::from_str(&p),
3896        uuid: YogStr::from_str(&u),
3897        dimension: YogStr::from_str(&d),
3898    };
3899    let srv = srv_ptr();
3900    guard("on_player_join", || {
3901        each(&handlers().player_join, |ud, f| unsafe {
3902            f(ud, srv, &ev, 1)
3903        });
3904    });
3905    // Queue startup grants: giving items directly inside the join callback
3906    // fails for the host of a freshly created world (player not fully in the
3907    // world yet), so grants are processed a few server ticks later.
3908    let h = handlers();
3909    if !h.startup_grants.is_empty() {
3910        h.pending_grants
3911            .lock()
3912            .expect("pending_grants poisoned")
3913            .push((p, u, 0));
3914    }
3915}
3916
3917/// The command tag a player carries once startup grant `id` was given. It's
3918/// saved with the player's own data, so it follows the player — not their
3919/// name or uuid (a dev client gets a new name each launch, while a
3920/// singleplayer world's owner stays the same player).
3921fn grant_tag(id: &str) -> String {
3922    format!("yog.grant.{id}")
3923}
3924
3925/// Try to fulfil pending startup grants. Called each server tick; a grant is
3926/// only marked as given (tagged on the player) after `give_item` succeeds.
3927fn process_pending_grants() {
3928    let h = handlers();
3929    let mut pending = match h.pending_grants.try_lock() {
3930        Ok(g) => g,
3931        Err(_) => return,
3932    };
3933    if pending.is_empty() {
3934        return;
3935    }
3936    // Wait a couple of ticks after join before the first attempt.
3937    const FIRST_TRY_TICK: u32 = 2;
3938    // Give up after 30 seconds — the player probably left.
3939    const MAX_TICKS: u32 = 600;
3940
3941    let mut still_pending = Vec::new();
3942    for (p, u, ticks) in pending.drain(..) {
3943        if ticks < FIRST_TRY_TICK {
3944            still_pending.push((p, u, ticks + 1));
3945            continue;
3946        }
3947        let player = YogStr::from_str(&p);
3948        let mut all_ok = true;
3949        for sg in &h.startup_grants {
3950            let tag = grant_tag(&sg.id);
3951            let tag = YogStr::from_str(&tag);
3952            if unsafe { bridge!("playerHasTag", [S(player), S(tag)]) }.unwrap_or(false) {
3953                continue;
3954            }
3955            let book = sg.book.as_ref().map(|_| "minecraft:written_book");
3956            let mut ok = true;
3957            for item_id in sg.items.iter().map(String::as_str).chain(book) {
3958                ok &= unsafe { srv_give_item(std::ptr::null_mut(), player, YogStr::from_str(item_id), 1) };
3959            }
3960            if ok && unsafe { bridge!("addPlayerTag", [S(player), S(tag)]) }.unwrap_or(false) {
3961                yog_logging::info!("startup grant {} given to {}", sg.id, p);
3962            } else {
3963                all_ok = false;
3964            }
3965        }
3966        if !all_ok && ticks < MAX_TICKS {
3967            still_pending.push((p, u, ticks + 1));
3968        }
3969    }
3970    *pending = still_pending;
3971}
3972
3973#[unsafe(no_mangle)]
3974pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerLeave<'l>(
3975    mut env: JNIEnv<'l>,
3976    _class: JClass<'l>,
3977    player: JString<'l>,
3978    uuid: JString<'l>,
3979    dimension: JString<'l>,
3980) {
3981    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
3982    let ev = yog_abi::YogPlayerEvent {
3983        player: YogStr::from_str(&p),
3984        uuid: YogStr::from_str(&u),
3985        dimension: YogStr::from_str(&d),
3986    };
3987    let srv = srv_ptr();
3988    guard("on_player_leave", || {
3989        each(&handlers().player_leave, |ud, f| unsafe {
3990            f(ud, srv, &ev, 1)
3991        });
3992    });
3993}
3994
3995#[unsafe(no_mangle)]
3996pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItem<'l>(
3997    mut env: JNIEnv<'l>,
3998    _class: JClass<'l>,
3999    player: JString<'l>,
4000    item: JString<'l>,
4001    sneaking: jni::sys::jboolean,
4002    dimension: JString<'l>,
4003) {
4004    let (p, i, d) = (jstr!(env, player), jstr!(env, item), jstr!(env, dimension));
4005    let ev = yog_abi::YogUseItemEvent {
4006        player: YogStr::from_str(&p),
4007        item: YogStr::from_str(&i),
4008        sneaking: sneaking != 0,
4009        dimension: YogStr::from_str(&d),
4010    };
4011    let srv = srv_ptr();
4012    guard("on_use_item", || {
4013        each(&handlers().use_item, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4014    });
4015}
4016
4017#[unsafe(no_mangle)]
4018pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItemPre<'l>(
4019    mut env: JNIEnv<'l>,
4020    _class: JClass<'l>,
4021    player: JString<'l>,
4022    item: JString<'l>,
4023    sneaking: jni::sys::jboolean,
4024    dimension: JString<'l>,
4025) -> jni::sys::jboolean {
4026    let h = handlers();
4027    if h.use_item.is_empty() {
4028        return 1;
4029    }
4030    let p = jstr!(env, player, 1);
4031    let i = jstr!(env, item, 1);
4032    let d = jstr!(env, dimension, 1);
4033    let ev = yog_abi::YogUseItemEvent {
4034        player: YogStr::from_str(&p),
4035        item: YogStr::from_str(&i),
4036        sneaking: sneaking != 0,
4037        dimension: YogStr::from_str(&d),
4038    };
4039    let srv = srv_ptr();
4040    allowed(&h.use_item, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4041}
4042
4043#[unsafe(no_mangle)]
4044pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlock<'l>(
4045    mut env: JNIEnv<'l>,
4046    _class: JClass<'l>,
4047    player: JString<'l>,
4048    block: JString<'l>,
4049    x: jint,
4050    y: jint,
4051    z: jint,
4052    dimension: JString<'l>,
4053    sneaking: jni::sys::jboolean,
4054) {
4055    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
4056    let ev = yog_abi::YogUseBlockEvent {
4057        player: YogStr::from_str(&p),
4058        block: YogStr::from_str(&b),
4059        pos: YogBlockPos { x, y, z },
4060        dimension: YogStr::from_str(&d),
4061        sneaking: sneaking != 0,
4062    };
4063    let srv = srv_ptr();
4064    guard("on_use_block", || {
4065        each(&handlers().use_block, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4066    });
4067}
4068
4069#[unsafe(no_mangle)]
4070pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlockPre<'l>(
4071    mut env: JNIEnv<'l>,
4072    _class: JClass<'l>,
4073    player: JString<'l>,
4074    block: JString<'l>,
4075    x: jint,
4076    y: jint,
4077    z: jint,
4078    dimension: JString<'l>,
4079    sneaking: jni::sys::jboolean,
4080) -> jni::sys::jboolean {
4081    let h = handlers();
4082    if h.use_block.is_empty() {
4083        return 1;
4084    }
4085    let p = jstr!(env, player, 1);
4086    let b = jstr!(env, block, 1);
4087    let d = jstr!(env, dimension, 1);
4088    let ev = yog_abi::YogUseBlockEvent {
4089        player: YogStr::from_str(&p),
4090        block: YogStr::from_str(&b),
4091        pos: YogBlockPos { x, y, z },
4092        dimension: YogStr::from_str(&d),
4093        sneaking: sneaking != 0,
4094    };
4095    let srv = srv_ptr();
4096    allowed(&h.use_block, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4097}
4098
4099#[unsafe(no_mangle)]
4100pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAttackEntity<'l>(
4101    mut env: JNIEnv<'l>,
4102    _class: JClass<'l>,
4103    player: JString<'l>,
4104    target_type: JString<'l>,
4105    target_uuid: JString<'l>,
4106    dimension: JString<'l>,
4107) {
4108    let (p, tt, tu, d) = (
4109        jstr!(env, player),
4110        jstr!(env, target_type),
4111        jstr!(env, target_uuid),
4112        jstr!(env, dimension),
4113    );
4114    let ev = yog_abi::YogAttackEntityEvent {
4115        player: YogStr::from_str(&p),
4116        target_type: YogStr::from_str(&tt),
4117        target_uuid: YogStr::from_str(&tu),
4118        dimension: YogStr::from_str(&d),
4119    };
4120    let srv = srv_ptr();
4121    guard("on_attack_entity", || {
4122        each(&handlers().attack_entity, |ud, f| unsafe {
4123            f(ud, srv, &ev, 1)
4124        });
4125    });
4126}
4127
4128#[unsafe(no_mangle)]
4129pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamage<'l>(
4130    mut env: JNIEnv<'l>,
4131    _class: JClass<'l>,
4132    entity_type: JString<'l>,
4133    uuid: JString<'l>,
4134    amount: jfloat,
4135    source: JString<'l>,
4136    dimension: JString<'l>,
4137) {
4138    let (et, u, s, d) = (
4139        jstr!(env, entity_type),
4140        jstr!(env, uuid),
4141        jstr!(env, source),
4142        jstr!(env, dimension),
4143    );
4144    let ev = yog_abi::YogEntityDamageEvent {
4145        entity_type: YogStr::from_str(&et),
4146        uuid: YogStr::from_str(&u),
4147        amount,
4148        source: YogStr::from_str(&s),
4149        dimension: YogStr::from_str(&d),
4150    };
4151    let srv = srv_ptr();
4152    guard("on_entity_damage", || {
4153        each(&handlers().entity_damage, |ud, f| unsafe {
4154            f(ud, srv, &ev, 1)
4155        });
4156    });
4157}
4158
4159#[unsafe(no_mangle)]
4160pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDeath<'l>(
4161    mut env: JNIEnv<'l>,
4162    _class: JClass<'l>,
4163    entity_type: JString<'l>,
4164    uuid: JString<'l>,
4165    source: JString<'l>,
4166    dimension: JString<'l>,
4167) {
4168    let (et, u, s, d) = (
4169        jstr!(env, entity_type),
4170        jstr!(env, uuid),
4171        jstr!(env, source),
4172        jstr!(env, dimension),
4173    );
4174    let ev = yog_abi::YogEntityDeathEvent {
4175        entity_type: YogStr::from_str(&et),
4176        uuid: YogStr::from_str(&u),
4177        source: YogStr::from_str(&s),
4178        dimension: YogStr::from_str(&d),
4179    };
4180    let srv = srv_ptr();
4181    guard("on_entity_death", || {
4182        each(&handlers().entity_death, |ud, f| unsafe {
4183            f(ud, srv, &ev, 1)
4184        });
4185    });
4186}
4187
4188#[unsafe(no_mangle)]
4189pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnTick<'l>(
4190    _env: JNIEnv<'l>,
4191    _class: JClass<'l>,
4192) {
4193    let h = handlers();
4194    let srv = srv_ptr();
4195    guard("on_tick", || {
4196        each(&h.server_tick, |ud, f| unsafe { f(ud, srv) });
4197    });
4198
4199    guard("startup_grants", process_pending_grants);
4200
4201    // Entity data changed this tick, to who sees it — after the mods' ticks.
4202    guard("entity data", entity_data::flush);
4203
4204    // Scheduler: what's due this tick, run outside the lock (a task may schedule more).
4205    let due = h.scheduler.lock().expect("scheduler poisoned").due();
4206    for (module, ud, f) in due {
4207        if module.is_retiring() {
4208            continue;
4209        }
4210        let Some(_call) = module.enter() else {
4211            continue;
4212        };
4213        guard("scheduled task", || unsafe { f(ud, srv) });
4214    }
4215}
4216
4217#[unsafe(no_mangle)]
4218pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStarted<'l>(
4219    _env: JNIEnv<'l>,
4220    _class: JClass<'l>,
4221    _world_dir: JString<'l>,
4222) {
4223    // Grants pending for a previous world's players are void.
4224    handlers().pending_grants.lock().expect("pending_grants poisoned").clear();
4225    let srv = srv_ptr();
4226    guard("on_server_started", || {
4227        each(&handlers().server_started, |ud, f| unsafe { f(ud, srv) });
4228    });
4229}
4230
4231#[unsafe(no_mangle)]
4232pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStopping<'l>(
4233    _env: JNIEnv<'l>,
4234    _class: JClass<'l>,
4235) {
4236    let srv = srv_ptr();
4237    guard("on_server_stopping", || {
4238        each(&handlers().server_stopping, |ud, f| unsafe { f(ud, srv) });
4239    });
4240    entity_data::server_stopped();
4241}
4242
4243#[unsafe(no_mangle)]
4244pub extern "system" fn Java_dev_yog_NativeBridge_nativeCommandNames<'l>(
4245    env: JNIEnv<'l>,
4246    _class: JClass<'l>,
4247) -> jstring {
4248    let names = handlers()
4249        .commands
4250        .keys()
4251        .cloned()
4252        .collect::<Vec<_>>()
4253        .join("\n");
4254    env.new_string(names)
4255        .map(jni::objects::JString::into_raw)
4256        .unwrap_or(std::ptr::null_mut())
4257}
4258
4259#[unsafe(no_mangle)]
4260pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreakPre<'l>(
4261    mut env: JNIEnv<'l>,
4262    _class: JClass<'l>,
4263    player: JString<'l>,
4264    block: JString<'l>,
4265    x: jint,
4266    y: jint,
4267    z: jint,
4268    dimension: JString<'l>,
4269) -> jni::sys::jboolean {
4270    let h = handlers();
4271    if h.block_break.is_empty() {
4272        return 1;
4273    }
4274    let p = jstr!(env, player, 1);
4275    let b = jstr!(env, block, 1);
4276    let d = jstr!(env, dimension, 1);
4277    let ev = yog_abi::YogBlockBreakEvent {
4278        player: YogStr::from_str(&p),
4279        block: YogStr::from_str(&b),
4280        pos: YogBlockPos { x, y, z },
4281        dimension: YogStr::from_str(&d),
4282    };
4283    let srv = srv_ptr();
4284    allowed(&h.block_break, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4285}
4286
4287#[unsafe(no_mangle)]
4288pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChatPre<'l>(
4289    mut env: JNIEnv<'l>,
4290    _class: JClass<'l>,
4291    player: JString<'l>,
4292    message: JString<'l>,
4293    dimension: JString<'l>,
4294) -> jni::sys::jboolean {
4295    let h = handlers();
4296    if h.chat.is_empty() {
4297        return 1;
4298    }
4299    let p = jstr!(env, player, 1);
4300    let m = jstr!(env, message, 1);
4301    let d = jstr!(env, dimension, 1);
4302    let ev = yog_abi::YogChatEvent {
4303        player: YogStr::from_str(&p),
4304        message: YogStr::from_str(&m),
4305        dimension: YogStr::from_str(&d),
4306    };
4307    let srv = srv_ptr();
4308    allowed(&h.chat, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4309}
4310
4311/// Called by a registered chunk-generator closure (via `ChunkWriter::set_block`)
4312/// to place one block in the chunk currently being generated. Calls back
4313/// into `YogCallbackChunkGenerator.setBlockInGeneratingChunk` on the Java
4314/// side — same thread, since the whole round trip is synchronous.
4315unsafe extern "C" fn chunk_writer_set_block(
4316    _ctx: *mut c_void,
4317    x: i32,
4318    y: i32,
4319    z: i32,
4320    block_id: YogStr,
4321) -> bool {
4322    unsafe {
4323        host!(
4324            "dev/yog/YogCallbackChunkGenerator",
4325            "setBlockInGeneratingChunk",
4326            [I(x), I(y), I(z), S(block_id)]
4327        )
4328        .unwrap_or(false)
4329    }
4330}
4331
4332#[unsafe(no_mangle)]
4333pub extern "system" fn Java_dev_yog_NativeBridge_nativeGenerateChunk<'l>(
4334    mut env: JNIEnv<'l>,
4335    _class: JClass<'l>,
4336    generator_type_id: JString<'l>,
4337    chunk_x: jint,
4338    chunk_z: jint,
4339    min_y: jint,
4340    height: jint,
4341) {
4342    let id: String = match env.get_string(&generator_type_id) {
4343        Ok(s) => String::from(s),
4344        Err(_) => return,
4345    };
4346    let terrain = handlers().terrains.get(&id).cloned();
4347    if let Some(g) = terrain {
4348        guard("chunk_generator", || {
4349            g.generate(chunk_x, chunk_z, min_y, height, |x, y, z, block| unsafe {
4350                chunk_writer_set_block(std::ptr::null_mut(), x, y, z, YogStr::from_str(block));
4351            });
4352        });
4353        return;
4354    }
4355    let Some((module, ud, cb)) = handlers().chunk_generators.get(&id).cloned() else {
4356        return;
4357    };
4358    if module.is_retiring() {
4359        return;
4360    }
4361    let Some(_call) = module.enter() else { return };
4362    let writer = yog_abi::YogChunkWriterApi {
4363        chunk_x,
4364        chunk_z,
4365        min_y,
4366        height,
4367        ctx: std::ptr::null_mut(),
4368        set_block: chunk_writer_set_block,
4369    };
4370    guard("chunk_generator", || unsafe {
4371        cb(ud, &writer as *const _);
4372    });
4373}
4374
4375#[unsafe(no_mangle)]
4376pub extern "system" fn Java_dev_yog_NativeBridge_nativeTypedCommandSchemas<'l>(
4377    env: JNIEnv<'l>,
4378    _class: JClass<'l>,
4379) -> jstring {
4380    // One line per DISTINCT (name, schema) pair — a name can have several
4381    // typed registrations (different arg shapes); Brigadier merges repeated
4382    // `dispatcher.register()` calls for the same literal name into one tree,
4383    // so the Java side just needs every distinct schema once each.
4384    let mut lines = Vec::new();
4385    for (name, regs) in handlers().commands.iter() {
4386        let mut seen = std::collections::HashSet::new();
4387        for (_module, schema, _, _) in regs {
4388            if let Some(schema) = schema
4389                && seen.insert(schema.as_str())
4390            {
4391                lines.push(format!("{name}\t{schema}"));
4392            }
4393        }
4394    }
4395    env.new_string(lines.join("\n"))
4396        .map(jni::objects::JString::into_raw)
4397        .unwrap_or(std::ptr::null_mut())
4398}
4399
4400#[unsafe(no_mangle)]
4401pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnCommand<'l>(
4402    mut env: JNIEnv<'l>,
4403    _class: JClass<'l>,
4404    name: JString<'l>,
4405    args: JString<'l>,
4406    source: JString<'l>,
4407    uuid: JString<'l>,
4408    dimension: JString<'l>,
4409) -> jstring {
4410    let (n, a, s, u, d) = (
4411        env.get_string(&name).map(String::from).unwrap_or_default(),
4412        env.get_string(&args).map(String::from).unwrap_or_default(),
4413        env.get_string(&source)
4414            .map(String::from)
4415            .unwrap_or_default(),
4416        env.get_string(&uuid).map(String::from).unwrap_or_default(),
4417        env.get_string(&dimension)
4418            .map(String::from)
4419            .unwrap_or_default(),
4420    );
4421    let h = handlers();
4422    let srv = srv_ptr();
4423    let args: Vec<&str> = if a.is_empty() { Vec::new() } else { a.split('\t').collect() };
4424    // One handler with `args`; its reply, or `None` when it passed.
4425    let call = |ud: &*mut c_void, f: &YogCommandFn, args: &str| -> Option<String> {
4426        let ev = yog_abi::YogCommandEvent {
4427            name: YogStr::from_str(&n),
4428            args: YogStr::from_str(args),
4429            source: YogStr::from_str(&s),
4430            uuid: YogStr::from_str(&u),
4431            dimension: YogStr::from_str(&d),
4432        };
4433        let mut buf = [0u8; 4096];
4434        let mut reply_len: u32 = 0;
4435        unsafe { f(*ud, srv, &ev, buf.as_mut_ptr(), buf.len() as u32, &mut reply_len) };
4436        (reply_len > 0).then(|| String::from_utf8_lossy(&buf[..reply_len as usize]).into_owned())
4437    };
4438    let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4439        let Some(regs) = h.commands.get(&n) else {
4440            return String::new();
4441        };
4442        let live = regs.iter().filter(|(module, ..)| !module.is_retiring());
4443        // 1. Typed handlers whose schema has exactly these many args.
4444        // 2. Ones ending in a `string`, with the extra words joined into it
4445        //    (the game may have parsed them as separate words).
4446        // 3. Plain (schema-less) handlers, with whatever was typed.
4447        for pass in 0..3 {
4448            for (module, schema, ud, f) in live.clone() {
4449                let joined;
4450                let these = match (pass, schema) {
4451                    (0, Some(schema)) if schema.split_whitespace().count() == args.len() => a.as_str(),
4452                    (1, Some(schema)) => {
4453                        let types: Vec<&str> = schema.split_whitespace().collect();
4454                        let k = types.len();
4455                        if types.last() != Some(&"string") || k == 0 || args.len() <= k {
4456                            continue;
4457                        }
4458                        let mut parts: Vec<String> = args[..k - 1].iter().map(|x| x.to_string()).collect();
4459                        parts.push(args[k - 1..].join(" "));
4460                        joined = parts.join("\t");
4461                        joined.as_str()
4462                    }
4463                    (2, None) => a.as_str(),
4464                    _ => continue,
4465                };
4466                let Some(_call) = module.enter() else {
4467                    continue;
4468                };
4469                if let Some(r) = call(ud, f, these) {
4470                    return r;
4471                }
4472            }
4473        }
4474        String::new()
4475    }))
4476    .unwrap_or_else(|_| {
4477        yog_logging::error!("a mod panicked handling command `{}`", n);
4478        String::new()
4479    });
4480
4481    env.new_string(reply)
4482        .map(jni::objects::JString::into_raw)
4483        .unwrap_or(std::ptr::null_mut())
4484}
4485
4486/// Everything the host registers as one Yog Data blob (see `content_blob`),
4487/// built on the first call and kept.
4488#[unsafe(no_mangle)]
4489pub extern "system" fn Java_dev_yog_NativeBridge_nativeContent<'l>(
4490    env: JNIEnv<'l>,
4491    _class: JClass<'l>,
4492) -> jni::sys::jbyteArray {
4493    let h = handlers();
4494    let bytes = {
4495        let mut cached = h.content_blob.lock().unwrap_or_else(|e| e.into_inner());
4496        cached.get_or_insert_with(|| std::sync::Arc::new(content_blob::blob(&h))).clone()
4497    };
4498    env.byte_array_from_slice(&bytes)
4499        .map(|a| a.into_raw())
4500        .unwrap_or(std::ptr::null_mut())
4501}
4502
4503#[unsafe(no_mangle)]
4504pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPacket<'l>(
4505    mut env: JNIEnv<'l>,
4506    _class: JClass<'l>,
4507    channel: JString<'l>,
4508    player: JString<'l>,
4509    payload: JByteArray<'l>,
4510) {
4511    let ch = env
4512        .get_string(&channel)
4513        .map(String::from)
4514        .unwrap_or_default();
4515    let pl = env
4516        .get_string(&player)
4517        .map(String::from)
4518        .unwrap_or_default();
4519    let data = env.convert_byte_array(&payload).unwrap_or_default();
4520    let ev = yog_abi::YogPacketEvent {
4521        channel: YogStr::from_str(&ch),
4522        player: YogStr::from_str(&pl),
4523        payload: data.as_ptr(),
4524        payload_len: data.len() as u32,
4525    };
4526    let h = handlers();
4527    let srv = srv_ptr();
4528    guard("on_packet", || {
4529        if let Some((module, ud, f)) = h.packets.get(&ch) {
4530            if module.is_retiring() {
4531                return;
4532            }
4533            let Some(_call) = module.enter() else { return };
4534            unsafe { f(*ud, srv, &ev) };
4535        }
4536    });
4537}
4538
4539#[unsafe(no_mangle)]
4540pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientPacket<'l>(
4541    mut env: JNIEnv<'l>,
4542    _class: JClass<'l>,
4543    channel: JString<'l>,
4544    payload: JByteArray<'l>,
4545) {
4546    let ch = env
4547        .get_string(&channel)
4548        .map(String::from)
4549        .unwrap_or_default();
4550    let data = env.convert_byte_array(&payload).unwrap_or_default();
4551    if ch == entity_data::CHANNEL {
4552        guard("entity data", || entity_data::receive(&data));
4553        return;
4554    }
4555    let ev = yog_abi::YogPacketEvent {
4556        channel: YogStr::from_str(&ch),
4557        player: YogStr::EMPTY,
4558        payload: data.as_ptr(),
4559        payload_len: data.len() as u32,
4560    };
4561    let h = handlers();
4562    let srv = srv_ptr();
4563    guard("on_client_packet", || {
4564        if let Some((module, ud, f)) = h.client_packets.get(&ch) {
4565            if module.is_retiring() {
4566                return;
4567            }
4568            let Some(_call) = module.enter() else { return };
4569            unsafe { f(*ud, srv, &ev) };
4570        }
4571    });
4572}
4573
4574#[unsafe(no_mangle)]
4575pub extern "system" fn Java_dev_yog_NativeBridge_nativePacketChannels<'l>(
4576    env: JNIEnv<'l>,
4577    _class: JClass<'l>,
4578) -> jstring {
4579    let s = handlers()
4580        .packets
4581        .keys()
4582        .cloned()
4583        .collect::<Vec<_>>()
4584        .join("\n");
4585    env.new_string(s)
4586        .map(jni::objects::JString::into_raw)
4587        .unwrap_or(std::ptr::null_mut())
4588}
4589
4590#[unsafe(no_mangle)]
4591pub extern "system" fn Java_dev_yog_NativeBridge_nativeClientPacketChannels<'l>(
4592    env: JNIEnv<'l>,
4593    _class: JClass<'l>,
4594) -> jstring {
4595    let s = handlers()
4596        .client_packets
4597        .keys()
4598        .cloned()
4599        .chain([entity_data::CHANNEL.to_owned()])
4600        .collect::<Vec<_>>()
4601        .join("\n");
4602    env.new_string(s)
4603        .map(jni::objects::JString::into_raw)
4604        .unwrap_or(std::ptr::null_mut())
4605}
4606
4607#[unsafe(no_mangle)]
4608pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawn<'l>(
4609    mut env: JNIEnv<'l>,
4610    _class: JClass<'l>,
4611    entity_type: JString<'l>,
4612    uuid: JString<'l>,
4613    dimension: JString<'l>,
4614) {
4615    let h = handlers();
4616    if h.entity_spawn.is_empty() {
4617        return;
4618    }
4619    let (et, u, d) = (
4620        jstr!(env, entity_type),
4621        jstr!(env, uuid),
4622        jstr!(env, dimension),
4623    );
4624    let ev = yog_abi::YogEntitySpawnEvent {
4625        entity_type: YogStr::from_str(&et),
4626        uuid: YogStr::from_str(&u),
4627        dimension: YogStr::from_str(&d),
4628    };
4629    let srv = srv_ptr();
4630    guard("on_entity_spawn", || {
4631        each(&h.entity_spawn, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4632    });
4633}
4634
4635#[unsafe(no_mangle)]
4636pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawnPre<'l>(
4637    mut env: JNIEnv<'l>,
4638    _class: JClass<'l>,
4639    entity_type: JString<'l>,
4640    uuid: JString<'l>,
4641    dimension: JString<'l>,
4642) -> jni::sys::jboolean {
4643    let h = handlers();
4644    if h.entity_spawn.is_empty() {
4645        return 1;
4646    }
4647    let et = jstr!(env, entity_type, 1);
4648    let u = jstr!(env, uuid, 1);
4649    let d = jstr!(env, dimension, 1);
4650    let ev = yog_abi::YogEntitySpawnEvent {
4651        entity_type: YogStr::from_str(&et),
4652        uuid: YogStr::from_str(&u),
4653        dimension: YogStr::from_str(&d),
4654    };
4655    let srv = srv_ptr();
4656    allowed(&h.entity_spawn, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4657}
4658
4659#[unsafe(no_mangle)]
4660pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamagePre<'l>(
4661    mut env: JNIEnv<'l>,
4662    _class: JClass<'l>,
4663    entity_type: JString<'l>,
4664    uuid: JString<'l>,
4665    amount: jfloat,
4666    source: JString<'l>,
4667    dimension: JString<'l>,
4668) -> jni::sys::jboolean {
4669    let h = handlers();
4670    if h.entity_damage.is_empty() {
4671        return 1;
4672    }
4673    let et = jstr!(env, entity_type, 1);
4674    let u = jstr!(env, uuid, 1);
4675    let s = jstr!(env, source, 1);
4676    let d = jstr!(env, dimension, 1);
4677    let ev = yog_abi::YogEntityDamageEvent {
4678        entity_type: YogStr::from_str(&et),
4679        uuid: YogStr::from_str(&u),
4680        amount,
4681        source: YogStr::from_str(&s),
4682        dimension: YogStr::from_str(&d),
4683    };
4684    let srv = srv_ptr();
4685    allowed(&h.entity_damage, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4686}
4687
4688#[unsafe(no_mangle)]
4689pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlockPre<'l>(
4690    mut env: JNIEnv<'l>,
4691    _class: JClass<'l>,
4692    player: JString<'l>,
4693    block: JString<'l>,
4694    x: jint,
4695    y: jint,
4696    z: jint,
4697    dimension: JString<'l>,
4698    sneaking: jni::sys::jboolean,
4699) -> jni::sys::jboolean {
4700    let h = handlers();
4701    if h.player_place_block.is_empty() {
4702        return 1;
4703    }
4704    let p = jstr!(env, player, 1);
4705    let b = jstr!(env, block, 1);
4706    let d = jstr!(env, dimension, 1);
4707    let ev = YogPlaceBlockEvent {
4708        player: YogStr::from_str(&p),
4709        block: YogStr::from_str(&b),
4710        pos: YogBlockPos { x, y, z },
4711        dimension: YogStr::from_str(&d),
4712        sneaking: sneaking != 0,
4713    };
4714    let srv = srv_ptr();
4715    allowed(&h.player_place_block, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4716}
4717
4718#[unsafe(no_mangle)]
4719pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlock<'l>(
4720    mut env: JNIEnv<'l>,
4721    _class: JClass<'l>,
4722    player: JString<'l>,
4723    block: JString<'l>,
4724    x: jint,
4725    y: jint,
4726    z: jint,
4727    dimension: JString<'l>,
4728    sneaking: jni::sys::jboolean,
4729) {
4730    let h = handlers();
4731    if h.player_place_block.is_empty() {
4732        return;
4733    }
4734    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
4735    let ev = YogPlaceBlockEvent {
4736        player: YogStr::from_str(&p),
4737        block: YogStr::from_str(&b),
4738        pos: YogBlockPos { x, y, z },
4739        dimension: YogStr::from_str(&d),
4740        sneaking: sneaking != 0,
4741    };
4742    let srv = srv_ptr();
4743    guard("on_player_place_block", || {
4744        each(&h.player_place_block, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4745    });
4746}
4747
4748#[unsafe(no_mangle)]
4749pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeathPre<'l>(
4750    mut env: JNIEnv<'l>,
4751    _class: JClass<'l>,
4752    player: JString<'l>,
4753    uuid: JString<'l>,
4754    source: JString<'l>,
4755    dimension: JString<'l>,
4756) -> jni::sys::jboolean {
4757    let h = handlers();
4758    if h.player_death.is_empty() {
4759        return 1;
4760    }
4761    let p = jstr!(env, player, 1);
4762    let u = jstr!(env, uuid, 1);
4763    let s = jstr!(env, source, 1);
4764    let d = jstr!(env, dimension, 1);
4765    let ev = YogPlayerDeathEvent {
4766        player: YogStr::from_str(&p),
4767        uuid: YogStr::from_str(&u),
4768        source: YogStr::from_str(&s),
4769        dimension: YogStr::from_str(&d),
4770    };
4771    let srv = srv_ptr();
4772    allowed(&h.player_death, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4773}
4774
4775#[unsafe(no_mangle)]
4776pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeath<'l>(
4777    mut env: JNIEnv<'l>,
4778    _class: JClass<'l>,
4779    player: JString<'l>,
4780    uuid: JString<'l>,
4781    source: JString<'l>,
4782    dimension: JString<'l>,
4783) {
4784    let h = handlers();
4785    if h.player_death.is_empty() {
4786        return;
4787    }
4788    let (p, u, s, d) = (
4789        jstr!(env, player),
4790        jstr!(env, uuid),
4791        jstr!(env, source),
4792        jstr!(env, dimension),
4793    );
4794    let ev = YogPlayerDeathEvent {
4795        player: YogStr::from_str(&p),
4796        uuid: YogStr::from_str(&u),
4797        source: YogStr::from_str(&s),
4798        dimension: YogStr::from_str(&d),
4799    };
4800    let srv = srv_ptr();
4801    guard("on_player_death", || {
4802        each(&h.player_death, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4803    });
4804}
4805
4806#[unsafe(no_mangle)]
4807pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerRespawn<'l>(
4808    mut env: JNIEnv<'l>,
4809    _class: JClass<'l>,
4810    player: JString<'l>,
4811    uuid: JString<'l>,
4812    at_anchor: jni::sys::jboolean,
4813    dimension: JString<'l>,
4814) {
4815    let h = handlers();
4816    if h.player_respawn.is_empty() {
4817        return;
4818    }
4819    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4820    let ev = YogPlayerRespawnEvent {
4821        player: YogStr::from_str(&p),
4822        uuid: YogStr::from_str(&u),
4823        at_anchor: at_anchor != 0,
4824        dimension: YogStr::from_str(&d),
4825    };
4826    let srv = srv_ptr();
4827    guard("on_player_respawn", || {
4828        each(&h.player_respawn, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4829    });
4830}
4831
4832#[unsafe(no_mangle)]
4833pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAdvancement<'l>(
4834    mut env: JNIEnv<'l>,
4835    _class: JClass<'l>,
4836    player: JString<'l>,
4837    uuid: JString<'l>,
4838    advancement: JString<'l>,
4839    dimension: JString<'l>,
4840) {
4841    let h = handlers();
4842    if h.advancement.is_empty() {
4843        return;
4844    }
4845    let (p, u, a, d) = (
4846        jstr!(env, player),
4847        jstr!(env, uuid),
4848        jstr!(env, advancement),
4849        jstr!(env, dimension),
4850    );
4851    let ev = YogAdvancementEvent {
4852        player: YogStr::from_str(&p),
4853        uuid: YogStr::from_str(&u),
4854        advancement: YogStr::from_str(&a),
4855        dimension: YogStr::from_str(&d),
4856    };
4857    let srv = srv_ptr();
4858    guard("on_advancement", || {
4859        each(&h.advancement, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4860    });
4861}
4862
4863#[unsafe(no_mangle)]
4864pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteractPre<'l>(
4865    mut env: JNIEnv<'l>,
4866    _class: JClass<'l>,
4867    player: JString<'l>,
4868    player_uuid: JString<'l>,
4869    entity_type: JString<'l>,
4870    entity_uuid: JString<'l>,
4871    hand: JString<'l>,
4872    dimension: JString<'l>,
4873) -> jni::sys::jboolean {
4874    let h = handlers();
4875    if h.entity_interact.is_empty() {
4876        return 1;
4877    }
4878    let p = jstr!(env, player, 1);
4879    let pu = jstr!(env, player_uuid, 1);
4880    let et = jstr!(env, entity_type, 1);
4881    let eu = jstr!(env, entity_uuid, 1);
4882    let ha = jstr!(env, hand, 1);
4883    let d = jstr!(env, dimension, 1);
4884    let ev = YogEntityInteractEvent {
4885        player: YogStr::from_str(&p),
4886        player_uuid: YogStr::from_str(&pu),
4887        entity_type: YogStr::from_str(&et),
4888        entity_uuid: YogStr::from_str(&eu),
4889        hand: YogStr::from_str(&ha),
4890        dimension: YogStr::from_str(&d),
4891    };
4892    let srv = srv_ptr();
4893    allowed(&h.entity_interact, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4894}
4895
4896#[unsafe(no_mangle)]
4897pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteract<'l>(
4898    mut env: JNIEnv<'l>,
4899    _class: JClass<'l>,
4900    player: JString<'l>,
4901    player_uuid: JString<'l>,
4902    entity_type: JString<'l>,
4903    entity_uuid: JString<'l>,
4904    hand: JString<'l>,
4905    dimension: JString<'l>,
4906) {
4907    let h = handlers();
4908    if h.entity_interact.is_empty() {
4909        return;
4910    }
4911    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
4912    let (et, eu, ha, d) = (
4913        jstr!(env, entity_type),
4914        jstr!(env, entity_uuid),
4915        jstr!(env, hand),
4916        jstr!(env, dimension),
4917    );
4918    let ev = YogEntityInteractEvent {
4919        player: YogStr::from_str(&p),
4920        player_uuid: YogStr::from_str(&pu),
4921        entity_type: YogStr::from_str(&et),
4922        entity_uuid: YogStr::from_str(&eu),
4923        hand: YogStr::from_str(&ha),
4924        dimension: YogStr::from_str(&d),
4925    };
4926    let srv = srv_ptr();
4927    guard("on_entity_interact", || {
4928        each(&h.entity_interact, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4929    });
4930}
4931
4932#[unsafe(no_mangle)]
4933pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemCraft<'l>(
4934    mut env: JNIEnv<'l>,
4935    _class: JClass<'l>,
4936    player: JString<'l>,
4937    player_uuid: JString<'l>,
4938    result_item: JString<'l>,
4939    result_count: jint,
4940    dimension: JString<'l>,
4941) {
4942    let h = handlers();
4943    if h.item_craft.is_empty() {
4944        return;
4945    }
4946    let (p, pu, ri, d) = (
4947        jstr!(env, player),
4948        jstr!(env, player_uuid),
4949        jstr!(env, result_item),
4950        jstr!(env, dimension),
4951    );
4952    let ev = YogCraftEvent {
4953        player: YogStr::from_str(&p),
4954        player_uuid: YogStr::from_str(&pu),
4955        result_item: YogStr::from_str(&ri),
4956        result_count: result_count as u32,
4957        dimension: YogStr::from_str(&d),
4958    };
4959    let srv = srv_ptr();
4960    guard("on_item_craft", || {
4961        each(&h.item_craft, |ud, f| unsafe { f(ud, srv, &ev, 1) });
4962    });
4963}
4964
4965#[unsafe(no_mangle)]
4966pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosionPre<'l>(
4967    mut env: JNIEnv<'l>,
4968    _class: JClass<'l>,
4969    dimension: JString<'l>,
4970    x: jdouble,
4971    y: jdouble,
4972    z: jdouble,
4973    power: jfloat,
4974    cause_uuid: JString<'l>,
4975) -> jni::sys::jboolean {
4976    let h = handlers();
4977    if h.explosion.is_empty() {
4978        return 1;
4979    }
4980    let d = jstr!(env, dimension, 1);
4981    let cu = jstr!(env, cause_uuid, 1);
4982    let ev = YogExplosionEvent {
4983        dimension: YogStr::from_str(&d),
4984        x,
4985        y,
4986        z,
4987        power,
4988        cause_uuid: YogStr::from_str(&cu),
4989    };
4990    let srv = srv_ptr();
4991    allowed(&h.explosion, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
4992}
4993
4994#[unsafe(no_mangle)]
4995pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosion<'l>(
4996    mut env: JNIEnv<'l>,
4997    _class: JClass<'l>,
4998    dimension: JString<'l>,
4999    x: jdouble,
5000    y: jdouble,
5001    z: jdouble,
5002    power: jfloat,
5003    cause_uuid: JString<'l>,
5004) {
5005    let h = handlers();
5006    if h.explosion.is_empty() {
5007        return;
5008    }
5009    let (d, cu) = (jstr!(env, dimension), jstr!(env, cause_uuid));
5010    let ev = YogExplosionEvent {
5011        dimension: YogStr::from_str(&d),
5012        x,
5013        y,
5014        z,
5015        power,
5016        cause_uuid: YogStr::from_str(&cu),
5017    };
5018    let srv = srv_ptr();
5019    guard("on_explosion", || {
5020        each(&h.explosion, |ud, f| unsafe { f(ud, srv, &ev, 1) });
5021    });
5022}
5023
5024// ── item insert JNI entry points ─────────────────────────────────────────────
5025
5026/// A hopper or dropper offers an item to a block that accepts items:
5027/// `simulate` asks whether it would take it (Pre), else it takes it (Post).
5028#[unsafe(no_mangle)]
5029pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemInsert<'l>(
5030    mut env: JNIEnv<'l>,
5031    _class: JClass<'l>,
5032    block: JString<'l>,
5033    x: jint,
5034    y: jint,
5035    z: jint,
5036    dimension: JString<'l>,
5037    item_id: JString<'l>,
5038    count: jint,
5039    nbt: JString<'l>,
5040    simulate: jni::sys::jboolean,
5041) -> jni::sys::jboolean {
5042    let h = handlers();
5043    if h.item_insert.is_empty() {
5044        return 0;
5045    }
5046    let (b, d, i, n) = (jstr!(env, block, 0), jstr!(env, dimension, 0), jstr!(env, item_id, 0), jstr!(env, nbt, 0));
5047    let ev = YogItemInsertEvent {
5048        block: YogStr::from_str(&b),
5049        pos: YogBlockPos { x, y, z },
5050        dimension: YogStr::from_str(&d),
5051        item_id: YogStr::from_str(&i),
5052        count: count.max(0) as u32,
5053        nbt: YogStr::from_str(&n),
5054    };
5055    let srv = srv_ptr();
5056    if simulate != 0 {
5057        // Some handler takes it.
5058        !allowed(&h.item_insert, |ud, f| unsafe { !f(ud, srv, &ev, 0) }) as jni::sys::jboolean
5059    } else {
5060        let mut taken = false;
5061        guard("on_item_insert", || {
5062            each(&h.item_insert, |ud, f| taken |= unsafe { f(ud, srv, &ev, 1) });
5063        });
5064        taken as jni::sys::jboolean
5065    }
5066}
5067
5068// ── ABI minor 9 JNI entry points ─────────────────────────────────────────────
5069
5070#[unsafe(no_mangle)]
5071pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickupPre<'l>(
5072    mut env: JNIEnv<'l>,
5073    _class: JClass<'l>,
5074    player: JString<'l>,
5075    player_uuid: JString<'l>,
5076    item_id: JString<'l>,
5077    item_count: jint,
5078    entity_uuid: JString<'l>,
5079    dimension: JString<'l>,
5080) -> jni::sys::jboolean {
5081    let h = handlers();
5082    if h.item_pickup.is_empty() {
5083        return 1;
5084    }
5085    let p = jstr!(env, player, 1);
5086    let pu = jstr!(env, player_uuid, 1);
5087    let ii = jstr!(env, item_id, 1);
5088    let eu = jstr!(env, entity_uuid, 1);
5089    let d = jstr!(env, dimension, 1);
5090    let ev = YogItemPickupEvent {
5091        player: YogStr::from_str(&p),
5092        player_uuid: YogStr::from_str(&pu),
5093        item_id: YogStr::from_str(&ii),
5094        item_count: item_count as u32,
5095        entity_uuid: YogStr::from_str(&eu),
5096        dimension: YogStr::from_str(&d),
5097    };
5098    let srv = srv_ptr();
5099    allowed(&h.item_pickup, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
5100}
5101
5102#[unsafe(no_mangle)]
5103pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickup<'l>(
5104    mut env: JNIEnv<'l>,
5105    _class: JClass<'l>,
5106    player: JString<'l>,
5107    player_uuid: JString<'l>,
5108    item_id: JString<'l>,
5109    item_count: jint,
5110    entity_uuid: JString<'l>,
5111    dimension: JString<'l>,
5112) {
5113    let h = handlers();
5114    if h.item_pickup.is_empty() {
5115        return;
5116    }
5117    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
5118    let (ii, eu, d) = (
5119        jstr!(env, item_id),
5120        jstr!(env, entity_uuid),
5121        jstr!(env, dimension),
5122    );
5123    let ev = YogItemPickupEvent {
5124        player: YogStr::from_str(&p),
5125        player_uuid: YogStr::from_str(&pu),
5126        item_id: YogStr::from_str(&ii),
5127        item_count: item_count as u32,
5128        entity_uuid: YogStr::from_str(&eu),
5129        dimension: YogStr::from_str(&d),
5130    };
5131    let srv = srv_ptr();
5132    guard("on_item_pickup", || {
5133        each(&h.item_pickup, |ud, f| unsafe { f(ud, srv, &ev, 1) });
5134    });
5135}
5136
5137#[unsafe(no_mangle)]
5138pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerMove<'l>(
5139    mut env: JNIEnv<'l>,
5140    _class: JClass<'l>,
5141    player: JString<'l>,
5142    player_uuid: JString<'l>,
5143    x: jdouble,
5144    y: jdouble,
5145    z: jdouble,
5146    yaw: jfloat,
5147    pitch: jfloat,
5148    dimension: JString<'l>,
5149) {
5150    let h = handlers();
5151    if h.player_move.is_empty() {
5152        return;
5153    }
5154    let (p, pu, d) = (
5155        jstr!(env, player),
5156        jstr!(env, player_uuid),
5157        jstr!(env, dimension),
5158    );
5159    let ev = YogPlayerMoveEvent {
5160        player: YogStr::from_str(&p),
5161        player_uuid: YogStr::from_str(&pu),
5162        x,
5163        y,
5164        z,
5165        yaw,
5166        pitch,
5167        dimension: YogStr::from_str(&d),
5168    };
5169    let srv = srv_ptr();
5170    guard("on_player_move", || {
5171        each(&h.player_move, |ud, f| unsafe { f(ud, srv, &ev, 1) });
5172    });
5173}
5174
5175#[unsafe(no_mangle)]
5176pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpenPre<'l>(
5177    mut env: JNIEnv<'l>,
5178    _class: JClass<'l>,
5179    player: JString<'l>,
5180    player_uuid: JString<'l>,
5181    dimension: JString<'l>,
5182) -> jni::sys::jboolean {
5183    let h = handlers();
5184    if h.container_open.is_empty() {
5185        return 1;
5186    }
5187    let p = jstr!(env, player, 1);
5188    let pu = jstr!(env, player_uuid, 1);
5189    let d = jstr!(env, dimension, 1);
5190    let ev = YogContainerOpenEvent {
5191        player: YogStr::from_str(&p),
5192        player_uuid: YogStr::from_str(&pu),
5193        container_type: YogStr::EMPTY,
5194        dimension: YogStr::from_str(&d),
5195    };
5196    let srv = srv_ptr();
5197    allowed(&h.container_open, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
5198}
5199
5200#[unsafe(no_mangle)]
5201pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpen<'l>(
5202    mut env: JNIEnv<'l>,
5203    _class: JClass<'l>,
5204    player: JString<'l>,
5205    player_uuid: JString<'l>,
5206    container_type: JString<'l>,
5207    dimension: JString<'l>,
5208) {
5209    let h = handlers();
5210    if h.container_open.is_empty() {
5211        return;
5212    }
5213    let (p, pu, ct, d) = (
5214        jstr!(env, player),
5215        jstr!(env, player_uuid),
5216        jstr!(env, container_type),
5217        jstr!(env, dimension),
5218    );
5219    let ev = YogContainerOpenEvent {
5220        player: YogStr::from_str(&p),
5221        player_uuid: YogStr::from_str(&pu),
5222        container_type: YogStr::from_str(&ct),
5223        dimension: YogStr::from_str(&d),
5224    };
5225    let srv = srv_ptr();
5226    guard("on_container_open", || {
5227        each(&h.container_open, |ud, f| unsafe { f(ud, srv, &ev, 1) });
5228    });
5229}
5230
5231#[unsafe(no_mangle)]
5232pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerClose<'l>(
5233    mut env: JNIEnv<'l>,
5234    _class: JClass<'l>,
5235    player: JString<'l>,
5236    player_uuid: JString<'l>,
5237    dimension: JString<'l>,
5238) {
5239    let h = handlers();
5240    if h.container_close.is_empty() {
5241        return;
5242    }
5243    let (p, pu, d) = (
5244        jstr!(env, player),
5245        jstr!(env, player_uuid),
5246        jstr!(env, dimension),
5247    );
5248    let ev = YogContainerCloseEvent {
5249        player: YogStr::from_str(&p),
5250        player_uuid: YogStr::from_str(&pu),
5251        dimension: YogStr::from_str(&d),
5252    };
5253    let srv = srv_ptr();
5254    guard("on_container_close", || {
5255        each(&h.container_close, |ud, f| unsafe { f(ud, srv, &ev, 1) });
5256    });
5257}
5258
5259#[unsafe(no_mangle)]
5260pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHitPre<'l>(
5261    mut env: JNIEnv<'l>,
5262    _class: JClass<'l>,
5263    projectile_type: JString<'l>,
5264    projectile_uuid: JString<'l>,
5265    shooter_uuid: JString<'l>,
5266    hit_type: JString<'l>,
5267    hit_entity_uuid: JString<'l>,
5268    x: jdouble,
5269    y: jdouble,
5270    z: jdouble,
5271    dimension: JString<'l>,
5272) -> jni::sys::jboolean {
5273    let h = handlers();
5274    if h.projectile_hit.is_empty() {
5275        return 1;
5276    }
5277    let pt = jstr!(env, projectile_type, 1);
5278    let pu = jstr!(env, projectile_uuid, 1);
5279    let su = jstr!(env, shooter_uuid, 1);
5280    let ht = jstr!(env, hit_type, 1);
5281    let heu = jstr!(env, hit_entity_uuid, 1);
5282    let dim = jstr!(env, dimension, 1);
5283    let ev = YogProjectileHitEvent {
5284        projectile_type: YogStr::from_str(&pt),
5285        projectile_uuid: YogStr::from_str(&pu),
5286        shooter_uuid: YogStr::from_str(&su),
5287        hit_type: YogStr::from_str(&ht),
5288        hit_entity_uuid: YogStr::from_str(&heu),
5289        x,
5290        y,
5291        z,
5292        dimension: YogStr::from_str(&dim),
5293    };
5294    let srv = srv_ptr();
5295    allowed(&h.projectile_hit, |ud, f| unsafe { f(ud, srv, &ev, 0) }) as jni::sys::jboolean
5296}
5297
5298#[unsafe(no_mangle)]
5299pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHit<'l>(
5300    mut env: JNIEnv<'l>,
5301    _class: JClass<'l>,
5302    projectile_type: JString<'l>,
5303    projectile_uuid: JString<'l>,
5304    shooter_uuid: JString<'l>,
5305    hit_type: JString<'l>,
5306    hit_entity_uuid: JString<'l>,
5307    x: jdouble,
5308    y: jdouble,
5309    z: jdouble,
5310    dimension: JString<'l>,
5311) {
5312    let h = handlers();
5313    if h.projectile_hit.is_empty() {
5314        return;
5315    }
5316    let (pt, pu) = (jstr!(env, projectile_type), jstr!(env, projectile_uuid));
5317    let (su, ht) = (jstr!(env, shooter_uuid), jstr!(env, hit_type));
5318    let (heu, dim) = (jstr!(env, hit_entity_uuid), jstr!(env, dimension));
5319    let ev = YogProjectileHitEvent {
5320        projectile_type: YogStr::from_str(&pt),
5321        projectile_uuid: YogStr::from_str(&pu),
5322        shooter_uuid: YogStr::from_str(&su),
5323        hit_type: YogStr::from_str(&ht),
5324        hit_entity_uuid: YogStr::from_str(&heu),
5325        x,
5326        y,
5327        z,
5328        dimension: YogStr::from_str(&dim),
5329    };
5330    let srv = srv_ptr();
5331    guard("on_projectile_hit", || {
5332        each(&h.projectile_hit, |ud, f| unsafe { f(ud, srv, &ev, 1) });
5333    });
5334}
5335
5336// ── ABI minor 10 — client-side JNI entry points ───────────────────────────────
5337
5338#[unsafe(no_mangle)]
5339pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientTick<'l>(
5340    _env: JNIEnv<'l>,
5341    _class: JClass<'l>,
5342) {
5343    let h = handlers();
5344    if h.client_tick.is_empty() {
5345        return;
5346    }
5347    guard("on_client_tick", || {
5348        each(&h.client_tick, |ud, f| unsafe { f(ud) });
5349    });
5350}
5351
5352/// The host's GL function pointer for `sym` (0 if it has none).
5353fn gl_proc_address(sym: &str) -> usize {
5354    let ptr: Option<i64> = unsafe { bridge!("glProcAddress", [S(YogStr::from_str(sym))]) };
5355    ptr.unwrap_or(0) as usize
5356}
5357
5358#[unsafe(no_mangle)]
5359pub extern "system" fn Java_dev_yog_NativeBridge_nativeGlInit<'l>(
5360    _env: JNIEnv<'l>,
5361    _class: JClass<'l>,
5362) {
5363    if GL.get().is_some() {
5364        return;
5365    }
5366    let mut raw_get_binary: usize = 0;
5367    let mut raw_prog_binary: usize = 0;
5368    let gl = unsafe {
5369        glow::Context::from_loader_function(|sym| {
5370            let ptr = gl_proc_address(sym);
5371            // Capture extension pointers while the loader runs.
5372            match sym {
5373                "glGetProgramBinary" => raw_get_binary = ptr,
5374                "glProgramBinary" => raw_prog_binary = ptr,
5375                _ => {}
5376            }
5377            ptr as *const _
5378        })
5379    };
5380    let _ = GL.set(GlCtx(gl));
5381    let _ = GL_GET_PROGRAM_BINARY.set((raw_get_binary != 0).then_some(raw_get_binary));
5382    let _ = GL_PROGRAM_BINARY.set((raw_prog_binary != 0).then_some(raw_prog_binary));
5383    // `glGetProgramiv` is a core function; always available.  We look it up once here
5384    // to avoid depending on glow internals for the PROGRAM_BINARY_LENGTH query.
5385    let get_program_iv = gl_proc_address("glGetProgramiv");
5386    let _ = GL_GET_PROGRAM_IV.set((get_program_iv != 0).then_some(get_program_iv));
5387}
5388
5389#[unsafe(no_mangle)]
5390pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnHudRender<'l>(
5391    _env: JNIEnv<'l>,
5392    _class: JClass<'l>,
5393    delta_tick: jfloat,
5394    screen_w: jint,
5395    screen_h: jint,
5396    scale_factor: jfloat,
5397    player_x: jfloat,
5398    player_y: jfloat,
5399    player_z: jfloat,
5400) {
5401    let h = handlers();
5402    let mut gfx = GFX_FN_TABLE;
5403    gfx.screen_w = screen_w;
5404    gfx.screen_h = screen_h;
5405    gfx.delta_tick = delta_tick;
5406    gfx.scale_factor = scale_factor;
5407    gfx.player_pos = [player_x, player_y, player_z];
5408
5409    // Mod hud_render callbacks.
5410    if !h.hud_render.is_empty() {
5411        guard("on_hud_render", || {
5412            each(&h.hud_render, |ud, f| unsafe { f(ud, &gfx) });
5413        });
5414    }
5415
5416    // Render active book UIs.
5417    let active_layers: Vec<UiLayer> = h.active_uis.lock().unwrap().clone();
5418    let sw = screen_w as f32;
5419    let sh = screen_h as f32;
5420    let ctx = unsafe { yog_gfx::GfxContext::from_raw(&gfx as *const _) };
5421    let mut renderers = h.book_renderers.lock().unwrap();
5422    for layer in &active_layers {
5423        if !layer.visible {
5424            continue;
5425        }
5426        if let Some(renderer) = renderers.get_mut(&layer.id) {
5427            renderer.render(&ctx, sw, sh);
5428        }
5429    }
5430}
5431
5432#[unsafe(no_mangle)]
5433pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnWorldRender<'l>(
5434    env: JNIEnv<'l>,
5435    _class: JClass<'l>,
5436    delta_tick: jfloat,
5437    screen_w: jint,
5438    screen_h: jint,
5439    scale_factor: jfloat,
5440    view_proj_arr: JFloatArray<'l>,
5441    cam_x: jfloat,
5442    cam_y: jfloat,
5443    cam_z: jfloat,
5444    player_x: jfloat,
5445    player_y: jfloat,
5446    player_z: jfloat,
5447) {
5448    let h = handlers();
5449    if h.world_render.is_empty() {
5450        return;
5451    }
5452    let mut view_proj = [0f32; 16];
5453    if env
5454        .get_float_array_region(&view_proj_arr, 0, &mut view_proj)
5455        .is_err()
5456    {
5457        return;
5458    }
5459    let mut gfx = GFX_FN_TABLE;
5460    gfx.screen_w = screen_w;
5461    gfx.screen_h = screen_h;
5462    gfx.delta_tick = delta_tick;
5463    gfx.scale_factor = scale_factor;
5464    gfx.view_proj = view_proj;
5465    gfx.camera_pos = [cam_x, cam_y, cam_z];
5466    gfx.player_pos = [player_x, player_y, player_z];
5467    guard("on_world_render", || {
5468        each(&h.world_render, |ud, f| unsafe { f(ud, &gfx) });
5469    });
5470}
5471
5472#[unsafe(no_mangle)]
5473pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnKeyPress<'l>(
5474    _env: JNIEnv<'l>,
5475    _class: JClass<'l>,
5476    key_code: jint,
5477    scan_code: jint,
5478    action: jint,
5479    modifiers: jint,
5480) -> jni::sys::jboolean {
5481    let h = handlers();
5482    if h.key_press.is_empty() {
5483        return 1;
5484    }
5485    let ev = YogKeyPressEvent {
5486        key_code,
5487        scan_code,
5488        action,
5489        modifiers,
5490    };
5491    allowed(&h.key_press, |ud, f| unsafe { f(ud, &ev) }) as jni::sys::jboolean
5492}
5493
5494#[unsafe(no_mangle)]
5495pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenOpen<'l>(
5496    mut env: JNIEnv<'l>,
5497    _class: JClass<'l>,
5498    screen_class: JString<'l>,
5499) {
5500    let h = handlers();
5501    if h.screen_open.is_empty() {
5502        return;
5503    }
5504    let sc = match env.get_string(&screen_class) {
5505        Ok(s) => String::from(s),
5506        Err(_) => return,
5507    };
5508    guard("on_screen_open", || {
5509        each(&h.screen_open, |ud, f| unsafe {
5510            f(ud, YogStr::from_str(&sc))
5511        });
5512    });
5513}
5514
5515#[unsafe(no_mangle)]
5516pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenClose<'l>(
5517    mut env: JNIEnv<'l>,
5518    _class: JClass<'l>,
5519    screen_class: JString<'l>,
5520) {
5521    let h = handlers();
5522    if h.screen_close.is_empty() {
5523        return;
5524    }
5525    let sc = match env.get_string(&screen_class) {
5526        Ok(s) => String::from(s),
5527        Err(_) => return,
5528    };
5529    guard("on_screen_close", || {
5530        each(&h.screen_close, |ud, f| unsafe {
5531            f(ud, YogStr::from_str(&sc))
5532        });
5533    });
5534}
5535
5536mod body;
5537mod loot;
5538// Hot reload: dev builds only (release ones are optimised past it).
5539#[cfg(feature = "dev")]
5540mod registrations;
5541mod entity_data;
5542mod client_api;
5543mod content_blob;
5544mod machine;
5545#[cfg(feature = "dev")]
5546mod control_socket;
5547mod images;
5548mod svg;
5549mod jcall;
5550mod ui_jni;
5551// Entry points for the benchmarks only: never in a build of the loader.
5552#[cfg(feature = "bench")]
5553#[doc(hidden)]
5554pub mod bench_support;
5555#[cfg(test)]
5556mod tests;