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::{Mutex, OnceLock, RwLock};
20
21use glow::HasContext;
22use jni::objects::{JByteArray, JClass, JFloatArray, JObject, JString, JValue};
23use jni::sys::{jdouble, jfloat, jint, jstring};
24use jni::{JNIEnv, JavaVM};
25use libloading::Symbol;
26use yog_hot_reload::{HotReloader, LoadedModule, ModuleGeneration, ModuleRegistry};
27
28use yog_abi::{
29    YogAdvancementEvent, YogAdvancementFn, YogApi, YogAttackEntityFn, YogBlockBreakFn, YogBlockDef,
30    YogBlockPos, YogChatFn, YogClientFn, YogCommandFn, YogContainerCloseEvent, YogContainerCloseFn,
31    YogContainerOpenEvent, YogContainerOpenFn, YogCraftEvent, YogCraftFn, YogEntityDamageFn,
32    YogEntityDeathFn, YogEntityInteractEvent, YogEntityInteractFn, YogEntitySpawnFn,
33    YogExplosionEvent, YogExplosionFn, YogGfxApi, YogHudRenderFn, YogItemDef, YogItemPickupEvent,
34    YogItemPickupFn, YogKeyPressEvent, YogKeyPressFn, YogOwnedStr, YogPacketFn, YogPlaceBlockEvent,
35    YogPlaceBlockFn, YogPlayerDeathEvent, YogPlayerDeathFn, YogPlayerFn, YogPlayerMoveEvent,
36    YogPlayerMoveFn, YogPlayerRespawnEvent, YogPlayerRespawnFn, YogProjectileHitEvent,
37    YogProjectileHitFn, YogScheduledFn, YogScreenFn, YogServer, YogServerFn, YogStartupGrantDef,
38    YogStr, YogUseBlockFn, YogUseItemFn, YogVec3, YogWorldRenderFn, ABI_VERSION,
39};
40use yog_registry::{BlockDef, FoodDef, 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 `Java_dev_yog_NativeBridge_nativeHotReload`.
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.
116type CommandEntry = (LoadedModule, Option<String>, *mut c_void, YogCommandFn);
117
118// Every callback table below is tagged with the `LoadedModule` that
119// registered it (see `current_registration()`), so a hot-reload's dispatch
120// sites can skip a retiring module's stale entries (`LoadedModule::
121// is_retiring()`) before they're physically swept by `RuntimeModuleRegistry
122// ::purge`. Content registries — `items`/`blocks`/`inventories`/`books`/
123// `recipes`/`dimensions`/`startup_grants`/`menu_entries` — are deliberately
124// NOT tagged: they're one-time definitions copied into Minecraft's own
125// registries at startup, not callbacks invoked later, and Minecraft itself
126// has no live registry-unregister mechanism to hot-reload them against
127// regardless of what this crate does.
128struct RuntimeHandlers {
129    block_break: Vec<(LoadedModule, *mut c_void, YogBlockBreakFn)>,
130    chat: Vec<(LoadedModule, *mut c_void, YogChatFn)>,
131    player_join: Vec<(LoadedModule, *mut c_void, YogPlayerFn)>,
132    player_leave: Vec<(LoadedModule, *mut c_void, YogPlayerFn)>,
133    use_item: Vec<(LoadedModule, *mut c_void, YogUseItemFn)>,
134    use_block: Vec<(LoadedModule, *mut c_void, YogUseBlockFn)>,
135    attack_entity: Vec<(LoadedModule, *mut c_void, YogAttackEntityFn)>,
136    entity_damage: Vec<(LoadedModule, *mut c_void, YogEntityDamageFn)>,
137    entity_death: Vec<(LoadedModule, *mut c_void, YogEntityDeathFn)>,
138    entity_spawn: Vec<(LoadedModule, *mut c_void, YogEntitySpawnFn)>,
139    player_place_block: Vec<(LoadedModule, *mut c_void, YogPlaceBlockFn)>,
140    player_death: Vec<(LoadedModule, *mut c_void, YogPlayerDeathFn)>,
141    player_respawn: Vec<(LoadedModule, *mut c_void, YogPlayerRespawnFn)>,
142    advancement: Vec<(LoadedModule, *mut c_void, YogAdvancementFn)>,
143    entity_interact: Vec<(LoadedModule, *mut c_void, YogEntityInteractFn)>,
144    item_craft: Vec<(LoadedModule, *mut c_void, YogCraftFn)>,
145    explosion: Vec<(LoadedModule, *mut c_void, YogExplosionFn)>,
146    item_pickup: Vec<(LoadedModule, *mut c_void, YogItemPickupFn)>,
147    player_move: Vec<(LoadedModule, *mut c_void, YogPlayerMoveFn)>,
148    container_open: Vec<(LoadedModule, *mut c_void, YogContainerOpenFn)>,
149    container_close: Vec<(LoadedModule, *mut c_void, YogContainerCloseFn)>,
150    projectile_hit: Vec<(LoadedModule, *mut c_void, YogProjectileHitFn)>,
151    client_tick: Vec<(LoadedModule, *mut c_void, YogClientFn)>,
152    hud_render: Vec<(LoadedModule, *mut c_void, YogHudRenderFn)>,
153    world_render: Vec<(LoadedModule, *mut c_void, YogWorldRenderFn)>,
154    key_press: Vec<(LoadedModule, *mut c_void, YogKeyPressFn)>,
155    screen_open: Vec<(LoadedModule, *mut c_void, YogScreenFn)>,
156    screen_close: Vec<(LoadedModule, *mut c_void, YogScreenFn)>,
157    server_tick: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
158    server_started: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
159    server_stopping: Vec<(LoadedModule, *mut c_void, YogServerFn)>,
160    /// All handlers registered under one command name, in registration order.
161    /// `schema` is `None` for a plain `on_command` (bare, zero-argument)
162    /// registration and `Some(schema)` for `on_typed_command`. Kept as a
163    /// `Vec` (not a single slot) so a mod can register several subcommands —
164    /// e.g. differing arg counts, or several bare/typed registrations sharing
165    /// one top-level name — without later registrations silently clobbering
166    /// earlier ones (see `nativeOnCommand`, which tries each entry whose
167    /// schema's arg count matches the actual invocation, in order, until one
168    /// produces a reply).
169    commands: HashMap<String, Vec<CommandEntry>>,
170    recipes: Vec<(String, String, String)>,
171    packets: HashMap<String, (LoadedModule, *mut c_void, YogPacketFn)>,
172    client_packets: HashMap<String, (LoadedModule, *mut c_void, YogPacketFn)>,
173    items: Vec<ItemDef>,
174    blocks: Vec<BlockDef>,
175    inventories: Vec<yog_inventory::InventoryDef>,
176    books: HashMap<String, String>,
177    book_renderers: Mutex<HashMap<String, yog_book::BookRenderer>>,
178    /// Declared dimension-type defs: id -> `YogDimensionDef` JSON. Actual
179    /// `LevelStem`/`ServerLevel` creation is a host (Java) responsibility —
180    /// see `yog-dimensions` crate docs.
181    dimensions: HashMap<String, String>,
182    chunk_generators: HashMap<String, (LoadedModule, *mut c_void, yog_abi::YogChunkGeneratorFn)>,
183    ui_handlers: HashMap<String, (LoadedModule, *mut c_void, yog_abi::YogUIEventFn)>,
184    ui_render_handlers: HashMap<String, Vec<(LoadedModule, *mut c_void, YogHudRenderFn)>>,
185    menu_entries: Vec<(String, String)>, // (label, ui_id) for vanilla screen buttons
186    pub active_uis: Mutex<Vec<UiLayer>>,
187    startup_grants: Vec<yog_registry::StartupGrant>,
188    startup_granted: Mutex<HashMap<String, bool>>,
189    /// Players whose startup grants are pending: (name, uuid, ticks_waited).
190    /// Granting happens on a server tick after join — giving items directly in
191    /// the join callback fails for the host of a freshly created world.
192    pending_grants: Mutex<Vec<(String, String, u32)>>,
193    scheduler: Mutex<SchedulerState>,
194}
195
196// All fn ptrs are C-ABI; ud pointers are from Box::into_raw of Send+Sync closures.
197unsafe impl Send for RuntimeHandlers {}
198unsafe impl Sync for RuntimeHandlers {}
199
200impl RuntimeHandlers {
201    fn new() -> Self {
202        Self {
203            block_break: Vec::new(),
204            chat: Vec::new(),
205            player_join: Vec::new(),
206            player_leave: Vec::new(),
207            use_item: Vec::new(),
208            use_block: Vec::new(),
209            attack_entity: Vec::new(),
210            entity_damage: Vec::new(),
211            entity_death: Vec::new(),
212            entity_spawn: Vec::new(),
213            player_place_block: Vec::new(),
214            player_death: Vec::new(),
215            player_respawn: Vec::new(),
216            advancement: Vec::new(),
217            entity_interact: Vec::new(),
218            item_craft: Vec::new(),
219            explosion: Vec::new(),
220            item_pickup: Vec::new(),
221            player_move: Vec::new(),
222            container_open: Vec::new(),
223            container_close: Vec::new(),
224            projectile_hit: Vec::new(),
225            client_tick: Vec::new(),
226            hud_render: Vec::new(),
227            world_render: Vec::new(),
228            key_press: Vec::new(),
229            screen_open: Vec::new(),
230            screen_close: Vec::new(),
231            server_tick: Vec::new(),
232            server_started: Vec::new(),
233            server_stopping: Vec::new(),
234            commands: HashMap::new(),
235            recipes: Vec::new(),
236            packets: HashMap::new(),
237            client_packets: HashMap::new(),
238            items: Vec::new(),
239            ui_handlers: HashMap::new(),
240            ui_render_handlers: HashMap::new(),
241            menu_entries: Vec::new(),
242            active_uis: Mutex::new(Vec::new()),
243            startup_grants: Vec::new(),
244            blocks: Vec::new(),
245            inventories: Vec::new(),
246            books: HashMap::new(),
247            book_renderers: Mutex::new(HashMap::new()),
248            dimensions: HashMap::new(),
249            chunk_generators: HashMap::new(),
250            startup_granted: Mutex::new(HashMap::new()),
251            pending_grants: Mutex::new(Vec::new()),
252            scheduler: Mutex::new(SchedulerState::new()),
253        }
254    }
255}
256
257struct SchedulerState {
258    once_tasks: Vec<OnceTask>,
259    repeating_tasks: Vec<RepeatingTask>,
260}
261
262struct OnceTask {
263    module: LoadedModule,
264    delay_remaining: u64,
265    ud: *mut c_void,
266    f: YogScheduledFn,
267}
268struct RepeatingTask {
269    module: LoadedModule,
270    period: u64,
271    ticks_left: u64,
272    ud: *mut c_void,
273    f: YogScheduledFn,
274}
275
276unsafe impl Send for SchedulerState {}
277unsafe impl Sync for SchedulerState {}
278unsafe impl Send for OnceTask {}
279unsafe impl Send for RepeatingTask {}
280
281impl SchedulerState {
282    fn new() -> Self {
283        Self {
284            once_tasks: Vec::new(),
285            repeating_tasks: Vec::new(),
286        }
287    }
288}
289
290fn handlers() -> std::sync::RwLockReadGuard<'static, RuntimeHandlers> {
291    HANDLERS
292        .get()
293        .expect("yog: nativeInit not called yet")
294        .read()
295        .expect("handlers lock poisoned")
296}
297
298fn current_registration() -> LoadedModule {
299    CURRENT_REGISTRATION
300        .lock()
301        .unwrap()
302        .clone()
303        .expect("a yog-runtime api_* function was called outside of yog_mod_register")
304}
305
306fn hot_reloader() -> &'static HotReloader<RuntimeModuleRegistry> {
307    HOT_RELOADER.get().expect("yog: nativeInit not called yet")
308}
309
310/// The `yog-hot-reload` host contract: `retarget` needs no work here because
311/// `LoadedModule::is_retiring()` already makes a superseded generation's
312/// dispatch-table entries inert (every `handlers().<field>` loop checks it)
313/// the instant `HotReloader::reload` calls `retire` on the old module —
314/// well before this is even invoked. `purge` is the actual safety-net
315/// sweep, dropping every entry tagged with a retired generation right
316/// before its library is hard-unloaded.
317struct RuntimeModuleRegistry;
318
319impl ModuleRegistry for RuntimeModuleRegistry {
320    fn retarget(&self, _mod_id: &str, _from: ModuleGeneration, _to: ModuleGeneration) {}
321
322    fn purge(&self, generation: ModuleGeneration) {
323        let Some(lock) = HANDLERS.get() else { return };
324        let mut h = lock.write().expect("handlers lock poisoned");
325        h.block_break.retain(|(m, ..)| m.generation() != generation);
326        h.chat.retain(|(m, ..)| m.generation() != generation);
327        h.player_join.retain(|(m, ..)| m.generation() != generation);
328        h.player_leave
329            .retain(|(m, ..)| m.generation() != generation);
330        h.use_item.retain(|(m, ..)| m.generation() != generation);
331        h.use_block.retain(|(m, ..)| m.generation() != generation);
332        h.attack_entity
333            .retain(|(m, ..)| m.generation() != generation);
334        h.entity_damage
335            .retain(|(m, ..)| m.generation() != generation);
336        h.entity_death
337            .retain(|(m, ..)| m.generation() != generation);
338        h.entity_spawn
339            .retain(|(m, ..)| m.generation() != generation);
340        h.player_place_block
341            .retain(|(m, ..)| m.generation() != generation);
342        h.player_death
343            .retain(|(m, ..)| m.generation() != generation);
344        h.player_respawn
345            .retain(|(m, ..)| m.generation() != generation);
346        h.advancement.retain(|(m, ..)| m.generation() != generation);
347        h.entity_interact
348            .retain(|(m, ..)| m.generation() != generation);
349        h.item_craft.retain(|(m, ..)| m.generation() != generation);
350        h.explosion.retain(|(m, ..)| m.generation() != generation);
351        h.item_pickup.retain(|(m, ..)| m.generation() != generation);
352        h.player_move.retain(|(m, ..)| m.generation() != generation);
353        h.container_open
354            .retain(|(m, ..)| m.generation() != generation);
355        h.container_close
356            .retain(|(m, ..)| m.generation() != generation);
357        h.projectile_hit
358            .retain(|(m, ..)| m.generation() != generation);
359        h.client_tick.retain(|(m, ..)| m.generation() != generation);
360        h.hud_render.retain(|(m, ..)| m.generation() != generation);
361        h.world_render
362            .retain(|(m, ..)| m.generation() != generation);
363        h.key_press.retain(|(m, ..)| m.generation() != generation);
364        h.screen_open.retain(|(m, ..)| m.generation() != generation);
365        h.screen_close
366            .retain(|(m, ..)| m.generation() != generation);
367        h.server_tick.retain(|(m, ..)| m.generation() != generation);
368        h.server_started
369            .retain(|(m, ..)| m.generation() != generation);
370        h.server_stopping
371            .retain(|(m, ..)| m.generation() != generation);
372        for entries in h.commands.values_mut() {
373            entries.retain(|(m, ..)| m.generation() != generation);
374        }
375        h.packets.retain(|_, (m, ..)| m.generation() != generation);
376        h.client_packets
377            .retain(|_, (m, ..)| m.generation() != generation);
378        h.chunk_generators
379            .retain(|_, (m, ..)| m.generation() != generation);
380        h.ui_handlers
381            .retain(|_, (m, ..)| m.generation() != generation);
382        for entries in h.ui_render_handlers.values_mut() {
383            entries.retain(|(m, ..)| m.generation() != generation);
384        }
385        h.scheduler
386            .lock()
387            .expect("scheduler poisoned")
388            .once_tasks
389            .retain(|t| t.module.generation() != generation);
390        h.scheduler
391            .lock()
392            .expect("scheduler poisoned")
393            .repeating_tasks
394            .retain(|t| t.module.generation() != generation);
395    }
396}
397
398// ── JNI helpers ──────────────────────────────────────────────────────────────
399
400fn guard(label: &str, f: impl FnOnce()) {
401    if std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)).is_err() {
402        yog_logging::error!("a mod panicked handling `{}` (ignored)", label);
403    }
404}
405
406macro_rules! jstr {
407    ($env:expr, $s:expr) => {
408        match $env.get_string(&$s) {
409            Ok(s) => String::from(s),
410            Err(_) => return,
411        }
412    };
413}
414
415/// Convert a `YogStr` into a Java String. Caller must ensure `s` is valid UTF-8.
416unsafe fn ys_to_java<'l>(env: &mut JNIEnv<'l>, s: YogStr) -> Option<jni::objects::JString<'l>> {
417    env.new_string(s.as_str()).ok()
418}
419
420fn get_env() -> Option<jni::AttachGuard<'static>> {
421    JAVA_VM.get()?.attach_current_thread().ok()
422}
423
424// ── Free-str allocator used by YogOwnedStr ────────────────────────────────────
425
426unsafe extern "C" fn yog_free_str(ptr: *mut u8, len: u32) {
427    if !ptr.is_null() {
428        drop(Box::from_raw(std::ptr::slice_from_raw_parts_mut(
429            ptr,
430            len as usize,
431        )));
432    }
433}
434
435fn jstring_to_owned(env: &mut JNIEnv, obj: jni::objects::JObject) -> YogOwnedStr {
436    if obj.as_raw().is_null() {
437        return YogOwnedStr::NONE;
438    }
439    match env.get_string(&JString::from(obj)) {
440        Ok(s) => YogOwnedStr::from_string(String::from(s)),
441        Err(_) => YogOwnedStr::NONE,
442    }
443}
444
445// ── YogServer standalone functions (one per action) ───────────────────────────
446//
447// ctx is unused here — all state is in the JAVA_VM static.
448
449unsafe extern "C" fn srv_broadcast(_ctx: *mut c_void, msg: YogStr) {
450    let Some(mut env) = get_env() else { return };
451    if let Some(jmsg) = ys_to_java(&mut env, msg) {
452        let _ = env.call_static_method(
453            "dev/yog/NativeBridge",
454            "broadcast",
455            "(Ljava/lang/String;)V",
456            &[JValue::Object(&jmsg)],
457        );
458    }
459}
460
461unsafe extern "C" fn srv_get_block(
462    _ctx: *mut c_void,
463    dim: YogStr,
464    pos: YogBlockPos,
465) -> YogOwnedStr {
466    let Some(mut env) = get_env() else {
467        return YogOwnedStr::NONE;
468    };
469    let (Some(jd),) = (ys_to_java(&mut env, dim),) else {
470        return YogOwnedStr::NONE;
471    };
472    let ret = env.call_static_method(
473        "dev/yog/NativeBridge",
474        "getBlock",
475        "(Ljava/lang/String;III)Ljava/lang/String;",
476        &[
477            JValue::Object(&jd),
478            JValue::Int(pos.x),
479            JValue::Int(pos.y),
480            JValue::Int(pos.z),
481        ],
482    );
483    match ret.and_then(|v| v.l()) {
484        Ok(obj) => jstring_to_owned(&mut env, obj),
485        _ => YogOwnedStr::NONE,
486    }
487}
488
489unsafe extern "C" fn srv_set_block(
490    _ctx: *mut c_void,
491    dim: YogStr,
492    pos: YogBlockPos,
493    block: YogStr,
494) -> bool {
495    let Some(mut env) = get_env() else {
496        return false;
497    };
498    let (Some(jd), Some(jb)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, block)) else {
499        return false;
500    };
501    env.call_static_method(
502        "dev/yog/NativeBridge",
503        "setBlock",
504        "(Ljava/lang/String;IIILjava/lang/String;)Z",
505        &[
506            JValue::Object(&jd),
507            JValue::Int(pos.x),
508            JValue::Int(pos.y),
509            JValue::Int(pos.z),
510            JValue::Object(&jb),
511        ],
512    )
513    .and_then(|v| v.z())
514    .unwrap_or(false)
515}
516
517unsafe extern "C" fn srv_world_time(_ctx: *mut c_void, dim: YogStr, out: *mut i64) -> bool {
518    let Some(mut env) = get_env() else {
519        return false;
520    };
521    let Some(jd) = ys_to_java(&mut env, dim) else {
522        return false;
523    };
524    match env
525        .call_static_method(
526            "dev/yog/NativeBridge",
527            "worldTime",
528            "(Ljava/lang/String;)J",
529            &[JValue::Object(&jd)],
530        )
531        .and_then(|v| v.j())
532    {
533        Ok(v) if v != i64::MIN => {
534            *out = v;
535            true
536        }
537        _ => false,
538    }
539}
540
541unsafe extern "C" fn srv_set_time(_ctx: *mut c_void, dim: YogStr, time: i64) -> bool {
542    let Some(mut env) = get_env() else {
543        return false;
544    };
545    let Some(jd) = ys_to_java(&mut env, dim) else {
546        return false;
547    };
548    env.call_static_method(
549        "dev/yog/NativeBridge",
550        "worldSetTime",
551        "(Ljava/lang/String;J)Z",
552        &[JValue::Object(&jd), JValue::Long(time)],
553    )
554    .and_then(|v| v.z())
555    .unwrap_or(false)
556}
557
558unsafe extern "C" fn srv_is_raining(_ctx: *mut c_void, dim: YogStr) -> bool {
559    let Some(mut env) = get_env() else {
560        return false;
561    };
562    let Some(jd) = ys_to_java(&mut env, dim) else {
563        return false;
564    };
565    env.call_static_method(
566        "dev/yog/NativeBridge",
567        "worldIsRaining",
568        "(Ljava/lang/String;)Z",
569        &[JValue::Object(&jd)],
570    )
571    .and_then(|v| v.z())
572    .unwrap_or(false)
573}
574
575unsafe extern "C" fn srv_set_weather(
576    _ctx: *mut c_void,
577    dim: YogStr,
578    raining: bool,
579    dur: i32,
580) -> bool {
581    let Some(mut env) = get_env() else {
582        return false;
583    };
584    let Some(jd) = ys_to_java(&mut env, dim) else {
585        return false;
586    };
587    env.call_static_method(
588        "dev/yog/NativeBridge",
589        "worldSetWeather",
590        "(Ljava/lang/String;ZI)Z",
591        &[
592            JValue::Object(&jd),
593            JValue::Bool(raining as u8),
594            JValue::Int(dur),
595        ],
596    )
597    .and_then(|v| v.z())
598    .unwrap_or(false)
599}
600
601unsafe extern "C" fn srv_give_item(
602    _ctx: *mut c_void,
603    player: YogStr,
604    item: YogStr,
605    count: u32,
606) -> bool {
607    let Some(mut env) = get_env() else {
608        return false;
609    };
610    let (Some(jp), Some(ji)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, item)) else {
611        return false;
612    };
613    env.call_static_method(
614        "dev/yog/NativeBridge",
615        "giveItem",
616        "(Ljava/lang/String;Ljava/lang/String;I)Z",
617        &[
618            JValue::Object(&jp),
619            JValue::Object(&ji),
620            JValue::Int(count as i32),
621        ],
622    )
623    .and_then(|v| v.z())
624    .unwrap_or(false)
625}
626
627unsafe extern "C" fn srv_player_teleport(_ctx: *mut c_void, player: YogStr, pos: YogVec3) -> bool {
628    let Some(mut env) = get_env() else {
629        return false;
630    };
631    let Some(jp) = ys_to_java(&mut env, player) else {
632        return false;
633    };
634    env.call_static_method(
635        "dev/yog/NativeBridge",
636        "teleport",
637        "(Ljava/lang/String;DDD)Z",
638        &[
639            JValue::Object(&jp),
640            JValue::Double(pos.x),
641            JValue::Double(pos.y),
642            JValue::Double(pos.z),
643        ],
644    )
645    .and_then(|v| v.z())
646    .unwrap_or(false)
647}
648
649unsafe extern "C" fn srv_send_to_player(
650    _ctx: *mut c_void,
651    player: YogStr,
652    channel: YogStr,
653    data: *const u8,
654    len: u32,
655) -> bool {
656    let Some(mut env) = get_env() else {
657        return false;
658    };
659    let (Some(jp), Some(jc)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, channel)) else {
660        return false;
661    };
662    let payload = std::slice::from_raw_parts(data, len as usize);
663    let Ok(jdata) = env.byte_array_from_slice(payload) else {
664        return false;
665    };
666    env.call_static_method(
667        "dev/yog/NativeBridge",
668        "sendToPlayer",
669        "(Ljava/lang/String;Ljava/lang/String;[B)Z",
670        &[
671            JValue::Object(&jp),
672            JValue::Object(&jc),
673            JValue::Object(&jdata),
674        ],
675    )
676    .and_then(|v| v.z())
677    .unwrap_or(false)
678}
679
680unsafe extern "C" fn srv_send_to_server(
681    _ctx: *mut c_void,
682    channel: YogStr,
683    data: *const u8,
684    len: u32,
685) -> bool {
686    let Some(mut env) = get_env() else {
687        return false;
688    };
689    let Some(jc) = ys_to_java(&mut env, channel) else {
690        return false;
691    };
692    let payload = std::slice::from_raw_parts(data, len as usize);
693    let Ok(jdata) = env.byte_array_from_slice(payload) else {
694        return false;
695    };
696    let result = env.call_static_method(
697        "dev/yog/YogClient",
698        "sendToServer",
699        "(Ljava/lang/String;[B)Z",
700        &[JValue::Object(&jc), JValue::Object(&jdata)],
701    );
702    let _ = env.exception_clear();
703    result.and_then(|v| v.z()).unwrap_or(false)
704}
705
706unsafe extern "C" fn srv_kick_player(_ctx: *mut c_void, player: YogStr, reason: YogStr) -> bool {
707    let Some(mut env) = get_env() else {
708        return false;
709    };
710    let (Some(jp), Some(jr)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, reason)) else {
711        return false;
712    };
713    env.call_static_method(
714        "dev/yog/NativeBridge",
715        "kickPlayer",
716        "(Ljava/lang/String;Ljava/lang/String;)Z",
717        &[JValue::Object(&jp), JValue::Object(&jr)],
718    )
719    .and_then(|v| v.z())
720    .unwrap_or(false)
721}
722
723unsafe extern "C" fn srv_set_gamemode(_ctx: *mut c_void, player: YogStr, mode: YogStr) -> bool {
724    let Some(mut env) = get_env() else {
725        return false;
726    };
727    let (Some(jp), Some(jg)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, mode)) else {
728        return false;
729    };
730    env.call_static_method(
731        "dev/yog/NativeBridge",
732        "setGamemode",
733        "(Ljava/lang/String;Ljava/lang/String;)Z",
734        &[JValue::Object(&jp), JValue::Object(&jg)],
735    )
736    .and_then(|v| v.z())
737    .unwrap_or(false)
738}
739
740unsafe extern "C" fn srv_send_title(
741    _ctx: *mut c_void,
742    player: YogStr,
743    title: YogStr,
744    sub: YogStr,
745    fi: i32,
746    stay: i32,
747    fo: i32,
748) -> bool {
749    let Some(mut env) = get_env() else {
750        return false;
751    };
752    let (Some(jp), Some(jt), Some(js)) = (
753        ys_to_java(&mut env, player),
754        ys_to_java(&mut env, title),
755        ys_to_java(&mut env, sub),
756    ) else {
757        return false;
758    };
759    env.call_static_method(
760        "dev/yog/NativeBridge",
761        "sendTitle",
762        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;III)Z",
763        &[
764            JValue::Object(&jp),
765            JValue::Object(&jt),
766            JValue::Object(&js),
767            JValue::Int(fi),
768            JValue::Int(stay),
769            JValue::Int(fo),
770        ],
771    )
772    .and_then(|v| v.z())
773    .unwrap_or(false)
774}
775
776unsafe extern "C" fn srv_send_actionbar(_ctx: *mut c_void, player: YogStr, msg: YogStr) -> bool {
777    let Some(mut env) = get_env() else {
778        return false;
779    };
780    let (Some(jp), Some(jm)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, msg)) else {
781        return false;
782    };
783    env.call_static_method(
784        "dev/yog/NativeBridge",
785        "sendActionbar",
786        "(Ljava/lang/String;Ljava/lang/String;)Z",
787        &[JValue::Object(&jp), JValue::Object(&jm)],
788    )
789    .and_then(|v| v.z())
790    .unwrap_or(false)
791}
792
793unsafe extern "C" fn srv_play_sound(
794    _ctx: *mut c_void,
795    dim: YogStr,
796    pos: YogVec3,
797    sound: YogStr,
798    vol: f32,
799    pitch: f32,
800) -> bool {
801    let Some(mut env) = get_env() else {
802        return false;
803    };
804    let (Some(jd), Some(js)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, sound)) else {
805        return false;
806    };
807    env.call_static_method(
808        "dev/yog/NativeBridge",
809        "playSound",
810        "(Ljava/lang/String;DDDLjava/lang/String;FF)Z",
811        &[
812            JValue::Object(&jd),
813            JValue::Double(pos.x),
814            JValue::Double(pos.y),
815            JValue::Double(pos.z),
816            JValue::Object(&js),
817            JValue::Float(vol),
818            JValue::Float(pitch),
819        ],
820    )
821    .and_then(|v| v.z())
822    .unwrap_or(false)
823}
824
825unsafe extern "C" fn srv_play_sound_player(
826    _ctx: *mut c_void,
827    player: YogStr,
828    sound: YogStr,
829    vol: f32,
830    pitch: f32,
831) -> bool {
832    let Some(mut env) = get_env() else {
833        return false;
834    };
835    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, sound)) else {
836        return false;
837    };
838    env.call_static_method(
839        "dev/yog/NativeBridge",
840        "playSoundToPlayer",
841        "(Ljava/lang/String;Ljava/lang/String;FF)Z",
842        &[
843            JValue::Object(&jp),
844            JValue::Object(&js),
845            JValue::Float(vol),
846            JValue::Float(pitch),
847        ],
848    )
849    .and_then(|v| v.z())
850    .unwrap_or(false)
851}
852
853unsafe extern "C" fn srv_entity_teleport(_ctx: *mut c_void, uuid: YogStr, pos: YogVec3) -> bool {
854    let Some(mut env) = get_env() else {
855        return false;
856    };
857    let Some(ju) = ys_to_java(&mut env, uuid) else {
858        return false;
859    };
860    env.call_static_method(
861        "dev/yog/NativeBridge",
862        "entityTeleport",
863        "(Ljava/lang/String;DDD)Z",
864        &[
865            JValue::Object(&ju),
866            JValue::Double(pos.x),
867            JValue::Double(pos.y),
868            JValue::Double(pos.z),
869        ],
870    )
871    .and_then(|v| v.z())
872    .unwrap_or(false)
873}
874
875unsafe extern "C" fn srv_entity_rotation(
876    _ctx: *mut c_void,
877    uuid: YogStr,
878    out: *mut YogVec3,
879) -> bool {
880    let Some(mut env) = get_env() else {
881        return false;
882    };
883    let Some(ju) = ys_to_java(&mut env, uuid) else {
884        return false;
885    };
886    let ret = env.call_static_method(
887        "dev/yog/NativeBridge",
888        "entityRotation",
889        "(Ljava/lang/String;)Ljava/lang/String;",
890        &[JValue::Object(&ju)],
891    );
892    let obj = match ret.and_then(|v| v.l()) {
893        Ok(o) => o,
894        Err(_) => {
895            env.exception_clear().ok();
896            return false;
897        }
898    };
899    if obj.as_raw().is_null() {
900        return false;
901    }
902    let s: String = match env.get_string(&JString::from(obj)) {
903        Ok(s) => String::from(s),
904        Err(_) => return false,
905    };
906    let mut it = s.split('\t');
907    let (yaw, pitch) = (it.next(), it.next());
908    if let (Some(yaw), Some(pitch)) = (
909        yaw.and_then(|v| v.parse().ok()),
910        pitch.and_then(|v| v.parse().ok()),
911    ) {
912        *out = YogVec3 {
913            x: yaw,
914            y: pitch,
915            z: 0.0,
916        };
917        true
918    } else {
919        false
920    }
921}
922
923unsafe extern "C" fn srv_entity_position(
924    _ctx: *mut c_void,
925    uuid: YogStr,
926    out: *mut YogVec3,
927) -> bool {
928    let Some(mut env) = get_env() else {
929        return false;
930    };
931    let Some(ju) = ys_to_java(&mut env, uuid) else {
932        return false;
933    };
934    let ret = env.call_static_method(
935        "dev/yog/NativeBridge",
936        "entityPosition",
937        "(Ljava/lang/String;)Ljava/lang/String;",
938        &[JValue::Object(&ju)],
939    );
940    let obj = match ret.and_then(|v| v.l()) {
941        Ok(o) => o,
942        Err(_) => return false,
943    };
944    if obj.as_raw().is_null() {
945        return false;
946    }
947    let s: String = match env.get_string(&JString::from(obj)) {
948        Ok(s) => String::from(s),
949        Err(_) => return false,
950    };
951    let mut it = s.split('\t');
952    let (x, y, z) = (it.next(), it.next(), it.next());
953    if let (Some(x), Some(y), Some(z)) = (
954        x.and_then(|v| v.parse().ok()),
955        y.and_then(|v| v.parse().ok()),
956        z.and_then(|v| v.parse().ok()),
957    ) {
958        *out = YogVec3 { x, y, z };
959        true
960    } else {
961        false
962    }
963}
964
965unsafe extern "C" fn srv_entity_health(_ctx: *mut c_void, uuid: YogStr, out: *mut f32) -> bool {
966    let Some(mut env) = get_env() else {
967        return false;
968    };
969    let Some(ju) = ys_to_java(&mut env, uuid) else {
970        return false;
971    };
972    match env
973        .call_static_method(
974            "dev/yog/NativeBridge",
975            "entityHealth",
976            "(Ljava/lang/String;)D",
977            &[JValue::Object(&ju)],
978        )
979        .and_then(|v| v.d())
980    {
981        Ok(v) if !v.is_nan() => {
982            *out = v as f32;
983            true
984        }
985        _ => false,
986    }
987}
988
989unsafe extern "C" fn srv_entity_set_health(_ctx: *mut c_void, uuid: YogStr, hp: f32) -> bool {
990    let Some(mut env) = get_env() else {
991        return false;
992    };
993    let Some(ju) = ys_to_java(&mut env, uuid) else {
994        return false;
995    };
996    env.call_static_method(
997        "dev/yog/NativeBridge",
998        "entitySetHealth",
999        "(Ljava/lang/String;D)Z",
1000        &[JValue::Object(&ju), JValue::Double(hp as f64)],
1001    )
1002    .and_then(|v| v.z())
1003    .unwrap_or(false)
1004}
1005
1006unsafe extern "C" fn srv_entity_kill(_ctx: *mut c_void, uuid: YogStr) -> bool {
1007    let Some(mut env) = get_env() else {
1008        return false;
1009    };
1010    let Some(ju) = ys_to_java(&mut env, uuid) else {
1011        return false;
1012    };
1013    env.call_static_method(
1014        "dev/yog/NativeBridge",
1015        "entityKill",
1016        "(Ljava/lang/String;)Z",
1017        &[JValue::Object(&ju)],
1018    )
1019    .and_then(|v| v.z())
1020    .unwrap_or(false)
1021}
1022
1023unsafe extern "C" fn srv_spawn_entity(
1024    _ctx: *mut c_void,
1025    type_id: YogStr,
1026    dim: YogStr,
1027    pos: YogVec3,
1028) -> YogOwnedStr {
1029    let Some(mut env) = get_env() else {
1030        return YogOwnedStr::NONE;
1031    };
1032    let (Some(jt), Some(jd)) = (ys_to_java(&mut env, type_id), ys_to_java(&mut env, dim)) else {
1033        return YogOwnedStr::NONE;
1034    };
1035    let ret = env.call_static_method(
1036        "dev/yog/NativeBridge",
1037        "spawnEntity",
1038        "(Ljava/lang/String;Ljava/lang/String;DDD)Ljava/lang/String;",
1039        &[
1040            JValue::Object(&jt),
1041            JValue::Object(&jd),
1042            JValue::Double(pos.x),
1043            JValue::Double(pos.y),
1044            JValue::Double(pos.z),
1045        ],
1046    );
1047    match ret.and_then(|v| v.l()) {
1048        Ok(obj) => jstring_to_owned(&mut env, obj),
1049        _ => YogOwnedStr::NONE,
1050    }
1051}
1052
1053unsafe extern "C" fn srv_entity_add_effect(
1054    _ctx: *mut c_void,
1055    uuid: YogStr,
1056    fx: YogStr,
1057    dur: i32,
1058    amp: u8,
1059    particles: bool,
1060) -> bool {
1061    let Some(mut env) = get_env() else {
1062        return false;
1063    };
1064    let (Some(ju), Some(je)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, fx)) else {
1065        return false;
1066    };
1067    env.call_static_method(
1068        "dev/yog/NativeBridge",
1069        "entityAddEffect",
1070        "(Ljava/lang/String;Ljava/lang/String;IIZ)Z",
1071        &[
1072            JValue::Object(&ju),
1073            JValue::Object(&je),
1074            JValue::Int(dur),
1075            JValue::Int(amp as i32),
1076            JValue::Bool(particles as u8),
1077        ],
1078    )
1079    .and_then(|v| v.z())
1080    .unwrap_or(false)
1081}
1082
1083unsafe extern "C" fn srv_entity_remove_effect(_ctx: *mut c_void, uuid: YogStr, fx: YogStr) -> bool {
1084    let Some(mut env) = get_env() else {
1085        return false;
1086    };
1087    let (Some(ju), Some(je)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, fx)) else {
1088        return false;
1089    };
1090    env.call_static_method(
1091        "dev/yog/NativeBridge",
1092        "entityRemoveEffect",
1093        "(Ljava/lang/String;Ljava/lang/String;)Z",
1094        &[JValue::Object(&ju), JValue::Object(&je)],
1095    )
1096    .and_then(|v| v.z())
1097    .unwrap_or(false)
1098}
1099
1100unsafe extern "C" fn srv_entity_clear_effects(_ctx: *mut c_void, uuid: YogStr) -> bool {
1101    let Some(mut env) = get_env() else {
1102        return false;
1103    };
1104    let Some(ju) = ys_to_java(&mut env, uuid) else {
1105        return false;
1106    };
1107    env.call_static_method(
1108        "dev/yog/NativeBridge",
1109        "entityClearEffects",
1110        "(Ljava/lang/String;)Z",
1111        &[JValue::Object(&ju)],
1112    )
1113    .and_then(|v| v.z())
1114    .unwrap_or(false)
1115}
1116
1117unsafe extern "C" fn srv_entity_velocity(
1118    _ctx: *mut c_void,
1119    uuid: YogStr,
1120    out: *mut YogVec3,
1121) -> bool {
1122    let Some(mut env) = get_env() else {
1123        return false;
1124    };
1125    let Some(ju) = ys_to_java(&mut env, uuid) else {
1126        return false;
1127    };
1128    let ret = env.call_static_method(
1129        "dev/yog/NativeBridge",
1130        "entityVelocity",
1131        "(Ljava/lang/String;)Ljava/lang/String;",
1132        &[JValue::Object(&ju)],
1133    );
1134    let obj = match ret.and_then(|v| v.l()) {
1135        Ok(o) => o,
1136        Err(_) => return false,
1137    };
1138    if obj.as_raw().is_null() {
1139        return false;
1140    }
1141    let s: String = match env.get_string(&JString::from(obj)) {
1142        Ok(s) => String::from(s),
1143        Err(_) => return false,
1144    };
1145    let mut it = s.split('\t');
1146    let (x, y, z) = (it.next(), it.next(), it.next());
1147    if let (Some(x), Some(y), Some(z)) = (
1148        x.and_then(|v| v.parse().ok()),
1149        y.and_then(|v| v.parse().ok()),
1150        z.and_then(|v| v.parse().ok()),
1151    ) {
1152        *out = YogVec3 { x, y, z };
1153        true
1154    } else {
1155        false
1156    }
1157}
1158
1159unsafe extern "C" fn srv_entity_set_velocity(
1160    _ctx: *mut c_void,
1161    uuid: YogStr,
1162    vel: YogVec3,
1163) -> bool {
1164    let Some(mut env) = get_env() else {
1165        return false;
1166    };
1167    let Some(ju) = ys_to_java(&mut env, uuid) else {
1168        return false;
1169    };
1170    env.call_static_method(
1171        "dev/yog/NativeBridge",
1172        "entitySetVelocity",
1173        "(Ljava/lang/String;DDD)Z",
1174        &[
1175            JValue::Object(&ju),
1176            JValue::Double(vel.x),
1177            JValue::Double(vel.y),
1178            JValue::Double(vel.z),
1179        ],
1180    )
1181    .and_then(|v| v.z())
1182    .unwrap_or(false)
1183}
1184
1185unsafe extern "C" fn srv_entity_add_velocity(
1186    _ctx: *mut c_void,
1187    uuid: YogStr,
1188    vel: YogVec3,
1189) -> bool {
1190    let Some(mut env) = get_env() else {
1191        return false;
1192    };
1193    let Some(ju) = ys_to_java(&mut env, uuid) else {
1194        return false;
1195    };
1196    env.call_static_method(
1197        "dev/yog/NativeBridge",
1198        "entityAddVelocity",
1199        "(Ljava/lang/String;DDD)Z",
1200        &[
1201            JValue::Object(&ju),
1202            JValue::Double(vel.x),
1203            JValue::Double(vel.y),
1204            JValue::Double(vel.z),
1205        ],
1206    )
1207    .and_then(|v| v.z())
1208    .unwrap_or(false)
1209}
1210
1211unsafe extern "C" fn srv_has_item_tag(_ctx: *mut c_void, item: YogStr, tag: YogStr) -> bool {
1212    let Some(mut env) = get_env() else {
1213        return false;
1214    };
1215    let (Some(ji), Some(jt)) = (ys_to_java(&mut env, item), ys_to_java(&mut env, tag)) else {
1216        return false;
1217    };
1218    env.call_static_method(
1219        "dev/yog/NativeBridge",
1220        "hasItemTag",
1221        "(Ljava/lang/String;Ljava/lang/String;)Z",
1222        &[JValue::Object(&ji), JValue::Object(&jt)],
1223    )
1224    .and_then(|v| v.z())
1225    .unwrap_or(false)
1226}
1227
1228unsafe extern "C" fn srv_has_block_tag(_ctx: *mut c_void, block: YogStr, tag: YogStr) -> bool {
1229    let Some(mut env) = get_env() else {
1230        return false;
1231    };
1232    let (Some(jb), Some(jt)) = (ys_to_java(&mut env, block), ys_to_java(&mut env, tag)) else {
1233        return false;
1234    };
1235    env.call_static_method(
1236        "dev/yog/NativeBridge",
1237        "hasBlockTag",
1238        "(Ljava/lang/String;Ljava/lang/String;)Z",
1239        &[JValue::Object(&jb), JValue::Object(&jt)],
1240    )
1241    .and_then(|v| v.z())
1242    .unwrap_or(false)
1243}
1244
1245unsafe extern "C" fn srv_drop_loot(
1246    _ctx: *mut c_void,
1247    table: YogStr,
1248    dim: YogStr,
1249    pos: YogVec3,
1250) -> bool {
1251    let Some(mut env) = get_env() else {
1252        return false;
1253    };
1254    let (Some(jt), Some(jd)) = (ys_to_java(&mut env, table), ys_to_java(&mut env, dim)) else {
1255        return false;
1256    };
1257    env.call_static_method(
1258        "dev/yog/NativeBridge",
1259        "dropLoot",
1260        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
1261        &[
1262            JValue::Object(&jt),
1263            JValue::Object(&jd),
1264            JValue::Double(pos.x),
1265            JValue::Double(pos.y),
1266            JValue::Double(pos.z),
1267        ],
1268    )
1269    .and_then(|v| v.z())
1270    .unwrap_or(false)
1271}
1272
1273unsafe extern "C" fn srv_scoreboard_get(
1274    _ctx: *mut c_void,
1275    obj: YogStr,
1276    player: YogStr,
1277    out: *mut i32,
1278) -> bool {
1279    let Some(mut env) = get_env() else {
1280        return false;
1281    };
1282    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else {
1283        return false;
1284    };
1285    match env
1286        .call_static_method(
1287            "dev/yog/NativeBridge",
1288            "scoreboardGet",
1289            "(Ljava/lang/String;Ljava/lang/String;)I",
1290            &[JValue::Object(&jo), JValue::Object(&jp)],
1291        )
1292        .and_then(|v| v.i())
1293    {
1294        Ok(v) if v != i32::MIN => {
1295            *out = v;
1296            true
1297        }
1298        _ => false,
1299    }
1300}
1301
1302unsafe extern "C" fn srv_scoreboard_set(
1303    _ctx: *mut c_void,
1304    obj: YogStr,
1305    player: YogStr,
1306    score: i32,
1307) -> bool {
1308    let Some(mut env) = get_env() else {
1309        return false;
1310    };
1311    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else {
1312        return false;
1313    };
1314    env.call_static_method(
1315        "dev/yog/NativeBridge",
1316        "scoreboardSet",
1317        "(Ljava/lang/String;Ljava/lang/String;I)Z",
1318        &[JValue::Object(&jo), JValue::Object(&jp), JValue::Int(score)],
1319    )
1320    .and_then(|v| v.z())
1321    .unwrap_or(false)
1322}
1323
1324unsafe extern "C" fn srv_scoreboard_add(
1325    _ctx: *mut c_void,
1326    obj: YogStr,
1327    player: YogStr,
1328    delta: i32,
1329    out: *mut i32,
1330) -> bool {
1331    let Some(mut env) = get_env() else {
1332        return false;
1333    };
1334    let (Some(jo), Some(jp)) = (ys_to_java(&mut env, obj), ys_to_java(&mut env, player)) else {
1335        return false;
1336    };
1337    match env
1338        .call_static_method(
1339            "dev/yog/NativeBridge",
1340            "scoreboardAdd",
1341            "(Ljava/lang/String;Ljava/lang/String;I)I",
1342            &[JValue::Object(&jo), JValue::Object(&jp), JValue::Int(delta)],
1343        )
1344        .and_then(|v| v.i())
1345    {
1346        Ok(v) if v != i32::MIN => {
1347            *out = v;
1348            true
1349        }
1350        _ => false,
1351    }
1352}
1353
1354unsafe extern "C" fn srv_bossbar_create(
1355    _ctx: *mut c_void,
1356    id: YogStr,
1357    title: YogStr,
1358    color: YogStr,
1359    style: YogStr,
1360) -> bool {
1361    let Some(mut env) = get_env() else {
1362        return false;
1363    };
1364    let (Some(ji), Some(jt), Some(jc), Some(js)) = (
1365        ys_to_java(&mut env, id),
1366        ys_to_java(&mut env, title),
1367        ys_to_java(&mut env, color),
1368        ys_to_java(&mut env, style),
1369    ) else {
1370        return false;
1371    };
1372    env.call_static_method(
1373        "dev/yog/NativeBridge",
1374        "bossbarCreate",
1375        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Z",
1376        &[
1377            JValue::Object(&ji),
1378            JValue::Object(&jt),
1379            JValue::Object(&jc),
1380            JValue::Object(&js),
1381        ],
1382    )
1383    .and_then(|v| v.z())
1384    .unwrap_or(false)
1385}
1386
1387unsafe extern "C" fn srv_bossbar_remove(_ctx: *mut c_void, id: YogStr) -> bool {
1388    let Some(mut env) = get_env() else {
1389        return false;
1390    };
1391    let Some(ji) = ys_to_java(&mut env, id) else {
1392        return false;
1393    };
1394    env.call_static_method(
1395        "dev/yog/NativeBridge",
1396        "bossbarRemove",
1397        "(Ljava/lang/String;)Z",
1398        &[JValue::Object(&ji)],
1399    )
1400    .and_then(|v| v.z())
1401    .unwrap_or(false)
1402}
1403
1404unsafe extern "C" fn srv_bossbar_set_title(_ctx: *mut c_void, id: YogStr, title: YogStr) -> bool {
1405    let Some(mut env) = get_env() else {
1406        return false;
1407    };
1408    let (Some(ji), Some(jt)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, title)) else {
1409        return false;
1410    };
1411    env.call_static_method(
1412        "dev/yog/NativeBridge",
1413        "bossbarSetTitle",
1414        "(Ljava/lang/String;Ljava/lang/String;)Z",
1415        &[JValue::Object(&ji), JValue::Object(&jt)],
1416    )
1417    .and_then(|v| v.z())
1418    .unwrap_or(false)
1419}
1420
1421unsafe extern "C" fn srv_bossbar_set_progress(
1422    _ctx: *mut c_void,
1423    id: YogStr,
1424    progress: f32,
1425) -> bool {
1426    let Some(mut env) = get_env() else {
1427        return false;
1428    };
1429    let Some(ji) = ys_to_java(&mut env, id) else {
1430        return false;
1431    };
1432    env.call_static_method(
1433        "dev/yog/NativeBridge",
1434        "bossbarSetProgress",
1435        "(Ljava/lang/String;F)Z",
1436        &[JValue::Object(&ji), JValue::Float(progress)],
1437    )
1438    .and_then(|v| v.z())
1439    .unwrap_or(false)
1440}
1441
1442unsafe extern "C" fn srv_bossbar_set_color(_ctx: *mut c_void, id: YogStr, color: YogStr) -> bool {
1443    let Some(mut env) = get_env() else {
1444        return false;
1445    };
1446    let (Some(ji), Some(jc)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, color)) else {
1447        return false;
1448    };
1449    env.call_static_method(
1450        "dev/yog/NativeBridge",
1451        "bossbarSetColor",
1452        "(Ljava/lang/String;Ljava/lang/String;)Z",
1453        &[JValue::Object(&ji), JValue::Object(&jc)],
1454    )
1455    .and_then(|v| v.z())
1456    .unwrap_or(false)
1457}
1458
1459unsafe extern "C" fn srv_bossbar_add_player(_ctx: *mut c_void, id: YogStr, player: YogStr) -> bool {
1460    let Some(mut env) = get_env() else {
1461        return false;
1462    };
1463    let (Some(ji), Some(jp)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, player)) else {
1464        return false;
1465    };
1466    env.call_static_method(
1467        "dev/yog/NativeBridge",
1468        "bossbarAddPlayer",
1469        "(Ljava/lang/String;Ljava/lang/String;)Z",
1470        &[JValue::Object(&ji), JValue::Object(&jp)],
1471    )
1472    .and_then(|v| v.z())
1473    .unwrap_or(false)
1474}
1475
1476unsafe extern "C" fn srv_bossbar_remove_player(
1477    _ctx: *mut c_void,
1478    id: YogStr,
1479    player: YogStr,
1480) -> bool {
1481    let Some(mut env) = get_env() else {
1482        return false;
1483    };
1484    let (Some(ji), Some(jp)) = (ys_to_java(&mut env, id), ys_to_java(&mut env, player)) else {
1485        return false;
1486    };
1487    env.call_static_method(
1488        "dev/yog/NativeBridge",
1489        "bossbarRemovePlayer",
1490        "(Ljava/lang/String;Ljava/lang/String;)Z",
1491        &[JValue::Object(&ji), JValue::Object(&jp)],
1492    )
1493    .and_then(|v| v.z())
1494    .unwrap_or(false)
1495}
1496
1497unsafe extern "C" fn srv_bossbar_set_visible(_ctx: *mut c_void, id: YogStr, visible: bool) -> bool {
1498    let Some(mut env) = get_env() else {
1499        return false;
1500    };
1501    let Some(ji) = ys_to_java(&mut env, id) else {
1502        return false;
1503    };
1504    env.call_static_method(
1505        "dev/yog/NativeBridge",
1506        "bossbarSetVisible",
1507        "(Ljava/lang/String;Z)Z",
1508        &[JValue::Object(&ji), JValue::Bool(visible as u8)],
1509    )
1510    .and_then(|v| v.z())
1511    .unwrap_or(false)
1512}
1513
1514unsafe extern "C" fn srv_get_block_nbt(
1515    _ctx: *mut c_void,
1516    dim: YogStr,
1517    pos: YogBlockPos,
1518) -> YogOwnedStr {
1519    let Some(mut env) = get_env() else {
1520        return YogOwnedStr::NONE;
1521    };
1522    let Some(jd) = ys_to_java(&mut env, dim) else {
1523        return YogOwnedStr::NONE;
1524    };
1525    let ret = env.call_static_method(
1526        "dev/yog/NativeBridge",
1527        "getBlockNbt",
1528        "(Ljava/lang/String;III)Ljava/lang/String;",
1529        &[
1530            JValue::Object(&jd),
1531            JValue::Int(pos.x),
1532            JValue::Int(pos.y),
1533            JValue::Int(pos.z),
1534        ],
1535    );
1536    match ret.and_then(|v| v.l()) {
1537        Ok(obj) => jstring_to_owned(&mut env, obj),
1538        _ => YogOwnedStr::NONE,
1539    }
1540}
1541
1542unsafe extern "C" fn srv_set_block_nbt(
1543    _ctx: *mut c_void,
1544    dim: YogStr,
1545    pos: YogBlockPos,
1546    snbt: YogStr,
1547) -> bool {
1548    let Some(mut env) = get_env() else {
1549        return false;
1550    };
1551    let (Some(jd), Some(js)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, snbt)) else {
1552        return false;
1553    };
1554    env.call_static_method(
1555        "dev/yog/NativeBridge",
1556        "setBlockNbt",
1557        "(Ljava/lang/String;IIILjava/lang/String;)Z",
1558        &[
1559            JValue::Object(&jd),
1560            JValue::Int(pos.x),
1561            JValue::Int(pos.y),
1562            JValue::Int(pos.z),
1563            JValue::Object(&js),
1564        ],
1565    )
1566    .and_then(|v| v.z())
1567    .unwrap_or(false)
1568}
1569
1570unsafe extern "C" fn srv_get_inventory_slot(
1571    _ctx: *mut c_void,
1572    dim: YogStr,
1573    pos: yog_abi::YogBlockPos,
1574    slot: u32,
1575) -> YogOwnedStr {
1576    let Some(mut env) = get_env() else {
1577        return YogOwnedStr::NONE;
1578    };
1579    let Some(jd) = ys_to_java(&mut env, dim) else {
1580        return YogOwnedStr::NONE;
1581    };
1582    let ret = env.call_static_method(
1583        "dev/yog/NativeBridge",
1584        "getInventorySlot",
1585        "(Ljava/lang/String;IIII)Ljava/lang/String;",
1586        &[
1587            JValue::Object(&jd),
1588            JValue::Int(pos.x),
1589            JValue::Int(pos.y),
1590            JValue::Int(pos.z),
1591            JValue::Int(slot as i32),
1592        ],
1593    );
1594    match ret.and_then(|v| v.l()) {
1595        Ok(obj) => jstring_to_owned(&mut env, obj),
1596        _ => YogOwnedStr::NONE,
1597    }
1598}
1599
1600unsafe extern "C" fn srv_set_inventory_slot(
1601    _ctx: *mut c_void,
1602    dim: YogStr,
1603    pos: yog_abi::YogBlockPos,
1604    slot: u32,
1605    item_id: YogStr,
1606    count: u32,
1607) -> bool {
1608    let Some(mut env) = get_env() else {
1609        return false;
1610    };
1611    let (Some(jd), Some(ji)) = (ys_to_java(&mut env, dim), ys_to_java(&mut env, item_id)) else {
1612        return false;
1613    };
1614    env.call_static_method(
1615        "dev/yog/NativeBridge",
1616        "setInventorySlot",
1617        "(Ljava/lang/String;IIIILjava/lang/String;I)Z",
1618        &[
1619            JValue::Object(&jd),
1620            JValue::Int(pos.x),
1621            JValue::Int(pos.y),
1622            JValue::Int(pos.z),
1623            JValue::Int(slot as i32),
1624            JValue::Object(&ji),
1625            JValue::Int(count as i32),
1626        ],
1627    )
1628    .and_then(|v| v.z())
1629    .unwrap_or(false)
1630}
1631
1632unsafe extern "C" fn srv_player_inventory(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1633    let Some(mut env) = get_env() else {
1634        return YogOwnedStr::NONE;
1635    };
1636    let Some(jp) = ys_to_java(&mut env, player) else {
1637        return YogOwnedStr::NONE;
1638    };
1639    let ret = env.call_static_method(
1640        "dev/yog/NativeBridge",
1641        "playerInventory",
1642        "(Ljava/lang/String;)Ljava/lang/String;",
1643        &[JValue::Object(&jp)],
1644    );
1645    match ret.and_then(|v| v.l()) {
1646        Ok(obj) => jstring_to_owned(&mut env, obj),
1647        _ => YogOwnedStr::NONE,
1648    }
1649}
1650
1651unsafe extern "C" fn srv_player_set_slot(
1652    _ctx: *mut c_void,
1653    player: YogStr,
1654    slot: u32,
1655    item_id: YogStr,
1656    count: u32,
1657) -> bool {
1658    let Some(mut env) = get_env() else {
1659        return false;
1660    };
1661    let (Some(jp), Some(ji)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, item_id)) else {
1662        return false;
1663    };
1664    env.call_static_method(
1665        "dev/yog/NativeBridge",
1666        "playerSetSlot",
1667        "(Ljava/lang/String;ILjava/lang/String;I)Z",
1668        &[
1669            JValue::Object(&jp),
1670            JValue::Int(slot as i32),
1671            JValue::Object(&ji),
1672            JValue::Int(count as i32),
1673        ],
1674    )
1675    .and_then(|v| v.z())
1676    .unwrap_or(false)
1677}
1678
1679unsafe extern "C" fn srv_player_teleport_dim(
1680    _ctx: *mut c_void,
1681    player: YogStr,
1682    dim: YogStr,
1683    pos: YogVec3,
1684) -> bool {
1685    let Some(mut env) = get_env() else {
1686        return false;
1687    };
1688    let (Some(jp), Some(jd)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, dim)) else {
1689        return false;
1690    };
1691    env.call_static_method(
1692        "dev/yog/NativeBridge",
1693        "teleportToDim",
1694        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
1695        &[
1696            JValue::Object(&jp),
1697            JValue::Object(&jd),
1698            JValue::Double(pos.x),
1699            JValue::Double(pos.y),
1700            JValue::Double(pos.z),
1701        ],
1702    )
1703    .and_then(|v| v.z())
1704    .unwrap_or(false)
1705}
1706
1707unsafe extern "C" fn srv_entity_teleport_dim(
1708    _ctx: *mut c_void,
1709    uuid: YogStr,
1710    dim: YogStr,
1711    pos: YogVec3,
1712) -> bool {
1713    let Some(mut env) = get_env() else {
1714        return false;
1715    };
1716    let (Some(ju), Some(jd)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, dim)) else {
1717        return false;
1718    };
1719    env.call_static_method(
1720        "dev/yog/NativeBridge",
1721        "entityTeleportToDim",
1722        "(Ljava/lang/String;Ljava/lang/String;DDD)Z",
1723        &[
1724            JValue::Object(&ju),
1725            JValue::Object(&jd),
1726            JValue::Double(pos.x),
1727            JValue::Double(pos.y),
1728            JValue::Double(pos.z),
1729        ],
1730    )
1731    .and_then(|v| v.z())
1732    .unwrap_or(false)
1733}
1734
1735unsafe extern "C" fn srv_online_players(_ctx: *mut c_void) -> YogOwnedStr {
1736    let Some(mut env) = get_env() else {
1737        return YogOwnedStr::NONE;
1738    };
1739    let ret = env.call_static_method(
1740        "dev/yog/NativeBridge",
1741        "onlinePlayers",
1742        "()Ljava/lang/String;",
1743        &[],
1744    );
1745    match ret.and_then(|v| v.l()) {
1746        Ok(obj) => jstring_to_owned(&mut env, obj),
1747        _ => YogOwnedStr::NONE,
1748    }
1749}
1750
1751unsafe extern "C" fn srv_world_entity_count(
1752    _ctx: *mut c_void,
1753    dim: YogStr,
1754    entity_type: YogStr,
1755) -> i32 {
1756    let Some(mut env) = get_env() else { return -1 };
1757    let d = dim.as_str();
1758    let et = entity_type.as_str();
1759    let jd = match env.new_string(d) {
1760        Ok(s) => s,
1761        Err(_) => return -1,
1762    };
1763    let jet = match env.new_string(et) {
1764        Ok(s) => s,
1765        Err(_) => return -1,
1766    };
1767    let ret = env.call_static_method(
1768        "dev/yog/NativeBridge",
1769        "worldEntityCount",
1770        "(Ljava/lang/String;Ljava/lang/String;)I",
1771        &[JValue::Object(&jd), JValue::Object(&jet)],
1772    );
1773    ret.and_then(|v| v.i()).unwrap_or(-1)
1774}
1775
1776unsafe extern "C" fn srv_game_dir(_ctx: *mut c_void) -> YogOwnedStr {
1777    let Some(mut env) = get_env() else {
1778        return YogOwnedStr::NONE;
1779    };
1780    let ret = env.call_static_method(
1781        "dev/yog/NativeBridge",
1782        "gameDir",
1783        "()Ljava/lang/String;",
1784        &[],
1785    );
1786    match ret.and_then(|v| v.l()) {
1787        Ok(obj) => jstring_to_owned(&mut env, obj),
1788        _ => YogOwnedStr::NONE,
1789    }
1790}
1791
1792unsafe extern "C" fn srv_entity_get_nbt(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
1793    let Some(mut env) = get_env() else {
1794        return YogOwnedStr::NONE;
1795    };
1796    let Some(ju) = ys_to_java(&mut env, uuid) else {
1797        return YogOwnedStr::NONE;
1798    };
1799    let ret = env.call_static_method(
1800        "dev/yog/NativeBridge",
1801        "entityGetNbt",
1802        "(Ljava/lang/String;)Ljava/lang/String;",
1803        &[JValue::Object(&ju)],
1804    );
1805    match ret.and_then(|v| v.l()) {
1806        Ok(obj) => jstring_to_owned(&mut env, obj),
1807        _ => YogOwnedStr::NONE,
1808    }
1809}
1810
1811unsafe extern "C" fn srv_entity_set_nbt(_ctx: *mut c_void, uuid: YogStr, snbt: YogStr) -> bool {
1812    let Some(mut env) = get_env() else {
1813        return false;
1814    };
1815    let (Some(ju), Some(js)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, snbt)) else {
1816        return false;
1817    };
1818    env.call_static_method(
1819        "dev/yog/NativeBridge",
1820        "entitySetNbt",
1821        "(Ljava/lang/String;Ljava/lang/String;)Z",
1822        &[JValue::Object(&ju), JValue::Object(&js)],
1823    )
1824    .and_then(|v| v.z())
1825    .unwrap_or(false)
1826}
1827
1828unsafe extern "C" fn srv_spawn_particles(
1829    _ctx: *mut c_void,
1830    dim: YogStr,
1831    pos: YogVec3,
1832    particle_type: YogStr,
1833    count: i32,
1834    dx: f64,
1835    dy: f64,
1836    dz: f64,
1837    speed: f64,
1838) -> bool {
1839    let Some(mut env) = get_env() else {
1840        return false;
1841    };
1842    let (Some(jd), Some(jp)) = (
1843        ys_to_java(&mut env, dim),
1844        ys_to_java(&mut env, particle_type),
1845    ) else {
1846        return false;
1847    };
1848    env.call_static_method(
1849        "dev/yog/NativeBridge",
1850        "spawnParticles",
1851        "(Ljava/lang/String;DDDLjava/lang/String;IDDDD)Z",
1852        &[
1853            JValue::Object(&jd),
1854            JValue::Double(pos.x),
1855            JValue::Double(pos.y),
1856            JValue::Double(pos.z),
1857            JValue::Object(&jp),
1858            JValue::Int(count),
1859            JValue::Double(dx),
1860            JValue::Double(dy),
1861            JValue::Double(dz),
1862            JValue::Double(speed),
1863        ],
1864    )
1865    .and_then(|v| v.z())
1866    .unwrap_or(false)
1867}
1868
1869unsafe extern "C" fn srv_entity_attribute_get(
1870    _ctx: *mut c_void,
1871    uuid: YogStr,
1872    attr: YogStr,
1873) -> f64 {
1874    let Some(mut env) = get_env() else {
1875        return f64::NAN;
1876    };
1877    let (Some(ju), Some(ja)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, attr)) else {
1878        return f64::NAN;
1879    };
1880    env.call_static_method(
1881        "dev/yog/NativeBridge",
1882        "entityAttributeGet",
1883        "(Ljava/lang/String;Ljava/lang/String;)D",
1884        &[JValue::Object(&ju), JValue::Object(&ja)],
1885    )
1886    .and_then(|v| v.d())
1887    .unwrap_or(f64::NAN)
1888}
1889
1890unsafe extern "C" fn srv_entity_attribute_set(
1891    _ctx: *mut c_void,
1892    uuid: YogStr,
1893    attr: YogStr,
1894    value: f64,
1895) -> bool {
1896    let Some(mut env) = get_env() else {
1897        return false;
1898    };
1899    let (Some(ju), Some(ja)) = (ys_to_java(&mut env, uuid), ys_to_java(&mut env, attr)) else {
1900        return false;
1901    };
1902    env.call_static_method(
1903        "dev/yog/NativeBridge",
1904        "entityAttributeSet",
1905        "(Ljava/lang/String;Ljava/lang/String;D)Z",
1906        &[
1907            JValue::Object(&ju),
1908            JValue::Object(&ja),
1909            JValue::Double(value),
1910        ],
1911    )
1912    .and_then(|v| v.z())
1913    .unwrap_or(false)
1914}
1915
1916unsafe extern "C" fn srv_get_held_item_nbt(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1917    let Some(mut env) = get_env() else {
1918        return YogOwnedStr::NONE;
1919    };
1920    let Some(jp) = ys_to_java(&mut env, player) else {
1921        return YogOwnedStr::NONE;
1922    };
1923    let ret = env.call_static_method(
1924        "dev/yog/NativeBridge",
1925        "getHeldItemNbt",
1926        "(Ljava/lang/String;)Ljava/lang/String;",
1927        &[JValue::Object(&jp)],
1928    );
1929    match ret.and_then(|v| v.l()) {
1930        Ok(obj) => jstring_to_owned(&mut env, obj),
1931        _ => YogOwnedStr::NONE,
1932    }
1933}
1934
1935unsafe extern "C" fn srv_set_held_item_nbt(
1936    _ctx: *mut c_void,
1937    player: YogStr,
1938    snbt: YogStr,
1939) -> bool {
1940    let Some(mut env) = get_env() else {
1941        return false;
1942    };
1943    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, snbt)) else {
1944        return false;
1945    };
1946    env.call_static_method(
1947        "dev/yog/NativeBridge",
1948        "setHeldItemNbt",
1949        "(Ljava/lang/String;Ljava/lang/String;)Z",
1950        &[JValue::Object(&jp), JValue::Object(&js)],
1951    )
1952    .and_then(|v| v.z())
1953    .unwrap_or(false)
1954}
1955
1956unsafe extern "C" fn srv_get_offhand_item_nbt(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
1957    let Some(mut env) = get_env() else {
1958        return YogOwnedStr::NONE;
1959    };
1960    let Some(jp) = ys_to_java(&mut env, player) else {
1961        return YogOwnedStr::NONE;
1962    };
1963    let ret = env.call_static_method(
1964        "dev/yog/NativeBridge",
1965        "getOffhandItemNbt",
1966        "(Ljava/lang/String;)Ljava/lang/String;",
1967        &[JValue::Object(&jp)],
1968    );
1969    match ret.and_then(|v| v.l()) {
1970        Ok(obj) => jstring_to_owned(&mut env, obj),
1971        _ => YogOwnedStr::NONE,
1972    }
1973}
1974
1975unsafe extern "C" fn srv_set_offhand_item_nbt(
1976    _ctx: *mut c_void,
1977    player: YogStr,
1978    snbt: YogStr,
1979) -> bool {
1980    let Some(mut env) = get_env() else {
1981        return false;
1982    };
1983    let (Some(jp), Some(js)) = (ys_to_java(&mut env, player), ys_to_java(&mut env, snbt)) else {
1984        return false;
1985    };
1986    env.call_static_method(
1987        "dev/yog/NativeBridge",
1988        "setOffhandItemNbt",
1989        "(Ljava/lang/String;Ljava/lang/String;)Z",
1990        &[JValue::Object(&jp), JValue::Object(&js)],
1991    )
1992    .and_then(|v| v.z())
1993    .unwrap_or(false)
1994}
1995
1996unsafe extern "C" fn srv_get_slot_item(
1997    _ctx: *mut c_void,
1998    player: YogStr,
1999    slot: u32,
2000) -> YogOwnedStr {
2001    let Some(mut env) = get_env() else {
2002        return YogOwnedStr::NONE;
2003    };
2004    let Some(jp) = ys_to_java(&mut env, player) else {
2005        return YogOwnedStr::NONE;
2006    };
2007    let ret = env.call_static_method(
2008        "dev/yog/NativeBridge",
2009        "getSlotItem",
2010        "(Ljava/lang/String;I)Ljava/lang/String;",
2011        &[JValue::Object(&jp), JValue::Int(slot as i32)],
2012    );
2013    match ret.and_then(|v| v.l()) {
2014        Ok(obj) => jstring_to_owned(&mut env, obj),
2015        _ => YogOwnedStr::NONE,
2016    }
2017}
2018
2019unsafe extern "C" fn srv_set_slot_item(
2020    _ctx: *mut c_void,
2021    player: YogStr,
2022    slot: u32,
2023    item_id: YogStr,
2024    count: u32,
2025    snbt: YogStr,
2026) -> bool {
2027    let Some(mut env) = get_env() else {
2028        return false;
2029    };
2030    let (Some(jp), Some(ji), Some(js)) = (
2031        ys_to_java(&mut env, player),
2032        ys_to_java(&mut env, item_id),
2033        ys_to_java(&mut env, snbt),
2034    ) else {
2035        return false;
2036    };
2037    env.call_static_method(
2038        "dev/yog/NativeBridge",
2039        "setSlotItem",
2040        "(Ljava/lang/String;ILjava/lang/String;ILjava/lang/String;)Z",
2041        &[
2042            JValue::Object(&jp),
2043            JValue::Int(slot as i32),
2044            JValue::Object(&ji),
2045            JValue::Int(count as i32),
2046            JValue::Object(&js),
2047        ],
2048    )
2049    .and_then(|v| v.z())
2050    .unwrap_or(false)
2051}
2052
2053// ── ABI minor 14 — low-level GPU pipeline ────────────────────────────────────
2054//
2055// All raw GL calls go through `glow::Context` stored in GL.
2056// `draw2d_*` functions still call JNI (NativeDraw) for MC text/texture rendering.
2057// Everything is called on the render thread — no synchronization needed.
2058
2059// ── helpers ───────────────────────────────────────────────────────────────────
2060
2061fn gl_draw_mode(mode: u8) -> u32 {
2062    match mode {
2063        1 => glow::LINES,
2064        2 => glow::LINE_STRIP,
2065        3 => glow::TRIANGLE_STRIP,
2066        4 => glow::TRIANGLE_FAN,
2067        _ => glow::TRIANGLES,
2068    }
2069}
2070
2071fn gl_attr_type(dtype: u8) -> u32 {
2072    match dtype {
2073        1 => glow::UNSIGNED_BYTE,
2074        2 => glow::INT,
2075        3 => glow::UNSIGNED_INT,
2076        _ => glow::FLOAT,
2077    }
2078}
2079
2080unsafe fn compile_shader(gl: &glow::Context, stage: u32, src: &str) -> Option<glow::NativeShader> {
2081    let sh = gl.create_shader(stage).ok()?;
2082    gl.shader_source(sh, src);
2083    gl.compile_shader(sh);
2084    if !gl.get_shader_compile_status(sh) {
2085        yog_logging::error!("yog-gfx shader compile: {}", gl.get_shader_info_log(sh));
2086        gl.delete_shader(sh);
2087        return None;
2088    }
2089    Some(sh)
2090}
2091
2092// ── GPU buffers ───────────────────────────────────────────────────────────────
2093
2094unsafe extern "C" fn gfx_buf_create() -> u32 {
2095    let Some(g) = GL.get() else { return 0 };
2096    g.0.create_buffer().map(|b| b.0.get()).unwrap_or(0)
2097}
2098
2099unsafe extern "C" fn gfx_buf_delete(handle: u32) {
2100    let Some(g) = GL.get() else { return };
2101    let Some(n) = NonZeroU32::new(handle) else {
2102        return;
2103    };
2104    g.0.delete_buffer(glow::NativeBuffer(n));
2105}
2106
2107unsafe extern "C" fn gfx_buf_data(handle: u32, bytes: *const u8, len: u32, dynamic: bool) {
2108    let Some(g) = GL.get() else { return };
2109    let Some(n) = NonZeroU32::new(handle) else {
2110        return;
2111    };
2112    let gl = &g.0;
2113    let data = std::slice::from_raw_parts(bytes, len as usize);
2114    let usage = if dynamic {
2115        glow::DYNAMIC_DRAW
2116    } else {
2117        glow::STATIC_DRAW
2118    };
2119    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
2120    gl.buffer_data_u8_slice(glow::ARRAY_BUFFER, data, usage);
2121    gl.bind_buffer(glow::ARRAY_BUFFER, None);
2122}
2123
2124unsafe extern "C" fn gfx_buf_subdata(handle: u32, offset: u32, bytes: *const u8, len: u32) {
2125    let Some(g) = GL.get() else { return };
2126    let Some(n) = NonZeroU32::new(handle) else {
2127        return;
2128    };
2129    let gl = &g.0;
2130    let data = std::slice::from_raw_parts(bytes, len as usize);
2131    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(n)));
2132    gl.buffer_sub_data_u8_slice(glow::ARRAY_BUFFER, offset as i32, data);
2133    gl.bind_buffer(glow::ARRAY_BUFFER, None);
2134}
2135
2136// ── Vertex arrays ─────────────────────────────────────────────────────────────
2137
2138unsafe extern "C" fn gfx_vao_create() -> u32 {
2139    let Some(g) = GL.get() else { return 0 };
2140    g.0.create_vertex_array().map(|v| v.0.get()).unwrap_or(0)
2141}
2142
2143unsafe extern "C" fn gfx_vao_delete(handle: u32) {
2144    let Some(g) = GL.get() else { return };
2145    let Some(n) = NonZeroU32::new(handle) else {
2146        return;
2147    };
2148    g.0.delete_vertex_array(glow::NativeVertexArray(n));
2149}
2150
2151unsafe extern "C" fn gfx_vao_attrib(
2152    vao: u32,
2153    vbo: u32,
2154    index: u32,
2155    components: u8,
2156    dtype: u8,
2157    normalized: bool,
2158    stride: u32,
2159    offset: u32,
2160) {
2161    let Some(g) = GL.get() else { return };
2162    let (Some(vn), Some(bn)) = (NonZeroU32::new(vao), NonZeroU32::new(vbo)) else {
2163        return;
2164    };
2165    let gl = &g.0;
2166    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
2167    gl.bind_buffer(glow::ARRAY_BUFFER, Some(glow::NativeBuffer(bn)));
2168    let gl_type = gl_attr_type(dtype);
2169    if dtype == 2 || dtype == 3 {
2170        gl.vertex_attrib_pointer_i32(
2171            index,
2172            components as i32,
2173            gl_type,
2174            stride as i32,
2175            offset as i32,
2176        );
2177    } else {
2178        gl.vertex_attrib_pointer_f32(
2179            index,
2180            components as i32,
2181            gl_type,
2182            normalized,
2183            stride as i32,
2184            offset as i32,
2185        );
2186    }
2187    gl.enable_vertex_attrib_array(index);
2188    gl.bind_vertex_array(None);
2189}
2190
2191unsafe extern "C" fn gfx_vao_set_ebo(vao: u32, ebo: u32) {
2192    let Some(g) = GL.get() else { return };
2193    let (Some(vn), Some(en)) = (NonZeroU32::new(vao), NonZeroU32::new(ebo)) else {
2194        return;
2195    };
2196    let gl = &g.0;
2197    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
2198    gl.bind_buffer(glow::ELEMENT_ARRAY_BUFFER, Some(glow::NativeBuffer(en)));
2199    gl.bind_vertex_array(None);
2200}
2201
2202// ── Shader programs ───────────────────────────────────────────────────────────
2203
2204/// Returns a path under `~/.cache/yog/shaders/<hash>.ysc` for the given GLSL source pair,
2205/// creating the directory if needed.  Returns `None` if the home directory is unknown.
2206fn shader_cache_path(vert: &str, frag: &str) -> Option<PathBuf> {
2207    use std::hash::{Hash, Hasher};
2208    let mut h = std::collections::hash_map::DefaultHasher::new();
2209    vert.hash(&mut h);
2210    frag.hash(&mut h);
2211    let hash = h.finish();
2212    let dir = std::env::var("HOME")
2213        .map(|home| {
2214            PathBuf::from(home)
2215                .join(".cache")
2216                .join("yog")
2217                .join("shaders")
2218        })
2219        .ok()?;
2220    std::fs::create_dir_all(&dir).ok()?;
2221    Some(dir.join(format!("{hash:016x}.ysc")))
2222}
2223
2224/// Try restoring a program from a binary blob (`[4 LE bytes: GL format][binary…]`).
2225/// Returns `Some(handle)` if the driver accepts the binary, `None` otherwise.
2226///
2227/// Uses `glProgramBinary` (GL 4.1 / ARB_get_program_binary) via the raw pointer
2228/// captured in `nativeGlInit`.  Returns `None` if the extension is unavailable.
2229unsafe fn load_shader_binary(gl: &glow::Context, data: &[u8]) -> Option<glow::NativeProgram> {
2230    if data.len() < 4 {
2231        return None;
2232    }
2233    type ProgramBinaryFn = unsafe extern "system" fn(u32, u32, *const c_void, i32);
2234    let fn_ptr = (*GL_PROGRAM_BINARY.get()?)?;
2235    let program_binary: ProgramBinaryFn = std::mem::transmute(fn_ptr);
2236
2237    let fmt = u32::from_le_bytes([data[0], data[1], data[2], data[3]]);
2238    let prog = gl.create_program().ok()?;
2239    program_binary(
2240        prog.0.get(),
2241        fmt,
2242        data[4..].as_ptr() as *const c_void,
2243        (data.len() - 4) as i32,
2244    );
2245    if gl.get_program_link_status(prog) {
2246        Some(prog)
2247    } else {
2248        gl.delete_program(prog);
2249        None
2250    }
2251}
2252
2253/// Read the compiled binary of a linked program.  Returns empty `Vec` if unsupported.
2254unsafe fn get_shader_binary(prog: glow::NativeProgram) -> (Vec<u8>, u32) {
2255    type GetProgramivFn = unsafe extern "system" fn(u32, u32, *mut i32);
2256    type GetProgramBinaryFn = unsafe extern "system" fn(u32, i32, *mut i32, *mut u32, *mut c_void);
2257
2258    let Some(get_iv_raw) = GL_GET_PROGRAM_IV.get().and_then(|v| *v) else {
2259        return (vec![], 0);
2260    };
2261    let Some(get_bin_raw) = GL_GET_PROGRAM_BINARY.get().and_then(|v| *v) else {
2262        return (vec![], 0);
2263    };
2264    let get_program_iv: GetProgramivFn = std::mem::transmute(get_iv_raw);
2265    let get_program_binary: GetProgramBinaryFn = std::mem::transmute(get_bin_raw);
2266
2267    // Query binary size via glGetProgramiv(GL_PROGRAM_BINARY_LENGTH).
2268    const PROGRAM_BINARY_LENGTH: u32 = 0x8741;
2269    let mut size: i32 = 0;
2270    get_program_iv(prog.0.get(), PROGRAM_BINARY_LENGTH, &mut size);
2271    if size <= 0 {
2272        return (vec![], 0);
2273    }
2274
2275    let mut buf = vec![0u8; size as usize];
2276    let mut actual_len: i32 = 0;
2277    let mut fmt: u32 = 0;
2278    get_program_binary(
2279        prog.0.get(),
2280        size,
2281        &mut actual_len,
2282        &mut fmt,
2283        buf.as_mut_ptr() as *mut c_void,
2284    );
2285    buf.truncate(actual_len.max(0) as usize);
2286    (buf, fmt)
2287}
2288
2289unsafe extern "C" fn gfx_prog_create(vert: YogStr, frag: YogStr, out: *mut u32) -> bool {
2290    let Some(g) = GL.get() else { return false };
2291    let gl = &g.0;
2292    let vert_s = vert.as_str();
2293    let frag_s = frag.as_str();
2294
2295    // Fast path: binary shader cache — avoids GLSL re-compilation on subsequent launches.
2296    let cache_path = shader_cache_path(vert_s, frag_s);
2297    if let Some(ref path) = cache_path {
2298        if let Ok(data) = std::fs::read(path) {
2299            if let Some(prog) = load_shader_binary(gl, &data) {
2300                *out = prog.0.get();
2301                return true;
2302            }
2303            // Cache stale (driver updated?); remove and fall through to GLSL compile.
2304            let _ = std::fs::remove_file(path);
2305        }
2306    }
2307
2308    // GLSL compile path.
2309    let vs = match compile_shader(gl, glow::VERTEX_SHADER, vert_s) {
2310        Some(s) => s,
2311        None => return false,
2312    };
2313    let fs = match compile_shader(gl, glow::FRAGMENT_SHADER, frag_s) {
2314        Some(s) => s,
2315        None => {
2316            gl.delete_shader(vs);
2317            return false;
2318        }
2319    };
2320    let prog = match gl.create_program() {
2321        Ok(p) => p,
2322        Err(e) => {
2323            yog_logging::error!("yog-gfx: create_program: {}", e);
2324            gl.delete_shader(vs);
2325            gl.delete_shader(fs);
2326            return false;
2327        }
2328    };
2329    gl.attach_shader(prog, vs);
2330    gl.attach_shader(prog, fs);
2331    gl.link_program(prog);
2332    gl.detach_shader(prog, vs);
2333    gl.detach_shader(prog, fs);
2334    gl.delete_shader(vs);
2335    gl.delete_shader(fs);
2336    if !gl.get_program_link_status(prog) {
2337        yog_logging::error!("yog-gfx: shader link: {}", gl.get_program_info_log(prog));
2338        gl.delete_program(prog);
2339        return false;
2340    }
2341
2342    // Persist binary so the next launch skips GLSL compilation entirely.
2343    if let Some(ref path) = cache_path {
2344        let (binary, fmt) = get_shader_binary(prog);
2345        if !binary.is_empty() {
2346            let mut blob = fmt.to_le_bytes().to_vec();
2347            blob.extend_from_slice(&binary);
2348            let _ = std::fs::write(path, &blob);
2349        }
2350    }
2351
2352    *out = prog.0.get();
2353    true
2354}
2355
2356unsafe extern "C" fn gfx_prog_delete(handle: u32) {
2357    let Some(g) = GL.get() else { return };
2358    let Some(n) = NonZeroU32::new(handle) else {
2359        return;
2360    };
2361    g.0.delete_program(glow::NativeProgram(n));
2362}
2363
2364macro_rules! with_prog {
2365    ($handle:expr, |$gl:ident, $prog:ident, $loc:ident ($name:expr)| $body:expr) => {{
2366        let Some(g) = GL.get() else { return };
2367        let Some(n) = NonZeroU32::new($handle) else {
2368            return;
2369        };
2370        let $gl = &g.0;
2371        let $prog = glow::NativeProgram(n);
2372        $gl.use_program(Some($prog));
2373        let $loc = $gl.get_uniform_location($prog, $name.as_str());
2374        $body
2375    }};
2376}
2377
2378unsafe extern "C" fn gfx_prog_uniform_1i(prog: u32, name: YogStr, v: i32) {
2379    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_i32(loc.as_ref(), v));
2380}
2381unsafe extern "C" fn gfx_prog_uniform_1f(prog: u32, name: YogStr, v: f32) {
2382    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_1_f32(loc.as_ref(), v));
2383}
2384unsafe extern "C" fn gfx_prog_uniform_2f(prog: u32, name: YogStr, x: f32, y: f32) {
2385    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_2_f32(
2386        loc.as_ref(),
2387        x,
2388        y
2389    ));
2390}
2391unsafe extern "C" fn gfx_prog_uniform_3f(prog: u32, name: YogStr, x: f32, y: f32, z: f32) {
2392    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_3_f32(
2393        loc.as_ref(),
2394        x,
2395        y,
2396        z
2397    ));
2398}
2399unsafe extern "C" fn gfx_prog_uniform_4f(prog: u32, name: YogStr, x: f32, y: f32, z: f32, w: f32) {
2400    with_prog!(prog, |gl, _p, loc(name)| gl.uniform_4_f32(
2401        loc.as_ref(),
2402        x,
2403        y,
2404        z,
2405        w
2406    ));
2407}
2408unsafe extern "C" fn gfx_prog_uniform_mat4(prog: u32, name: YogStr, col_major: *const f32) {
2409    with_prog!(prog, |gl, _p, loc(name)| {
2410        let data = std::slice::from_raw_parts(col_major, 16);
2411        gl.uniform_matrix_4_f32_slice(loc.as_ref(), false, data);
2412    });
2413}
2414
2415// ── Textures ──────────────────────────────────────────────────────────────────
2416
2417unsafe extern "C" fn gfx_tex_create(w: u32, h: u32, rgba: *const u8, linear: bool) -> u32 {
2418    let Some(g) = GL.get() else { return 0 };
2419    let gl = &g.0;
2420    let tex = match gl.create_texture() {
2421        Ok(t) => t,
2422        Err(_) => return 0,
2423    };
2424    gl.bind_texture(glow::TEXTURE_2D, Some(tex));
2425    let filter = if linear { glow::LINEAR } else { glow::NEAREST };
2426    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, filter as i32);
2427    gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, filter as i32);
2428    gl.tex_parameter_i32(
2429        glow::TEXTURE_2D,
2430        glow::TEXTURE_WRAP_S,
2431        glow::CLAMP_TO_EDGE as i32,
2432    );
2433    gl.tex_parameter_i32(
2434        glow::TEXTURE_2D,
2435        glow::TEXTURE_WRAP_T,
2436        glow::CLAMP_TO_EDGE as i32,
2437    );
2438    let pixels = std::slice::from_raw_parts(rgba, (w * h * 4) as usize);
2439    gl.tex_image_2d(
2440        glow::TEXTURE_2D,
2441        0,
2442        glow::RGBA8 as i32,
2443        w as i32,
2444        h as i32,
2445        0,
2446        glow::RGBA,
2447        glow::UNSIGNED_BYTE,
2448        glow::PixelUnpackData::Slice(Some(pixels)),
2449    );
2450    gl.bind_texture(glow::TEXTURE_2D, None);
2451    tex.0.get()
2452}
2453
2454unsafe extern "C" fn gfx_tex_delete(handle: u32) {
2455    let Some(g) = GL.get() else { return };
2456    let Some(n) = NonZeroU32::new(handle) else {
2457        return;
2458    };
2459    g.0.delete_texture(glow::NativeTexture(n));
2460}
2461
2462unsafe extern "C" fn gfx_tex_bind(unit: u32, handle: u32) {
2463    let Some(g) = GL.get() else { return };
2464    let gl = &g.0;
2465    gl.active_texture(glow::TEXTURE0 + unit);
2466    match NonZeroU32::new(handle) {
2467        Some(n) => gl.bind_texture(glow::TEXTURE_2D, Some(glow::NativeTexture(n))),
2468        None => gl.bind_texture(glow::TEXTURE_2D, None),
2469    }
2470}
2471
2472unsafe extern "C" fn gfx_tex_from_mc(id: YogStr) -> u32 {
2473    let Some(mut env) = get_env() else { return 0 };
2474    let Some(ji) = ys_to_java(&mut env, id) else {
2475        return 0;
2476    };
2477    env.call_static_method(
2478        "dev/yog/NativeDraw",
2479        "getMcTextureId",
2480        "(Ljava/lang/String;)I",
2481        &[JValue::Object(&ji)],
2482    )
2483    .and_then(|v| v.i())
2484    .map(|id| id as u32)
2485    .unwrap_or(0)
2486}
2487
2488// ── Draw calls ────────────────────────────────────────────────────────────────
2489
2490unsafe extern "C" fn gfx_draw_arrays(vao: u32, prog: u32, mode: u8, first: u32, count: u32) {
2491    let Some(g) = GL.get() else { return };
2492    let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else {
2493        return;
2494    };
2495    let gl = &g.0;
2496    gl.use_program(Some(glow::NativeProgram(pn)));
2497    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
2498    gl.draw_arrays(gl_draw_mode(mode), first as i32, count as i32);
2499    gl.bind_vertex_array(None);
2500}
2501
2502unsafe extern "C" fn gfx_draw_elements(
2503    vao: u32,
2504    ebo: u32,
2505    prog: u32,
2506    mode: u8,
2507    count: u32,
2508    u32_idx: bool,
2509) {
2510    let Some(g) = GL.get() else { return };
2511    let (Some(vn), Some(pn)) = (NonZeroU32::new(vao), NonZeroU32::new(prog)) else {
2512        return;
2513    };
2514    let gl = &g.0;
2515    gl.use_program(Some(glow::NativeProgram(pn)));
2516    gl.bind_vertex_array(Some(glow::NativeVertexArray(vn)));
2517    // EBO is stored in the VAO; ebo param is informational for safety but not re-bound here.
2518    let _ = ebo;
2519    let idx_type = if u32_idx {
2520        glow::UNSIGNED_INT
2521    } else {
2522        glow::UNSIGNED_SHORT
2523    };
2524    gl.draw_elements(gl_draw_mode(mode), count as i32, idx_type, 0);
2525    gl.bind_vertex_array(None);
2526}
2527
2528// ── Render state ──────────────────────────────────────────────────────────────
2529
2530unsafe extern "C" fn gfx_set_blend(enabled: bool, src: u32, dst: u32) {
2531    let Some(g) = GL.get() else { return };
2532    let gl = &g.0;
2533    if enabled {
2534        gl.enable(glow::BLEND);
2535        gl.blend_func(src, dst);
2536    } else {
2537        gl.disable(glow::BLEND);
2538    }
2539}
2540
2541unsafe extern "C" fn gfx_set_depth(test: bool, write: bool) {
2542    let Some(g) = GL.get() else { return };
2543    let gl = &g.0;
2544    if test {
2545        gl.enable(glow::DEPTH_TEST);
2546    } else {
2547        gl.disable(glow::DEPTH_TEST);
2548    }
2549    gl.depth_mask(write);
2550    // Disable face culling: our 2D quads use CW winding (back-face) due to y-flip.
2551    if !test {
2552        gl.disable(glow::CULL_FACE);
2553    }
2554}
2555
2556unsafe extern "C" fn gfx_set_scissor(x: i32, y: i32, w: i32, h: i32) {
2557    let Some(g) = GL.get() else { return };
2558    let gl = &g.0;
2559    gl.enable(glow::SCISSOR_TEST);
2560    gl.scissor(x, y, w, h);
2561}
2562
2563unsafe extern "C" fn gfx_clear_scissor() {
2564    let Some(g) = GL.get() else { return };
2565    g.0.disable(glow::SCISSOR_TEST);
2566}
2567
2568unsafe extern "C" fn gfx_set_viewport(x: i32, y: i32, w: i32, h: i32) {
2569    let Some(g) = GL.get() else { return };
2570    g.0.viewport(x, y, w, h);
2571}
2572
2573// ── 2D convenience (JNI — uses MC's DrawContext / text renderer) ──────────────
2574
2575unsafe extern "C" fn gfx_draw2d_rect(x1: f32, y1: f32, x2: f32, y2: f32, color: u32) {
2576    let Some(mut env) = get_env() else { return };
2577    let _ = env.call_static_method(
2578        "dev/yog/NativeDraw",
2579        "drawRect",
2580        "(FFFFI)V",
2581        &[
2582            JValue::Float(x1),
2583            JValue::Float(y1),
2584            JValue::Float(x2),
2585            JValue::Float(y2),
2586            JValue::Int(color as i32),
2587        ],
2588    );
2589}
2590
2591unsafe extern "C" fn gfx_draw2d_gradient(
2592    x1: f32,
2593    y1: f32,
2594    x2: f32,
2595    y2: f32,
2596    top: u32,
2597    bottom: u32,
2598) {
2599    let Some(mut env) = get_env() else { return };
2600    let _ = env.call_static_method(
2601        "dev/yog/NativeDraw",
2602        "drawGradientRect",
2603        "(FFFFII)V",
2604        &[
2605            JValue::Float(x1),
2606            JValue::Float(y1),
2607            JValue::Float(x2),
2608            JValue::Float(y2),
2609            JValue::Int(top as i32),
2610            JValue::Int(bottom as i32),
2611        ],
2612    );
2613}
2614
2615unsafe extern "C" fn gfx_draw2d_text(text: YogStr, x: f32, y: f32, color: u32, shadow: bool) {
2616    let Some(mut env) = get_env() else { return };
2617    if let Some(jt) = ys_to_java(&mut env, text) {
2618        let _ = env.call_static_method(
2619            "dev/yog/NativeDraw",
2620            "drawText",
2621            "(Ljava/lang/String;FFIZ)V",
2622            &[
2623                JValue::Object(&jt),
2624                JValue::Float(x),
2625                JValue::Float(y),
2626                JValue::Int(color as i32),
2627                JValue::Bool(shadow as u8),
2628            ],
2629        );
2630    }
2631}
2632
2633unsafe extern "C" fn gfx_draw2d_text_font(
2634    text: YogStr,
2635    font: YogStr,
2636    x: f32,
2637    y: f32,
2638    color: u32,
2639    shadow: bool,
2640) {
2641    let Some(mut env) = get_env() else { return };
2642    let (Some(jt), Some(jf)) = (ys_to_java(&mut env, text), ys_to_java(&mut env, font)) else {
2643        return;
2644    };
2645    let _ = env.call_static_method(
2646        "dev/yog/NativeDraw",
2647        "drawTextFont",
2648        "(Ljava/lang/String;Ljava/lang/String;FFIZ)V",
2649        &[
2650            JValue::Object(&jt),
2651            JValue::Object(&jf),
2652            JValue::Float(x),
2653            JValue::Float(y),
2654            JValue::Int(color as i32),
2655            JValue::Bool(shadow as u8),
2656        ],
2657    );
2658}
2659
2660unsafe extern "C" fn gfx_text_width(text: YogStr, font: YogStr) -> f32 {
2661    let Some(mut env) = get_env() else { return 0.0 };
2662    let (Some(jt), Some(jf)) = (ys_to_java(&mut env, text), ys_to_java(&mut env, font)) else {
2663        return 0.0;
2664    };
2665    match env.call_static_method(
2666        "dev/yog/NativeDraw",
2667        "textWidth",
2668        "(Ljava/lang/String;Ljava/lang/String;)F",
2669        &[JValue::Object(&jt), JValue::Object(&jf)],
2670    ) {
2671        Ok(v) => v.f().unwrap_or(0.0),
2672        Err(_) => {
2673            env.exception_clear().ok();
2674            0.0
2675        }
2676    }
2677}
2678
2679unsafe extern "C" fn gfx_draw2d_item(id: YogStr, x: f32, y: f32, size: f32) {
2680    let Some(mut env) = get_env() else { return };
2681    if let Some(ji) = ys_to_java(&mut env, id) {
2682        if env
2683            .call_static_method(
2684                "dev/yog/NativeDraw",
2685                "drawItem",
2686                "(Ljava/lang/String;FFF)V",
2687                &[
2688                    JValue::Object(&ji),
2689                    JValue::Float(x),
2690                    JValue::Float(y),
2691                    JValue::Float(size),
2692                ],
2693            )
2694            .is_err()
2695        {
2696            env.exception_clear().ok();
2697        }
2698    }
2699}
2700
2701// ── Static GFX function table (function pointers only — per-frame data filled at call time) ──
2702
2703static GFX_FN_TABLE: YogGfxApi = YogGfxApi {
2704    // Per-frame fields zeroed in the static; actual values are set on the stack per render call.
2705    screen_w: 0,
2706    screen_h: 0,
2707    delta_tick: 0.0,
2708    scale_factor: 1.0,
2709    view_proj: [0.0; 16],
2710    camera_pos: [0.0; 3],
2711    player_pos: [0.0; 3],
2712    _pad1: 0.0,
2713    buf_create: gfx_buf_create,
2714    buf_delete: gfx_buf_delete,
2715    buf_data: gfx_buf_data,
2716    buf_subdata: gfx_buf_subdata,
2717    vao_create: gfx_vao_create,
2718    vao_delete: gfx_vao_delete,
2719    vao_attrib: gfx_vao_attrib,
2720    vao_set_ebo: gfx_vao_set_ebo,
2721    prog_create: gfx_prog_create,
2722    prog_delete: gfx_prog_delete,
2723    prog_uniform_1i: gfx_prog_uniform_1i,
2724    prog_uniform_1f: gfx_prog_uniform_1f,
2725    prog_uniform_2f: gfx_prog_uniform_2f,
2726    prog_uniform_3f: gfx_prog_uniform_3f,
2727    prog_uniform_4f: gfx_prog_uniform_4f,
2728    prog_uniform_mat4: gfx_prog_uniform_mat4,
2729    tex_create: gfx_tex_create,
2730    tex_delete: gfx_tex_delete,
2731    tex_bind: gfx_tex_bind,
2732    tex_from_mc: gfx_tex_from_mc,
2733    draw_arrays: gfx_draw_arrays,
2734    draw_elements: gfx_draw_elements,
2735    set_blend: gfx_set_blend,
2736    set_depth: gfx_set_depth,
2737    set_scissor: gfx_set_scissor,
2738    clear_scissor: gfx_clear_scissor,
2739    set_viewport: gfx_set_viewport,
2740    draw2d_rect: gfx_draw2d_rect,
2741    draw2d_gradient: gfx_draw2d_gradient,
2742    draw2d_text: gfx_draw2d_text,
2743    draw2d_item: gfx_draw2d_item,
2744    draw2d_text_font: gfx_draw2d_text_font,
2745    text_width: gfx_text_width,
2746    draw2d_image: images::gfx_draw2d_image,
2747    image_size: images::gfx_image_size,
2748};
2749
2750// ── YogApi registration functions ─────────────────────────────────────────────
2751//
2752// ctx is *const RwLock<RuntimeHandlers> (cast from *mut c_void) — see
2753// `current_registration()` for how each entry gets tagged with the
2754// `LoadedModule` that's registering it.
2755
2756macro_rules! api_event {
2757    ($name:ident, $field:ident, $fn_ty:ty) => {
2758        unsafe extern "C" fn $name(ctx: *mut c_void, ud: *mut c_void, h: $fn_ty) {
2759            let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2760            let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2761            handlers.$field.push((current_registration(), ud, h));
2762        }
2763    };
2764}
2765
2766api_event!(api_on_block_break, block_break, YogBlockBreakFn);
2767api_event!(api_on_chat, chat, YogChatFn);
2768api_event!(api_on_player_join, player_join, YogPlayerFn);
2769api_event!(api_on_player_leave, player_leave, YogPlayerFn);
2770api_event!(api_on_use_item, use_item, YogUseItemFn);
2771api_event!(api_on_use_block, use_block, YogUseBlockFn);
2772api_event!(api_on_attack_entity, attack_entity, YogAttackEntityFn);
2773api_event!(api_on_entity_damage, entity_damage, YogEntityDamageFn);
2774api_event!(api_on_entity_death, entity_death, YogEntityDeathFn);
2775api_event!(api_on_entity_spawn, entity_spawn, YogEntitySpawnFn);
2776api_event!(
2777    api_on_player_place_block,
2778    player_place_block,
2779    YogPlaceBlockFn
2780);
2781api_event!(api_on_player_death, player_death, YogPlayerDeathFn);
2782api_event!(api_on_player_respawn, player_respawn, YogPlayerRespawnFn);
2783api_event!(api_on_advancement, advancement, YogAdvancementFn);
2784api_event!(api_on_entity_interact, entity_interact, YogEntityInteractFn);
2785api_event!(api_on_item_craft, item_craft, YogCraftFn);
2786api_event!(api_on_explosion, explosion, YogExplosionFn);
2787api_event!(api_on_item_pickup, item_pickup, YogItemPickupFn);
2788api_event!(api_on_player_move, player_move, YogPlayerMoveFn);
2789api_event!(api_on_container_open, container_open, YogContainerOpenFn);
2790api_event!(api_on_container_close, container_close, YogContainerCloseFn);
2791api_event!(api_on_projectile_hit, projectile_hit, YogProjectileHitFn);
2792api_event!(api_on_client_tick, client_tick, YogClientFn);
2793api_event!(api_on_hud_render, hud_render, YogHudRenderFn);
2794api_event!(api_on_world_render, world_render, YogWorldRenderFn);
2795api_event!(api_on_key_press, key_press, YogKeyPressFn);
2796api_event!(api_on_screen_open, screen_open, YogScreenFn);
2797api_event!(api_on_screen_close, screen_close, YogScreenFn);
2798api_event!(api_on_server_tick, server_tick, YogServerFn);
2799api_event!(api_on_server_started, server_started, YogServerFn);
2800api_event!(api_on_server_stopping, server_stopping, YogServerFn);
2801
2802unsafe extern "C" fn api_on_packet(
2803    ctx: *mut c_void,
2804    channel: YogStr,
2805    ud: *mut c_void,
2806    h: YogPacketFn,
2807) {
2808    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2809    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2810    handlers
2811        .packets
2812        .insert(channel.as_str().to_owned(), (current_registration(), ud, h));
2813}
2814
2815unsafe extern "C" fn api_on_client_packet(
2816    ctx: *mut c_void,
2817    channel: YogStr,
2818    ud: *mut c_void,
2819    h: YogPacketFn,
2820) {
2821    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2822    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2823    handlers
2824        .client_packets
2825        .insert(channel.as_str().to_owned(), (current_registration(), ud, h));
2826}
2827
2828unsafe extern "C" fn api_register_command(
2829    ctx: *mut c_void,
2830    name: YogStr,
2831    ud: *mut c_void,
2832    h: YogCommandFn,
2833) {
2834    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2835    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2836    handlers
2837        .commands
2838        .entry(name.as_str().to_owned())
2839        .or_default()
2840        .push((current_registration(), None, ud, h));
2841}
2842
2843unsafe extern "C" fn api_register_typed_command(
2844    ctx: *mut c_void,
2845    name: YogStr,
2846    schema: YogStr,
2847    ud: *mut c_void,
2848    h: YogCommandFn,
2849) {
2850    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2851    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2852    let n = name.as_str().to_owned();
2853    handlers.commands.entry(n).or_default().push((
2854        current_registration(),
2855        Some(schema.as_str().to_owned()),
2856        ud,
2857        h,
2858    ));
2859}
2860
2861unsafe extern "C" fn api_register_recipe_json(
2862    ctx: *mut c_void,
2863    namespace: YogStr,
2864    name: YogStr,
2865    json: YogStr,
2866) {
2867    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2868    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2869    let ns = namespace.as_str().to_owned();
2870    let n = name.as_str().to_owned();
2871    let j = json.as_str().to_owned();
2872    // Feed the recipe to already-registered book renderers (crafting pages).
2873    let full_id = format!("{}:{}", ns, n);
2874    for r in handlers.book_renderers.lock().unwrap().values_mut() {
2875        r.add_recipe(full_id.clone(), &j);
2876    }
2877    handlers.recipes.push((ns, n, j));
2878}
2879
2880unsafe extern "C" fn api_register_item(ctx: *mut c_void, def: *const YogItemDef) {
2881    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2882    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2883    let d = &*def;
2884    let food = if d.food_nutrition > 0 {
2885        Some(FoodDef {
2886            nutrition: d.food_nutrition,
2887            saturation: d.food_saturation,
2888            can_always_eat: d.food_always_eat,
2889        })
2890    } else {
2891        None
2892    };
2893    handlers.items.push(ItemDef {
2894        id: d.id.as_str().to_owned(),
2895        max_stack: d.max_stack as u8,
2896        name: if d.name.is_empty() {
2897            None
2898        } else {
2899            Some(d.name.as_str().to_owned())
2900        },
2901        tooltip: if d.tooltip.is_empty() {
2902            None
2903        } else {
2904            Some(d.tooltip.as_str().to_owned())
2905        },
2906        max_damage: d.max_damage,
2907        fire_resistant: d.fire_resistant,
2908        fuel_ticks: d.fuel_ticks,
2909        food,
2910    });
2911}
2912
2913unsafe extern "C" fn api_register_block(ctx: *mut c_void, def: *const YogBlockDef) {
2914    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2915    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2916    let d = &*def;
2917    handlers.blocks.push(BlockDef {
2918        id: d.id.as_str().to_owned(),
2919        hardness: d.hardness,
2920        resistance: d.resistance,
2921        name: if d.name.is_empty() {
2922            None
2923        } else {
2924            Some(d.name.as_str().to_owned())
2925        },
2926        light_level: d.light_level,
2927        sound: if d.sound.is_empty() {
2928            None
2929        } else {
2930            Some(d.sound.as_str().to_owned())
2931        },
2932        requires_tool: d.requires_tool,
2933        no_collision: d.no_collision,
2934        slipperiness: d.slipperiness,
2935        shape: if d.shape == [0.0f32; 6] {
2936            None
2937        } else {
2938            Some(d.shape)
2939        },
2940        connects: d.connects,
2941        connect_groups: if d.connect_groups.is_empty() {
2942            Vec::new()
2943        } else {
2944            d.connect_groups
2945                .as_str()
2946                .split(',')
2947                .map(str::to_owned)
2948                .collect()
2949        },
2950        inventory_id: if d.inventory_id.is_empty() {
2951            None
2952        } else {
2953            Some(d.inventory_id.as_str().to_owned())
2954        },
2955    });
2956}
2957
2958unsafe extern "C" fn api_register_inventory(
2959    ctx: *mut c_void,
2960    def: *const yog_abi::YogInventoryDef,
2961) {
2962    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2963    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2964    let d = &*def;
2965    handlers.inventories.push(yog_inventory::InventoryDef {
2966        id: d.id.as_str().to_owned(),
2967        slot_count: d.slot_count as usize,
2968        layout: yog_inventory::decode_layout(d.layout.as_str()),
2969        include_player_inventory: d.include_player_inventory,
2970        player_inv_offset: (d.player_inv_x, d.player_inv_y),
2971        background_texture: if d.background_texture.is_empty() {
2972            None
2973        } else {
2974            Some(d.background_texture.as_str().to_owned())
2975        },
2976        title: d.title.as_str().to_owned(),
2977        background_size: if d.background_w > 0.0 && d.background_h > 0.0 {
2978            Some((d.background_w, d.background_h))
2979        } else {
2980            None
2981        },
2982    });
2983}
2984
2985unsafe extern "C" fn api_schedule_once(
2986    ctx: *mut c_void,
2987    delay_ticks: u64,
2988    ud: *mut c_void,
2989    h: YogScheduledFn,
2990) {
2991    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2992    let handlers = handlers_lock.write().expect("handlers lock poisoned");
2993    handlers
2994        .scheduler
2995        .lock()
2996        .expect("scheduler poisoned")
2997        .once_tasks
2998        .push(OnceTask {
2999            module: current_registration(),
3000            delay_remaining: delay_ticks,
3001            ud,
3002            f: h,
3003        });
3004}
3005
3006unsafe extern "C" fn api_schedule_repeating(
3007    ctx: *mut c_void,
3008    period_ticks: u64,
3009    ud: *mut c_void,
3010    h: YogScheduledFn,
3011) {
3012    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3013    let handlers = handlers_lock.write().expect("handlers lock poisoned");
3014    handlers
3015        .scheduler
3016        .lock()
3017        .expect("scheduler poisoned")
3018        .repeating_tasks
3019        .push(RepeatingTask {
3020            module: current_registration(),
3021            period: period_ticks,
3022            ticks_left: period_ticks,
3023            ud,
3024            f: h,
3025        });
3026}
3027
3028unsafe extern "C" fn api_register_startup_grant(
3029    ctx: *mut c_void,
3030    grant: *const YogStartupGrantDef,
3031) {
3032    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3033    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3034    let g = &*grant;
3035    let items: Vec<String> = if g.items.is_empty() {
3036        Vec::new()
3037    } else {
3038        unsafe {
3039            g.items
3040                .as_str()
3041                .split('|')
3042                .map(|s: &str| s.to_owned())
3043                .collect()
3044        }
3045    };
3046    let book = if g.book.is_empty() {
3047        None
3048    } else {
3049        Some(unsafe { g.book.as_str().to_owned() })
3050    };
3051    let command = if g.command.is_empty() {
3052        None
3053    } else {
3054        Some(unsafe { g.command.as_str().to_owned() })
3055    };
3056    handlers.startup_grants.push(yog_registry::StartupGrant {
3057        id: unsafe { g.id.as_str().to_owned() },
3058        items,
3059        book,
3060        command,
3061    });
3062}
3063
3064unsafe extern "C" fn api_register_book(ctx: *mut c_void, book_id: YogStr, book_json: YogStr) {
3065    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3066    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3067    let id = unsafe { book_id.as_str().to_owned() };
3068    let json = unsafe { book_json.as_str().to_owned() };
3069    handlers.books.insert(id.clone(), json.clone());
3070    // Parse JSON → Book → BookRenderer so rendering works without Java round-trip.
3071    match serde_json::from_str::<yog_book::Book>(&json) {
3072        Ok(book) => {
3073            let mut renderer = yog_book::BookRenderer::new(book);
3074            // i18n books carry translation keys; shown in the game language.
3075            renderer.set_translator(translate);
3076            // Recipes may register before the book — replay them into the renderer.
3077            for (ns, name, j) in &handlers.recipes {
3078                renderer.add_recipe(format!("{}:{}", ns, name), j);
3079            }
3080            handlers.book_renderers.lock().unwrap().insert(id, renderer);
3081        }
3082        Err(e) => {
3083            yog_logging::warn!(
3084                "book '{}': failed to parse JSON for Rust renderer: {}",
3085                id,
3086                e
3087            );
3088        }
3089    }
3090}
3091
3092unsafe extern "C" fn api_register_dimension_json(ctx: *mut c_void, id: YogStr, json: YogStr) {
3093    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3094    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3095    let id = unsafe { id.as_str().to_owned() };
3096    let json = unsafe { json.as_str().to_owned() };
3097    yog_logging::info!("registered dimension type: {}", id);
3098    handlers.dimensions.insert(id, json);
3099}
3100
3101unsafe extern "C" fn api_register_chunk_generator(
3102    ctx: *mut c_void,
3103    id: YogStr,
3104    ud: *mut c_void,
3105    h: yog_abi::YogChunkGeneratorFn,
3106) {
3107    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3108    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3109    let id = unsafe { id.as_str().to_owned() };
3110    yog_logging::info!("registered chunk generator for dimension: {}", id);
3111    handlers
3112        .chunk_generators
3113        .insert(id, (current_registration(), ud, h));
3114}
3115
3116unsafe extern "C" fn api_register_ui(
3117    ctx: *mut c_void,
3118    ui_id: YogStr,
3119    _layout_json: YogStr,
3120    ud: *mut c_void,
3121    h: yog_abi::YogUIEventFn,
3122) {
3123    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3124    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3125    let id = unsafe { ui_id.as_str().to_owned() };
3126    handlers
3127        .ui_handlers
3128        .insert(id.clone(), (current_registration(), ud, h));
3129    yog_logging::info!("registered UI handler: {}", id);
3130}
3131
3132unsafe extern "C" fn api_on_ui_render(
3133    ctx: *mut c_void,
3134    ui_id: YogStr,
3135    ud: *mut c_void,
3136    h: YogHudRenderFn,
3137) {
3138    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3139    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3140    let id = unsafe { ui_id.as_str().to_owned() };
3141    handlers
3142        .ui_render_handlers
3143        .entry(id)
3144        .or_default()
3145        .push((current_registration(), ud, h));
3146}
3147
3148/// Strip TSV separators so one mod can't corrupt the line format.
3149fn tsv_clean(v: &str) -> String {
3150    v.replace(['\t', '\n', '\r'], " ")
3151}
3152
3153unsafe extern "C" fn api_ui_open(_ctx: *mut c_void, ui_id: YogStr, modal: bool, pause: bool) {
3154    let id = ui_id.as_str().to_string();
3155    if id.is_empty() {
3156        return;
3157    }
3158    let Some(mut env) = get_env() else { return };
3159    let Ok(jid) = env.new_string(&id) else { return };
3160    let jid_obj: JObject = jid.into();
3161    // Java side schedules onto the render thread; no-op on dedicated servers.
3162    if env
3163        .call_static_method(
3164            "dev/yog/NativeBridge",
3165            "openUI",
3166            "(Ljava/lang/String;ZZ)V",
3167            &[
3168                JValue::Object(&jid_obj),
3169                JValue::Bool(modal as u8),
3170                JValue::Bool(pause as u8),
3171            ],
3172        )
3173        .is_err()
3174    {
3175        env.exception_clear().ok();
3176    }
3177}
3178
3179unsafe extern "C" fn api_ui_close(_ctx: *mut c_void, ui_id: YogStr) {
3180    let id = ui_id.as_str().to_string();
3181    let Some(mut env) = get_env() else { return };
3182    let Ok(jid) = env.new_string(&id) else { return };
3183    let jid_obj: JObject = jid.into();
3184    // Java side defers onto the render thread (after the current event) and
3185    // checks the open screen is that Yog UI; no-op on dedicated servers.
3186    if env
3187        .call_static_method(
3188            "dev/yog/NativeBridge",
3189            "closeUI",
3190            "(Ljava/lang/String;)V",
3191            &[JValue::Object(&jid_obj)],
3192        )
3193        .is_err()
3194    {
3195        env.exception_clear().ok();
3196    }
3197}
3198
3199unsafe extern "C" fn api_ui_consume_event(_ctx: *mut c_void) {
3200    ui_jni::consume_event();
3201}
3202
3203unsafe extern "C" fn api_translate(_ctx: *mut c_void, key: YogStr) -> YogOwnedStr {
3204    translate(key.as_str()).map_or(YogOwnedStr::NONE, YogOwnedStr::from_string)
3205}
3206
3207/// The game's text for translation `key` in the current language — `None`
3208/// when no lang file has it (or there's no JVM).
3209fn translate(key: &str) -> Option<String> {
3210    if key.is_empty() {
3211        return None;
3212    }
3213    let mut env = get_env()?;
3214    let jkey: JObject = env.new_string(key).ok()?.into();
3215    let result = env.call_static_method(
3216        "dev/yog/NativeBridge",
3217        "translate",
3218        "(Ljava/lang/String;)Ljava/lang/String;",
3219        &[JValue::Object(&jkey)],
3220    );
3221    let text = match result.and_then(|v| v.l()) {
3222        Ok(obj) if !obj.as_raw().is_null() => env.get_string(&obj.into()).ok().map(String::from),
3223        Ok(_) => None,
3224        Err(_) => {
3225            env.exception_clear().ok();
3226            None
3227        }
3228    };
3229    let _ = env.delete_local_ref(jkey);
3230    text
3231}
3232
3233unsafe extern "C" fn api_mods_list(_ctx: *mut c_void) -> YogOwnedStr {
3234    let mut lines: Vec<String> = Vec::new();
3235    let infos = MOD_INFOS.lock().expect("mod infos lock poisoned").clone();
3236    for m in &infos {
3237        // A `.yres` name/description shows in the player's language.
3238        let localized = |text: &str, key: &str| {
3239            translate(key).map_or_else(|| text.to_string(), |t| tsv_clean(&t))
3240        };
3241        lines.push(format!(
3242            "yog\t{}\t{}\t{}\t{}\t{}",
3243            m[0],
3244            localized(&m[1], &m[5]),
3245            m[2],
3246            m[3],
3247            localized(&m[4], &m[6])
3248        ));
3249    }
3250    // Loader-side (Java) mods, if the host provides them.
3251    if let Some(mut env) = get_env() {
3252        if let Ok(val) = env.call_static_method(
3253            "dev/yog/NativeBridge",
3254            "listPlatformMods",
3255            "()Ljava/lang/String;",
3256            &[],
3257        ) {
3258            if let Ok(obj) = val.l() {
3259                if !obj.as_raw().is_null() {
3260                    if let Ok(js) = env.get_string(&obj.into()) {
3261                        for line in String::from(js).lines() {
3262                            if !line.trim().is_empty() {
3263                                lines.push(format!("platform\t{line}"));
3264                            }
3265                        }
3266                    }
3267                }
3268            }
3269        } else {
3270            env.exception_clear().ok();
3271        }
3272    }
3273    YogOwnedStr::from_string(lines.join("\n"))
3274}
3275
3276unsafe extern "C" fn api_register_menu_entry(ctx: *mut c_void, label: YogStr, ui_id: YogStr) {
3277    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3278    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3279    let l = unsafe { label.as_str().to_owned() };
3280    let u = unsafe { ui_id.as_str().to_owned() };
3281    handlers.menu_entries.push((l, u));
3282}
3283
3284#[no_mangle]
3285pub extern "system" fn Java_dev_yog_NativeBridge_nativeBookJson<'l>(
3286    mut env: JNIEnv<'l>,
3287    _class: JClass<'l>,
3288    book_id: JString<'l>,
3289) -> jstring {
3290    let id = match env.get_string(&book_id) {
3291        Ok(s) => String::from(s),
3292        Err(_) => return std::ptr::null_mut(),
3293    };
3294    let json = handlers()
3295        .books
3296        .get(&id)
3297        .cloned()
3298        .unwrap_or_else(|| "null".to_string());
3299    env.new_string(json)
3300        .map(|s| s.into_raw())
3301        .unwrap_or(std::ptr::null_mut())
3302}
3303
3304// ── World queries & effects (ABI minor 1) ────────────────────────────────────
3305//
3306// Each of these forwards to a `NativeBridge` static of the same shape; the JNI
3307// signature is derived from the argument list so the two cannot drift apart.
3308
3309#[derive(Clone, Copy)]
3310enum JArg {
3311    S(YogStr),
3312    D(f64),
3313    F(f32),
3314    I(i32),
3315    Z(bool),
3316}
3317
3318/// JNI method descriptor for `args`, returning `ret` (`"Z"` or a String).
3319fn bridge_sig(args: &[JArg], ret: &str) -> String {
3320    let mut sig = String::from("(");
3321    for a in args {
3322        sig.push_str(match a {
3323            JArg::S(_) => "Ljava/lang/String;",
3324            JArg::D(_) => "D",
3325            JArg::F(_) => "F",
3326            JArg::I(_) => "I",
3327            JArg::Z(_) => "Z",
3328        });
3329    }
3330    sig.push(')');
3331    sig.push_str(ret);
3332    sig
3333}
3334
3335/// Call `NativeBridge.<name>(args)`; `None` if the JVM is unavailable or the
3336/// call threw (the exception is cleared).
3337unsafe fn bridge_call<'l>(
3338    env: &mut JNIEnv<'l>,
3339    name: &str,
3340    args: &[JArg],
3341    ret: &str,
3342) -> Option<jni::objects::JValueOwned<'l>> {
3343    let mut strs = Vec::new();
3344    for a in args {
3345        if let JArg::S(s) = a {
3346            strs.push(ys_to_java(env, *s)?);
3347        }
3348    }
3349    let mut next_str = strs.iter();
3350    let mut vals: Vec<JValue> = Vec::with_capacity(args.len());
3351    for a in args {
3352        vals.push(match *a {
3353            JArg::S(_) => JValue::Object(next_str.next()?),
3354            JArg::D(d) => JValue::Double(d),
3355            JArg::F(f) => JValue::Float(f),
3356            JArg::I(i) => JValue::Int(i),
3357            JArg::Z(z) => JValue::Bool(z as u8),
3358        });
3359    }
3360    let sig = bridge_sig(args, ret);
3361    match env.call_static_method("dev/yog/NativeBridge", name, &sig, &vals) {
3362        Ok(v) => Some(v),
3363        Err(_) => {
3364            let _ = env.exception_clear();
3365            None
3366        }
3367    }
3368}
3369
3370unsafe fn bridge_bool(name: &str, args: &[JArg]) -> bool {
3371    let Some(mut env) = get_env() else {
3372        return false;
3373    };
3374    bridge_call(&mut env, name, args, "Z")
3375        .and_then(|v| v.z().ok())
3376        .unwrap_or(false)
3377}
3378
3379unsafe fn bridge_str(name: &str, args: &[JArg]) -> YogOwnedStr {
3380    let Some(mut env) = get_env() else {
3381        return YogOwnedStr::NONE;
3382    };
3383    match bridge_call(&mut env, name, args, "Ljava/lang/String;").and_then(|v| v.l().ok()) {
3384        Some(obj) => jstring_to_owned(&mut env, obj),
3385        None => YogOwnedStr::NONE,
3386    }
3387}
3388
3389fn vec_args(v: YogVec3) -> [JArg; 3] {
3390    [JArg::D(v.x), JArg::D(v.y), JArg::D(v.z)]
3391}
3392
3393fn pos_args(p: YogBlockPos) -> [JArg; 3] {
3394    [JArg::I(p.x), JArg::I(p.y), JArg::I(p.z)]
3395}
3396
3397unsafe extern "C" fn srv_entity_info(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
3398    bridge_str("entityInfo", &[JArg::S(uuid)])
3399}
3400
3401unsafe extern "C" fn srv_entities_in_box(
3402    _ctx: *mut c_void,
3403    dim: YogStr,
3404    min: YogVec3,
3405    max: YogVec3,
3406) -> YogOwnedStr {
3407    let [a, b, c] = vec_args(min);
3408    let [d, e, f] = vec_args(max);
3409    bridge_str("entitiesInBox", &[JArg::S(dim), a, b, c, d, e, f])
3410}
3411
3412unsafe extern "C" fn srv_raycast_block(
3413    _ctx: *mut c_void,
3414    dim: YogStr,
3415    from: YogVec3,
3416    to: YogVec3,
3417) -> YogOwnedStr {
3418    let [a, b, c] = vec_args(from);
3419    let [d, e, f] = vec_args(to);
3420    bridge_str("raycastBlock", &[JArg::S(dim), a, b, c, d, e, f])
3421}
3422
3423unsafe extern "C" fn srv_raycast_entity(
3424    _ctx: *mut c_void,
3425    dim: YogStr,
3426    from: YogVec3,
3427    to: YogVec3,
3428    exclude: YogStr,
3429) -> YogOwnedStr {
3430    let [a, b, c] = vec_args(from);
3431    let [d, e, f] = vec_args(to);
3432    bridge_str(
3433        "raycastEntity",
3434        &[JArg::S(dim), a, b, c, d, e, f, JArg::S(exclude)],
3435    )
3436}
3437
3438unsafe extern "C" fn srv_block_info(
3439    _ctx: *mut c_void,
3440    dim: YogStr,
3441    pos: YogBlockPos,
3442) -> YogOwnedStr {
3443    let [x, y, z] = pos_args(pos);
3444    bridge_str("blockInfo", &[JArg::S(dim), x, y, z])
3445}
3446
3447unsafe extern "C" fn srv_break_block(
3448    _ctx: *mut c_void,
3449    dim: YogStr,
3450    pos: YogBlockPos,
3451    drop: bool,
3452    breaker: YogStr,
3453) -> bool {
3454    let [x, y, z] = pos_args(pos);
3455    bridge_bool(
3456        "breakBlock",
3457        &[JArg::S(dim), x, y, z, JArg::Z(drop), JArg::S(breaker)],
3458    )
3459}
3460
3461unsafe extern "C" fn srv_place_block_from_slot(
3462    _ctx: *mut c_void,
3463    player: YogStr,
3464    slot: u32,
3465    dim: YogStr,
3466    pos: YogBlockPos,
3467) -> bool {
3468    let [x, y, z] = pos_args(pos);
3469    bridge_bool(
3470        "placeBlockFromSlot",
3471        &[JArg::S(player), JArg::I(slot as i32), JArg::S(dim), x, y, z],
3472    )
3473}
3474
3475unsafe extern "C" fn srv_bonemeal(_ctx: *mut c_void, dim: YogStr, pos: YogBlockPos) -> bool {
3476    let [x, y, z] = pos_args(pos);
3477    bridge_bool("bonemeal", &[JArg::S(dim), x, y, z])
3478}
3479
3480unsafe extern "C" fn srv_explode(
3481    _ctx: *mut c_void,
3482    dim: YogStr,
3483    pos: YogVec3,
3484    power: f32,
3485    fire: bool,
3486    source: YogStr,
3487) -> bool {
3488    let [x, y, z] = vec_args(pos);
3489    bridge_bool(
3490        "explode",
3491        &[
3492            JArg::S(dim),
3493            x,
3494            y,
3495            z,
3496            JArg::F(power),
3497            JArg::Z(fire),
3498            JArg::S(source),
3499        ],
3500    )
3501}
3502
3503unsafe extern "C" fn srv_tellraw(_ctx: *mut c_void, player: YogStr, json: YogStr) -> bool {
3504    bridge_bool("tellraw", &[JArg::S(player), JArg::S(json)])
3505}
3506
3507unsafe extern "C" fn srv_entity_damage(
3508    _ctx: *mut c_void,
3509    uuid: YogStr,
3510    amount: f32,
3511    damage_type: YogStr,
3512    attacker: YogStr,
3513) -> bool {
3514    bridge_bool(
3515        "entityDamage",
3516        &[
3517            JArg::S(uuid),
3518            JArg::F(amount),
3519            JArg::S(damage_type),
3520            JArg::S(attacker),
3521        ],
3522    )
3523}
3524
3525unsafe extern "C" fn srv_entity_set_fire_ticks(
3526    _ctx: *mut c_void,
3527    uuid: YogStr,
3528    ticks: i32,
3529) -> bool {
3530    bridge_bool("entitySetFireTicks", &[JArg::S(uuid), JArg::I(ticks)])
3531}
3532
3533unsafe extern "C" fn srv_player_add_xp(_ctx: *mut c_void, player: YogStr, amount: i32) -> bool {
3534    bridge_bool("playerAddXp", &[JArg::S(player), JArg::I(amount)])
3535}
3536
3537unsafe extern "C" fn srv_player_set_may_fly(
3538    _ctx: *mut c_void,
3539    player: YogStr,
3540    may_fly: bool,
3541) -> bool {
3542    bridge_bool("playerSetMayFly", &[JArg::S(player), JArg::Z(may_fly)])
3543}
3544
3545unsafe extern "C" fn srv_player_info(_ctx: *mut c_void, player: YogStr) -> YogOwnedStr {
3546    bridge_str("playerInfo", &[JArg::S(player)])
3547}
3548
3549unsafe extern "C" fn srv_spawn_item(
3550    _ctx: *mut c_void,
3551    dim: YogStr,
3552    pos: YogVec3,
3553    vel: YogVec3,
3554    item_id: YogStr,
3555    count: u32,
3556    snbt: YogStr,
3557) -> YogOwnedStr {
3558    let [a, b, c] = vec_args(pos);
3559    let [d, e, f] = vec_args(vel);
3560    bridge_str(
3561        "spawnItem",
3562        &[
3563            JArg::S(dim),
3564            a,
3565            b,
3566            c,
3567            d,
3568            e,
3569            f,
3570            JArg::S(item_id),
3571            JArg::I(count as i32),
3572            JArg::S(snbt),
3573        ],
3574    )
3575}
3576
3577unsafe extern "C" fn srv_item_entity_stack(_ctx: *mut c_void, uuid: YogStr) -> YogOwnedStr {
3578    bridge_str("itemEntityStack", &[JArg::S(uuid)])
3579}
3580
3581unsafe extern "C" fn srv_item_entity_set_stack(
3582    _ctx: *mut c_void,
3583    uuid: YogStr,
3584    item_id: YogStr,
3585    count: u32,
3586    snbt: YogStr,
3587) -> bool {
3588    bridge_bool(
3589        "itemEntitySetStack",
3590        &[
3591            JArg::S(uuid),
3592            JArg::S(item_id),
3593            JArg::I(count as i32),
3594            JArg::S(snbt),
3595        ],
3596    )
3597}
3598
3599// ── Table constructors ────────────────────────────────────────────────────────
3600
3601fn build_server_table() -> YogServer {
3602    YogServer {
3603        ctx: std::ptr::null_mut(),
3604        abi_version: ABI_VERSION,
3605        size: std::mem::size_of::<YogServer>() as u32,
3606        free_str: yog_free_str,
3607        broadcast: srv_broadcast,
3608        get_block: srv_get_block,
3609        set_block: srv_set_block,
3610        world_time: srv_world_time,
3611        set_time: srv_set_time,
3612        is_raining: srv_is_raining,
3613        set_weather: srv_set_weather,
3614        give_item: srv_give_item,
3615        player_teleport: srv_player_teleport,
3616        send_to_player: srv_send_to_player,
3617        send_to_server: srv_send_to_server,
3618        kick_player: srv_kick_player,
3619        set_gamemode: srv_set_gamemode,
3620        send_title: srv_send_title,
3621        send_actionbar: srv_send_actionbar,
3622        play_sound: srv_play_sound,
3623        play_sound_player: srv_play_sound_player,
3624        entity_teleport: srv_entity_teleport,
3625        entity_position: srv_entity_position,
3626        entity_rotation: srv_entity_rotation,
3627        entity_health: srv_entity_health,
3628        entity_set_health: srv_entity_set_health,
3629        entity_kill: srv_entity_kill,
3630        spawn_entity: srv_spawn_entity,
3631        entity_add_effect: srv_entity_add_effect,
3632        entity_remove_effect: srv_entity_remove_effect,
3633        entity_clear_effects: srv_entity_clear_effects,
3634        entity_velocity: srv_entity_velocity,
3635        entity_set_velocity: srv_entity_set_velocity,
3636        entity_add_velocity: srv_entity_add_velocity,
3637        has_item_tag: srv_has_item_tag,
3638        has_block_tag: srv_has_block_tag,
3639        drop_loot: srv_drop_loot,
3640        scoreboard_get: srv_scoreboard_get,
3641        scoreboard_set: srv_scoreboard_set,
3642        scoreboard_add: srv_scoreboard_add,
3643        bossbar_create: srv_bossbar_create,
3644        bossbar_remove: srv_bossbar_remove,
3645        bossbar_set_title: srv_bossbar_set_title,
3646        bossbar_set_progress: srv_bossbar_set_progress,
3647        bossbar_set_color: srv_bossbar_set_color,
3648        bossbar_add_player: srv_bossbar_add_player,
3649        bossbar_remove_player: srv_bossbar_remove_player,
3650        bossbar_set_visible: srv_bossbar_set_visible,
3651        game_dir: srv_game_dir,
3652        get_block_nbt: srv_get_block_nbt,
3653        set_block_nbt: srv_set_block_nbt,
3654        get_inventory_slot: srv_get_inventory_slot,
3655        set_inventory_slot: srv_set_inventory_slot,
3656        player_inventory: srv_player_inventory,
3657        player_set_slot: srv_player_set_slot,
3658        player_teleport_dim: srv_player_teleport_dim,
3659        entity_teleport_dim: srv_entity_teleport_dim,
3660        online_players: srv_online_players,
3661        world_entity_count: srv_world_entity_count,
3662        entity_get_nbt: srv_entity_get_nbt,
3663        entity_set_nbt: srv_entity_set_nbt,
3664        spawn_particles: srv_spawn_particles,
3665        entity_attribute_get: srv_entity_attribute_get,
3666        entity_attribute_set: srv_entity_attribute_set,
3667        get_held_item_nbt: srv_get_held_item_nbt,
3668        set_held_item_nbt: srv_set_held_item_nbt,
3669        get_offhand_item_nbt: srv_get_offhand_item_nbt,
3670        set_offhand_item_nbt: srv_set_offhand_item_nbt,
3671        get_slot_item: srv_get_slot_item,
3672        set_slot_item: srv_set_slot_item,
3673        entity_info: srv_entity_info,
3674        entities_in_box: srv_entities_in_box,
3675        raycast_block: srv_raycast_block,
3676        raycast_entity: srv_raycast_entity,
3677        block_info: srv_block_info,
3678        break_block: srv_break_block,
3679        place_block_from_slot: srv_place_block_from_slot,
3680        bonemeal: srv_bonemeal,
3681        explode: srv_explode,
3682        tellraw: srv_tellraw,
3683        entity_damage: srv_entity_damage,
3684        entity_set_fire_ticks: srv_entity_set_fire_ticks,
3685        player_add_xp: srv_player_add_xp,
3686        player_set_may_fly: srv_player_set_may_fly,
3687        player_info: srv_player_info,
3688        spawn_item: srv_spawn_item,
3689        item_entity_stack: srv_item_entity_stack,
3690        item_entity_set_stack: srv_item_entity_set_stack,
3691    }
3692}
3693
3694// ── Inter-mod communication ──────────────────────────────────────────────────
3695
3696unsafe extern "C" fn interop_export_impl(
3697    _ctx: *mut c_void,
3698    mod_id: YogStr,
3699    symbol: YogStr,
3700    ptr: *const c_void,
3701) {
3702    let mod_id = mod_id.as_str();
3703    let sym = symbol.as_str();
3704    let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3705    registry
3706        .lock()
3707        .expect("interop symbols lock poisoned")
3708        .entry(mod_id.to_string())
3709        .or_default()
3710        .insert(sym.to_string(), ptr as usize);
3711}
3712
3713unsafe extern "C" fn interop_import_impl(
3714    _ctx: *mut c_void,
3715    mod_id: YogStr,
3716    symbol: YogStr,
3717) -> *const c_void {
3718    let mod_id = mod_id.as_str();
3719    let sym = symbol.as_str();
3720    let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3721    registry
3722        .lock()
3723        .expect("interop symbols lock poisoned")
3724        .get(mod_id)
3725        .and_then(|m: &HashMap<String, usize>| m.get(sym))
3726        .map(|&ptr| ptr as *const c_void)
3727        .unwrap_or(std::ptr::null())
3728}
3729
3730fn build_api_table(ctx: *const RwLock<RuntimeHandlers>, server: *const YogServer) -> YogApi {
3731    YogApi {
3732        abi_version: ABI_VERSION,
3733        size: std::mem::size_of::<YogApi>() as u32,
3734        ctx: ctx as *mut c_void,
3735        server,
3736        on_block_break: api_on_block_break,
3737        on_chat: api_on_chat,
3738        on_player_join: api_on_player_join,
3739        on_player_leave: api_on_player_leave,
3740        on_use_item: api_on_use_item,
3741        on_use_block: api_on_use_block,
3742        on_attack_entity: api_on_attack_entity,
3743        on_entity_damage: api_on_entity_damage,
3744        on_entity_death: api_on_entity_death,
3745        on_entity_spawn: api_on_entity_spawn,
3746        on_player_place_block: api_on_player_place_block,
3747        on_player_death: api_on_player_death,
3748        on_player_respawn: api_on_player_respawn,
3749        on_advancement: api_on_advancement,
3750        on_entity_interact: api_on_entity_interact,
3751        on_item_craft: api_on_item_craft,
3752        on_explosion: api_on_explosion,
3753        on_item_pickup: api_on_item_pickup,
3754        on_player_move: api_on_player_move,
3755        on_container_open: api_on_container_open,
3756        on_container_close: api_on_container_close,
3757        on_projectile_hit: api_on_projectile_hit,
3758        on_server_tick: api_on_server_tick,
3759        on_server_started: api_on_server_started,
3760        on_server_stopping: api_on_server_stopping,
3761        on_packet: api_on_packet,
3762        on_client_packet: api_on_client_packet,
3763        register_command: api_register_command,
3764        register_typed_command: api_register_typed_command,
3765        register_recipe_json: api_register_recipe_json,
3766        register_item: api_register_item,
3767        register_block: api_register_block,
3768        schedule_once: api_schedule_once,
3769        schedule_repeating: api_schedule_repeating,
3770        on_client_tick: api_on_client_tick,
3771        on_hud_render: api_on_hud_render,
3772        on_key_press: api_on_key_press,
3773        on_screen_open: api_on_screen_open,
3774        on_screen_close: api_on_screen_close,
3775        on_world_render: api_on_world_render,
3776        register_startup_grant: api_register_startup_grant,
3777        register_book: api_register_book,
3778        register_ui: api_register_ui,
3779        on_ui_render: api_on_ui_render,
3780        register_menu_entry: api_register_menu_entry,
3781        mods_list: api_mods_list,
3782        free_str: yog_free_str,
3783        ui_open: api_ui_open,
3784        register_inventory: api_register_inventory,
3785        interop_export: interop_export_impl,
3786        interop_import: interop_import_impl,
3787        register_dimension_json: api_register_dimension_json,
3788        register_chunk_generator: api_register_chunk_generator,
3789        ui_close: api_ui_close,
3790        ui_consume_event: api_ui_consume_event,
3791        translate: api_translate,
3792        ui_open_flags: client_api::api_ui_open_flags,
3793        client_play_sound: client_api::api_client_play_sound,
3794        client_stop_sound: client_api::api_client_stop_sound,
3795        client_held_item: client_api::api_client_held_item,
3796        client_key_down: client_api::api_client_key_down,
3797    }
3798}
3799
3800// ── Mod loading ───────────────────────────────────────────────────────────────
3801
3802fn platform_tag() -> String {
3803    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
3804}
3805
3806type AbiVersionFn = unsafe extern "C" fn() -> u32;
3807/// Second arg is a null-terminated C string: the mod's `id` from its manifest.
3808type RegisterFn = unsafe extern "C" fn(*const YogApi, *const std::os::raw::c_char);
3809
3810fn load_mods(dir: &Path, api: &YogApi) {
3811    let entries = match std::fs::read_dir(dir) {
3812        Ok(e) => e,
3813        Err(_) => {
3814            yog_logging::info!("no mods directory at {} — none loaded", dir.display());
3815            return;
3816        }
3817    };
3818
3819    // First pass: collect (mod_id, dependencies, archive_path)
3820    struct ModMeta {
3821        id: String,
3822        deps: Vec<String>,
3823        yog_path: PathBuf,
3824    }
3825    let mut metas: Vec<ModMeta> = Vec::new();
3826    for entry in entries.flatten() {
3827        let path = entry.path();
3828        if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3829            continue;
3830        }
3831        let info = read_mod_info(&path);
3832        let deps = read_mod_deps(&path);
3833        metas.push(ModMeta {
3834            id: info[0].clone(),
3835            deps,
3836            yog_path: path,
3837        });
3838    }
3839
3840    // Topological sort by dependencies (Kahn's algorithm)
3841    let ids: Vec<String> = metas.iter().map(|m| m.id.clone()).collect();
3842    let deps_list: Vec<Vec<String>> = metas.iter().map(|m| m.deps.clone()).collect();
3843    let sorted = match topo_sort_mods(&ids, &deps_list) {
3844        Some(v) => v,
3845        None => {
3846            yog_logging::error!("circular dependency detected — loading in file order");
3847            (0..metas.len()).collect()
3848        }
3849    };
3850
3851    let mut loaded: Vec<LoadedModule> = Vec::new();
3852    for idx in sorted {
3853        let meta = &metas[idx];
3854        let lib_path = match extract_yog(&meta.yog_path) {
3855            Some(p) => p,
3856            None => {
3857                yog_logging::error!(
3858                    "no native for {} in {}",
3859                    platform_tag(),
3860                    meta.yog_path.display()
3861                );
3862                continue;
3863            }
3864        };
3865        if let Some(module) = load_mod_lib(&lib_path, api, &meta.id) {
3866            loaded.push(module);
3867            MOD_INFOS
3868                .lock()
3869                .expect("mod infos lock poisoned")
3870                .push(read_mod_info(&meta.yog_path));
3871        }
3872    }
3873    yog_logging::info!("loaded {} mod(s) from {}", loaded.len(), dir.display());
3874
3875    // Final import resolution pass — after all mods loaded, each mod's pending
3876    // imports can be resolved against the now-complete interop table.
3877    resolve_all_imports(api, &loaded);
3878}
3879
3880/// After all mods loaded, call `__yog_resolve_imports_final` on each library
3881/// to resolve any imports that weren't satisfied during initial registration.
3882fn resolve_all_imports(api: &YogApi, loaded: &[LoadedModule]) {
3883    for module in loaded {
3884        module.with_library(|lib| unsafe {
3885            type ResolveFn = unsafe extern "C" fn(*const YogApi);
3886            if let Ok(resolve) = lib.get::<ResolveFn>(b"__yog_resolve_imports_final") {
3887                resolve(api as *const YogApi);
3888            }
3889        });
3890    }
3891}
3892
3893/// Kahn's algorithm — returns indices in dependency order, or None on cycle.
3894fn topo_sort_mods(ids: &[String], deps_list: &[Vec<String>]) -> Option<Vec<usize>> {
3895    let n = ids.len();
3896    let name_to_idx: HashMap<&str, usize> = ids
3897        .iter()
3898        .enumerate()
3899        .map(|(i, id)| (id.as_str(), i))
3900        .collect();
3901    let mut in_degree = vec![0u32; n];
3902    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
3903    for (i, deps) in deps_list.iter().enumerate() {
3904        for dep in deps {
3905            if let Some(&j) = name_to_idx.get(dep.as_str()) {
3906                adj[j].push(i);
3907                in_degree[i] += 1;
3908            }
3909        }
3910    }
3911    let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
3912    let mut order = Vec::with_capacity(n);
3913    while let Some(u) = queue.pop() {
3914        order.push(u);
3915        for &v in &adj[u] {
3916            in_degree[v] -= 1;
3917            if in_degree[v] == 0 {
3918                queue.push(v);
3919            }
3920        }
3921    }
3922    if order.len() == n {
3923        Some(order)
3924    } else {
3925        None
3926    }
3927}
3928
3929/// Loads `path` as a fresh generation of `mod_id` via the shared
3930/// `HotReloader`, validates its ABI, and calls its `yog_mod_register` —
3931/// tagging every handler it registers with the returned `LoadedModule` (see
3932/// `current_registration()`). On any failure the module (if it got as far
3933/// as being tracked by the `HotReloader`) is retired immediately: nothing
3934/// can be executing inside a library that never successfully registered,
3935/// so this always hard-unloads right away rather than lingering.
3936fn load_mod_lib(path: &Path, api: &YogApi, mod_id: &str) -> Option<LoadedModule> {
3937    let module = match unsafe { hot_reloader().load_initial(mod_id, path) } {
3938        Ok(m) => m,
3939        Err(e) => {
3940            yog_logging::error!("failed to load {}: {}", path.display(), e);
3941            return None;
3942        }
3943    };
3944
3945    let abi = module.with_library(|lib| unsafe {
3946        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
3947        Some(abi())
3948    });
3949    match abi.flatten() {
3950        Some(v) if v == ABI_VERSION => {}
3951        Some(v) => {
3952            yog_logging::error!(
3953                "{}: ABI {} incompatible with runtime ABI {}",
3954                path.display(),
3955                v,
3956                ABI_VERSION
3957            );
3958            module.retire(|| {});
3959            return None;
3960        }
3961        None => {
3962            yog_logging::error!("{} is not a Yog mod (no yog_abi_version)", path.display());
3963            module.retire(|| {});
3964            return None;
3965        }
3966    }
3967
3968    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
3969        yog_logging::error!("{}: {}", path.display(), e);
3970        module.retire(|| {});
3971        return None;
3972    }
3973
3974    Some(module)
3975}
3976
3977/// Calls a loaded module's `yog_mod_register`, tagging everything it
3978/// registers with `module` via `CURRENT_REGISTRATION` for the duration of
3979/// the call — used for both a mod's initial load and a later hot-reload.
3980fn invoke_mod_register(module: &LoadedModule, api: &YogApi, mod_id: &str) -> Result<(), String> {
3981    module
3982        .with_library(|lib| unsafe {
3983            let register: Symbol<RegisterFn> = lib
3984                .get(b"yog_mod_register")
3985                .map_err(|_| "missing yog_mod_register".to_string())?;
3986            let mod_id_c = std::ffi::CString::new(mod_id).unwrap();
3987            *CURRENT_REGISTRATION.lock().unwrap() = Some(module.clone());
3988            register(api as *const YogApi, mod_id_c.as_ptr());
3989            *CURRENT_REGISTRATION.lock().unwrap() = None;
3990            Ok(())
3991        })
3992        .unwrap_or_else(|| Err("module was unloaded before registration could run".to_string()))
3993}
3994
3995/// Metadata for a mod file: [id, name, version, authors, description,
3996/// name_key, description_key].
3997/// For .yog archives this comes from the bundled yog.toml; bare native libs
3998/// fall back to the file stem.
3999fn read_mod_info(path: &Path) -> [String; 7] {
4000    let stem = path
4001        .file_stem()
4002        .map(|s| s.to_string_lossy().into_owned())
4003        .unwrap_or_default();
4004    let mut info = [
4005        stem.clone(),
4006        stem,
4007        String::new(),
4008        String::new(),
4009        String::new(),
4010        String::new(),
4011        String::new(),
4012    ];
4013    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
4014        return info;
4015    }
4016    let Some(text) = (|| {
4017        let file = std::fs::File::open(path).ok()?;
4018        let mut archive = zip::ZipArchive::new(file).ok()?;
4019        let mut entry = archive.by_name("yog.toml").ok()?;
4020        let mut text = String::new();
4021        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
4022        Some(text)
4023    })() else {
4024        return info;
4025    };
4026    // Minimal parse — enough for id/name/version/description/authors without
4027    // pulling in a TOML dependency. Source manifests keep these under [mod];
4028    // the packaged manifest (written by yog-cli) has them at top level, so
4029    // keys before any section header count too.
4030    let mut in_mod = true;
4031    for line in text.lines() {
4032        let line = line.trim();
4033        if line.starts_with('[') {
4034            in_mod = line == "[mod]";
4035            continue;
4036        }
4037        if !in_mod {
4038            continue;
4039        }
4040        let Some((key, value)) = line.split_once('=') else {
4041            continue;
4042        };
4043        let key = key.trim();
4044        let value = value.trim();
4045        let unquote = |v: &str| v.trim().trim_matches('"').to_string();
4046        match key {
4047            "id" => info[0] = tsv_clean(&unquote(value)),
4048            "name" => info[1] = tsv_clean(&unquote(value)),
4049            "version" => info[2] = tsv_clean(&unquote(value)),
4050            "description" => info[4] = tsv_clean(&unquote(value)),
4051            "name_key" => info[5] = unquote(value),
4052            "description_key" => info[6] = unquote(value),
4053            "authors" => {
4054                let list = value.trim_start_matches('[').trim_end_matches(']');
4055                let authors: Vec<String> = list
4056                    .split(',')
4057                    .map(unquote)
4058                    .filter(|a| !a.is_empty())
4059                    .collect();
4060                info[3] = tsv_clean(&authors.join(", "));
4061            }
4062            _ => {}
4063        }
4064    }
4065    info
4066}
4067
4068/// Parse `[dependencies]` section from yog.toml inside a .yog archive.
4069fn read_mod_deps(path: &Path) -> Vec<String> {
4070    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
4071        return Vec::new();
4072    }
4073    let text = (|| {
4074        let file = std::fs::File::open(path).ok()?;
4075        let mut archive = zip::ZipArchive::new(file).ok()?;
4076        let mut entry = archive.by_name("yog.toml").ok()?;
4077        let mut text = String::new();
4078        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
4079        Some(text)
4080    })();
4081    let Some(text) = text else { return Vec::new() };
4082    let mut deps = Vec::new();
4083    let mut in_deps = false;
4084    for line in text.lines() {
4085        let line = line.trim();
4086        if line.starts_with('[') {
4087            in_deps = line == "[dependencies]";
4088            continue;
4089        }
4090        if !in_deps {
4091            continue;
4092        }
4093        // `mod_id = "1.0"` or `mod_id = "*"` — we only care about the key (mod_id)
4094        if let Some((key, _)) = line.split_once('=') {
4095            deps.push(key.trim().to_string());
4096        }
4097    }
4098    deps
4099}
4100
4101fn extract_yog(path: &Path) -> Option<PathBuf> {
4102    let file = std::fs::File::open(path).ok()?;
4103    let mut archive = zip::ZipArchive::new(file).ok()?;
4104    let prefix = format!("natives/{}/", platform_tag());
4105    let mut entry_name = None;
4106    for i in 0..archive.len() {
4107        let f = archive.by_index(i).ok()?;
4108        let name = f.name().ok()?;
4109        if name.starts_with(&prefix) && !name.ends_with('/') {
4110            entry_name = Some(name.to_string());
4111            break;
4112        }
4113    }
4114    let entry_name = entry_name?;
4115    let ext = Path::new(&entry_name)
4116        .extension()
4117        .and_then(|e| e.to_str())
4118        .unwrap_or("bin");
4119    let stem = path.file_stem()?.to_string_lossy().into_owned();
4120    // A fresh name per extraction: a hot reload must never truncate the
4121    // library the game still has mapped, and `dlopen` of an already-loaded
4122    // path would just hand back the old module.
4123    static EXTRACTIONS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
4124    let n = EXTRACTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
4125    let out =
4126        std::env::temp_dir().join(format!("yog-{}-{}-{}.{}", stem, std::process::id(), n, ext));
4127    let mut entry = archive.by_name(&entry_name).ok()?;
4128    let mut out_file = std::fs::File::create(&out).ok()?;
4129    std::io::copy(&mut entry, &mut out_file).ok()?;
4130    Some(out)
4131}
4132
4133// ── Dispatcher helpers ────────────────────────────────────────────────────────
4134
4135fn srv_ptr() -> *const YogServer {
4136    SERVER.get().expect("yog: SERVER not initialised") as *const YogServer
4137}
4138
4139// ── JNI entry points ──────────────────────────────────────────────────────────
4140
4141#[no_mangle]
4142pub extern "system" fn Java_dev_yog_NativeBridge_nativeInit<'l>(
4143    mut env: JNIEnv<'l>,
4144    _class: JClass<'l>,
4145    mods_dir: JString<'l>,
4146) {
4147    if let Ok(vm) = env.get_java_vm() {
4148        let _ = JAVA_VM.set(vm);
4149    }
4150
4151    let dir = env
4152        .get_string(&mods_dir)
4153        .map(String::from)
4154        .unwrap_or_default();
4155
4156    // Build YogServer and store in static (gets a stable address).
4157    let _ = SERVER.set(build_server_table());
4158    let server_ptr = SERVER.get().unwrap() as *const YogServer;
4159
4160    // Publish HANDLERS *before* any mod registers — its address is then
4161    // `'static`-stable for the runtime's entire lifetime, unlike the old
4162    // design (a temporary heap `Box` moved into `HANDLERS` only after
4163    // `nativeInit` returned, silently invalidating the `ctx` pointer any
4164    // later re-registration — e.g. a hot-reload — would have needed).
4165    let handlers_lock = HANDLERS.get_or_init(|| RwLock::new(RuntimeHandlers::new()));
4166    let handlers_ptr = handlers_lock as *const RwLock<RuntimeHandlers>;
4167
4168    let api: &'static YogApi = API_TABLE.get_or_init(|| build_api_table(handlers_ptr, server_ptr));
4169
4170    let _ = HOT_RELOADER.get_or_init(|| HotReloader::new(RuntimeModuleRegistry));
4171
4172    guard("mod loading", || {
4173        load_mods(Path::new(&dir), api);
4174    });
4175
4176    control_socket::start_if_requested();
4177
4178    yog_logging::info!("runtime initialised — the gate is open.");
4179}
4180
4181#[no_mangle]
4182pub extern "system" fn Java_dev_yog_NativeBridge_nativeHotReload<'l>(
4183    mut env: JNIEnv<'l>,
4184    _class: JClass<'l>,
4185    mod_id: JString<'l>,
4186    new_yog_path: JString<'l>,
4187) -> jni::sys::jboolean {
4188    let Ok(mod_id) = env.get_string(&mod_id).map(String::from) else {
4189        return 0;
4190    };
4191    let Ok(yog_path) = env.get_string(&new_yog_path).map(String::from) else {
4192        return 0;
4193    };
4194    let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4195        trigger_hot_reload(&mod_id, Path::new(&yog_path))
4196    }))
4197    .unwrap_or(false);
4198    ok as jni::sys::jboolean
4199}
4200
4201/// Rebuilds and re-registers `mod_id` from a freshly built `.yog` at
4202/// `new_yog_path`: extracts the current platform's native, loads it as a
4203/// new generation via the shared `HotReloader` (which retires the previous
4204/// generation per its hybrid soft/hard-unload policy — hard-unloaded right
4205/// away if nothing's mid-call, deferred otherwise), then calls its
4206/// `yog_mod_register` again so its handlers get tagged under the new
4207/// generation. How this actually gets triggered — a keybind, a file-watch,
4208/// an IDE-driven socket — is a separate, later concern; this only needs to
4209/// work correctly once called.
4210fn trigger_hot_reload(mod_id: &str, new_yog_path: &Path) -> bool {
4211    let Some(native_path) = extract_yog(new_yog_path) else {
4212        yog_logging::error!(
4213            "hot-reload {}: no native for {} in {}",
4214            mod_id,
4215            platform_tag(),
4216            new_yog_path.display()
4217        );
4218        return false;
4219    };
4220
4221    let api = API_TABLE.get().expect("yog: nativeInit not called yet");
4222
4223    let module = match unsafe { hot_reloader().reload(mod_id, &native_path) } {
4224        Ok(m) => m,
4225        Err(e) => {
4226            yog_logging::error!(
4227                "hot-reload {}: failed to load {}: {}",
4228                mod_id,
4229                native_path.display(),
4230                e
4231            );
4232            return false;
4233        }
4234    };
4235
4236    let abi = module.with_library(|lib| unsafe {
4237        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
4238        Some(abi())
4239    });
4240    match abi.flatten() {
4241        Some(v) if v == ABI_VERSION => {}
4242        other => {
4243            yog_logging::error!(
4244                "hot-reload {}: ABI {:?} incompatible with runtime ABI {} — mod has no active handlers until a compatible reload succeeds",
4245                mod_id,
4246                other,
4247                ABI_VERSION
4248            );
4249            return false;
4250        }
4251    }
4252
4253    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
4254        yog_logging::error!("hot-reload {}: {}", mod_id, e);
4255        return false;
4256    }
4257
4258    yog_logging::info!("hot-reloaded mod {}", mod_id);
4259    true
4260}
4261
4262#[no_mangle]
4263pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreak<'l>(
4264    mut env: JNIEnv<'l>,
4265    _class: JClass<'l>,
4266    player: JString<'l>,
4267    block: JString<'l>,
4268    x: jint,
4269    y: jint,
4270    z: jint,
4271    dimension: JString<'l>,
4272) {
4273    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
4274    let ev = yog_abi::YogBlockBreakEvent {
4275        player: YogStr::from_str(&p),
4276        block: YogStr::from_str(&b),
4277        pos: YogBlockPos { x, y, z },
4278        dimension: YogStr::from_str(&d),
4279    };
4280    let srv = srv_ptr();
4281    guard("on_block_break", || {
4282        for (module, ud, f) in &handlers().block_break {
4283            if module.is_retiring() {
4284                continue;
4285            }
4286            let Some(_call) = module.enter() else {
4287                continue;
4288            };
4289            unsafe { f(*ud, srv, &ev, 1) };
4290        }
4291    });
4292}
4293
4294#[no_mangle]
4295pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChat<'l>(
4296    mut env: JNIEnv<'l>,
4297    _class: JClass<'l>,
4298    player: JString<'l>,
4299    message: JString<'l>,
4300    dimension: JString<'l>,
4301) {
4302    let (p, m, d) = (
4303        jstr!(env, player),
4304        jstr!(env, message),
4305        jstr!(env, dimension),
4306    );
4307    let ev = yog_abi::YogChatEvent {
4308        player: YogStr::from_str(&p),
4309        message: YogStr::from_str(&m),
4310        dimension: YogStr::from_str(&d),
4311    };
4312    let srv = srv_ptr();
4313    guard("on_chat", || {
4314        for (module, ud, f) in &handlers().chat {
4315            if module.is_retiring() {
4316                continue;
4317            }
4318            let Some(_call) = module.enter() else {
4319                continue;
4320            };
4321            unsafe { f(*ud, srv, &ev, 1) };
4322        }
4323    });
4324}
4325
4326#[no_mangle]
4327pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerJoin<'l>(
4328    mut env: JNIEnv<'l>,
4329    _class: JClass<'l>,
4330    player: JString<'l>,
4331    uuid: JString<'l>,
4332    dimension: JString<'l>,
4333) {
4334    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4335    let ev = yog_abi::YogPlayerEvent {
4336        player: YogStr::from_str(&p),
4337        uuid: YogStr::from_str(&u),
4338        dimension: YogStr::from_str(&d),
4339    };
4340    let srv = srv_ptr();
4341    guard("on_player_join", || {
4342        for (module, ud, f) in &handlers().player_join {
4343            if module.is_retiring() {
4344                continue;
4345            }
4346            let Some(_call) = module.enter() else {
4347                continue;
4348            };
4349            unsafe { f(*ud, srv, &ev, 1) };
4350        }
4351    });
4352    // Queue startup grants: giving items directly inside the join callback
4353    // fails for the host of a freshly created world (player not fully in the
4354    // world yet), so grants are processed a few server ticks later.
4355    let h = handlers();
4356    if !h.startup_grants.is_empty() {
4357        h.pending_grants
4358            .lock()
4359            .expect("pending_grants poisoned")
4360            .push((p, u, 0));
4361    }
4362}
4363
4364/// Try to fulfil pending startup grants. Called each server tick; a grant is
4365/// only marked as given (and persisted) after `give_item` actually succeeds.
4366fn process_pending_grants() {
4367    let h = handlers();
4368    let mut pending = match h.pending_grants.try_lock() {
4369        Ok(g) => g,
4370        Err(_) => return,
4371    };
4372    if pending.is_empty() {
4373        return;
4374    }
4375    // Wait a couple of ticks after join before the first attempt.
4376    const FIRST_TRY_TICK: u32 = 2;
4377    // Give up after 30 seconds — the player probably left.
4378    const MAX_TICKS: u32 = 600;
4379
4380    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
4381    let mut still_pending = Vec::new();
4382    let mut any_new = false;
4383
4384    for (p, u, ticks) in pending.drain(..) {
4385        if ticks < FIRST_TRY_TICK {
4386            still_pending.push((p, u, ticks + 1));
4387            continue;
4388        }
4389        let mut all_ok = true;
4390        for sg in &h.startup_grants {
4391            let key = format!("{}::{}", u, sg.id);
4392            if granted.contains_key(&key) {
4393                continue;
4394            }
4395            let mut ok = true;
4396            for item_id in &sg.items {
4397                ok &= unsafe {
4398                    srv_give_item(
4399                        std::ptr::null_mut(),
4400                        YogStr::from_str(&p),
4401                        YogStr::from_str(item_id),
4402                        1,
4403                    )
4404                };
4405            }
4406            if let Some(_book) = &sg.book {
4407                ok &= unsafe {
4408                    srv_give_item(
4409                        std::ptr::null_mut(),
4410                        YogStr::from_str(&p),
4411                        YogStr::from_str("minecraft:written_book"),
4412                        1,
4413                    )
4414                };
4415            }
4416            if ok {
4417                yog_logging::info!("startup grant {} given to {}", sg.id, p);
4418                granted.insert(key, true);
4419                any_new = true;
4420            } else {
4421                all_ok = false;
4422            }
4423        }
4424        if !all_ok && ticks < MAX_TICKS {
4425            still_pending.push((p, u, ticks + 1));
4426        }
4427    }
4428    *pending = still_pending;
4429    if any_new {
4430        save_startup_granted(&granted);
4431    }
4432}
4433
4434#[no_mangle]
4435pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerLeave<'l>(
4436    mut env: JNIEnv<'l>,
4437    _class: JClass<'l>,
4438    player: JString<'l>,
4439    uuid: JString<'l>,
4440    dimension: JString<'l>,
4441) {
4442    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4443    let ev = yog_abi::YogPlayerEvent {
4444        player: YogStr::from_str(&p),
4445        uuid: YogStr::from_str(&u),
4446        dimension: YogStr::from_str(&d),
4447    };
4448    let srv = srv_ptr();
4449    guard("on_player_leave", || {
4450        for (module, ud, f) in &handlers().player_leave {
4451            if module.is_retiring() {
4452                continue;
4453            }
4454            let Some(_call) = module.enter() else {
4455                continue;
4456            };
4457            unsafe { f(*ud, srv, &ev, 1) };
4458        }
4459    });
4460}
4461
4462#[no_mangle]
4463pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItem<'l>(
4464    mut env: JNIEnv<'l>,
4465    _class: JClass<'l>,
4466    player: JString<'l>,
4467    item: JString<'l>,
4468    sneaking: jni::sys::jboolean,
4469    dimension: JString<'l>,
4470) {
4471    let (p, i, d) = (jstr!(env, player), jstr!(env, item), jstr!(env, dimension));
4472    let ev = yog_abi::YogUseItemEvent {
4473        player: YogStr::from_str(&p),
4474        item: YogStr::from_str(&i),
4475        sneaking: sneaking != 0,
4476        dimension: YogStr::from_str(&d),
4477    };
4478    let srv = srv_ptr();
4479    guard("on_use_item", || {
4480        for (module, ud, f) in &handlers().use_item {
4481            if module.is_retiring() {
4482                continue;
4483            }
4484            let Some(_call) = module.enter() else {
4485                continue;
4486            };
4487            unsafe { f(*ud, srv, &ev, 1) };
4488        }
4489    });
4490}
4491
4492#[no_mangle]
4493pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItemPre<'l>(
4494    mut env: JNIEnv<'l>,
4495    _class: JClass<'l>,
4496    player: JString<'l>,
4497    item: JString<'l>,
4498    sneaking: jni::sys::jboolean,
4499    dimension: JString<'l>,
4500) -> jni::sys::jboolean {
4501    let h = handlers();
4502    if h.use_item.is_empty() {
4503        return 1;
4504    }
4505    let p = match env.get_string(&player) {
4506        Ok(s) => String::from(s),
4507        Err(_) => return 1,
4508    };
4509    let i = match env.get_string(&item) {
4510        Ok(s) => String::from(s),
4511        Err(_) => return 1,
4512    };
4513    let d = match env.get_string(&dimension) {
4514        Ok(s) => String::from(s),
4515        Err(_) => return 1,
4516    };
4517    let ev = yog_abi::YogUseItemEvent {
4518        player: YogStr::from_str(&p),
4519        item: YogStr::from_str(&i),
4520        sneaking: sneaking != 0,
4521        dimension: YogStr::from_str(&d),
4522    };
4523    let srv = srv_ptr();
4524    let mut allow = true;
4525    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4526        for (module, ud, f) in &h.use_item {
4527            if module.is_retiring() {
4528                continue;
4529            }
4530            let Some(_call) = module.enter() else {
4531                continue;
4532            };
4533            if !unsafe { f(*ud, srv, &ev, 0) } {
4534                allow = false;
4535                break;
4536            }
4537        }
4538    }))
4539    .ok();
4540    allow as jni::sys::jboolean
4541}
4542
4543#[no_mangle]
4544pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlock<'l>(
4545    mut env: JNIEnv<'l>,
4546    _class: JClass<'l>,
4547    player: JString<'l>,
4548    block: JString<'l>,
4549    x: jint,
4550    y: jint,
4551    z: jint,
4552    dimension: JString<'l>,
4553) {
4554    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
4555    let ev = yog_abi::YogUseBlockEvent {
4556        player: YogStr::from_str(&p),
4557        block: YogStr::from_str(&b),
4558        pos: YogBlockPos { x, y, z },
4559        dimension: YogStr::from_str(&d),
4560    };
4561    let srv = srv_ptr();
4562    guard("on_use_block", || {
4563        for (module, ud, f) in &handlers().use_block {
4564            if module.is_retiring() {
4565                continue;
4566            }
4567            let Some(_call) = module.enter() else {
4568                continue;
4569            };
4570            unsafe { f(*ud, srv, &ev, 1) };
4571        }
4572    });
4573}
4574
4575#[no_mangle]
4576pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlockPre<'l>(
4577    mut env: JNIEnv<'l>,
4578    _class: JClass<'l>,
4579    player: JString<'l>,
4580    block: JString<'l>,
4581    x: jint,
4582    y: jint,
4583    z: jint,
4584    dimension: JString<'l>,
4585) -> jni::sys::jboolean {
4586    let h = handlers();
4587    if h.use_block.is_empty() {
4588        return 1;
4589    }
4590    let p = match env.get_string(&player) {
4591        Ok(s) => String::from(s),
4592        Err(_) => return 1,
4593    };
4594    let b = match env.get_string(&block) {
4595        Ok(s) => String::from(s),
4596        Err(_) => return 1,
4597    };
4598    let d = match env.get_string(&dimension) {
4599        Ok(s) => String::from(s),
4600        Err(_) => return 1,
4601    };
4602    let ev = yog_abi::YogUseBlockEvent {
4603        player: YogStr::from_str(&p),
4604        block: YogStr::from_str(&b),
4605        pos: YogBlockPos { x, y, z },
4606        dimension: YogStr::from_str(&d),
4607    };
4608    let srv = srv_ptr();
4609    let mut allow = true;
4610    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4611        for (module, ud, f) in &h.use_block {
4612            if module.is_retiring() {
4613                continue;
4614            }
4615            let Some(_call) = module.enter() else {
4616                continue;
4617            };
4618            if !unsafe { f(*ud, srv, &ev, 0) } {
4619                allow = false;
4620                break;
4621            }
4622        }
4623    }))
4624    .ok();
4625    allow as jni::sys::jboolean
4626}
4627
4628#[no_mangle]
4629pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAttackEntity<'l>(
4630    mut env: JNIEnv<'l>,
4631    _class: JClass<'l>,
4632    player: JString<'l>,
4633    target_type: JString<'l>,
4634    target_uuid: JString<'l>,
4635    dimension: JString<'l>,
4636) {
4637    let (p, tt, tu, d) = (
4638        jstr!(env, player),
4639        jstr!(env, target_type),
4640        jstr!(env, target_uuid),
4641        jstr!(env, dimension),
4642    );
4643    let ev = yog_abi::YogAttackEntityEvent {
4644        player: YogStr::from_str(&p),
4645        target_type: YogStr::from_str(&tt),
4646        target_uuid: YogStr::from_str(&tu),
4647        dimension: YogStr::from_str(&d),
4648    };
4649    let srv = srv_ptr();
4650    guard("on_attack_entity", || {
4651        for (module, ud, f) in &handlers().attack_entity {
4652            if module.is_retiring() {
4653                continue;
4654            }
4655            let Some(_call) = module.enter() else {
4656                continue;
4657            };
4658            unsafe { f(*ud, srv, &ev, 1) };
4659        }
4660    });
4661}
4662
4663#[no_mangle]
4664pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamage<'l>(
4665    mut env: JNIEnv<'l>,
4666    _class: JClass<'l>,
4667    entity_type: JString<'l>,
4668    uuid: JString<'l>,
4669    amount: jfloat,
4670    source: JString<'l>,
4671    dimension: JString<'l>,
4672) {
4673    let (et, u, s, d) = (
4674        jstr!(env, entity_type),
4675        jstr!(env, uuid),
4676        jstr!(env, source),
4677        jstr!(env, dimension),
4678    );
4679    let ev = yog_abi::YogEntityDamageEvent {
4680        entity_type: YogStr::from_str(&et),
4681        uuid: YogStr::from_str(&u),
4682        amount,
4683        source: YogStr::from_str(&s),
4684        dimension: YogStr::from_str(&d),
4685    };
4686    let srv = srv_ptr();
4687    guard("on_entity_damage", || {
4688        for (module, ud, f) in &handlers().entity_damage {
4689            if module.is_retiring() {
4690                continue;
4691            }
4692            let Some(_call) = module.enter() else {
4693                continue;
4694            };
4695            unsafe { f(*ud, srv, &ev, 1) };
4696        }
4697    });
4698}
4699
4700#[no_mangle]
4701pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDeath<'l>(
4702    mut env: JNIEnv<'l>,
4703    _class: JClass<'l>,
4704    entity_type: JString<'l>,
4705    uuid: JString<'l>,
4706    source: JString<'l>,
4707    dimension: JString<'l>,
4708) {
4709    let (et, u, s, d) = (
4710        jstr!(env, entity_type),
4711        jstr!(env, uuid),
4712        jstr!(env, source),
4713        jstr!(env, dimension),
4714    );
4715    let ev = yog_abi::YogEntityDeathEvent {
4716        entity_type: YogStr::from_str(&et),
4717        uuid: YogStr::from_str(&u),
4718        source: YogStr::from_str(&s),
4719        dimension: YogStr::from_str(&d),
4720    };
4721    let srv = srv_ptr();
4722    guard("on_entity_death", || {
4723        for (module, ud, f) in &handlers().entity_death {
4724            if module.is_retiring() {
4725                continue;
4726            }
4727            let Some(_call) = module.enter() else {
4728                continue;
4729            };
4730            unsafe { f(*ud, srv, &ev, 1) };
4731        }
4732    });
4733}
4734
4735#[no_mangle]
4736pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnTick<'l>(
4737    _env: JNIEnv<'l>,
4738    _class: JClass<'l>,
4739) {
4740    let h = handlers();
4741    let srv = srv_ptr();
4742    guard("on_tick", || {
4743        for (module, ud, f) in &h.server_tick {
4744            if module.is_retiring() {
4745                continue;
4746            }
4747            let Some(_call) = module.enter() else {
4748                continue;
4749            };
4750            unsafe { f(*ud, srv) };
4751        }
4752    });
4753
4754    guard("startup_grants", process_pending_grants);
4755
4756    // Scheduler — once tasks
4757    {
4758        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
4759        let mut to_fire: Vec<(LoadedModule, *mut c_void, YogScheduledFn)> = Vec::new();
4760        let mut remaining = Vec::new();
4761        for task in sched.once_tasks.drain(..) {
4762            if task.delay_remaining == 0 {
4763                to_fire.push((task.module.clone(), task.ud, task.f));
4764            } else {
4765                remaining.push(OnceTask {
4766                    delay_remaining: task.delay_remaining - 1,
4767                    ..task
4768                });
4769            }
4770        }
4771        sched.once_tasks = remaining;
4772        drop(sched);
4773        for (module, ud, f) in to_fire {
4774            if module.is_retiring() {
4775                continue;
4776            }
4777            let Some(_call) = module.enter() else {
4778                continue;
4779            };
4780            guard("schedule_once", || unsafe { f(ud, srv) });
4781        }
4782    }
4783
4784    // Scheduler — repeating tasks
4785    {
4786        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
4787        let mut to_fire: Vec<(LoadedModule, *mut c_void, YogScheduledFn)> = Vec::new();
4788        for task in &mut sched.repeating_tasks {
4789            if task.ticks_left == 0 {
4790                to_fire.push((task.module.clone(), task.ud, task.f));
4791                task.ticks_left = task.period;
4792            } else {
4793                task.ticks_left -= 1;
4794            }
4795        }
4796        drop(sched);
4797        for (module, ud, f) in to_fire {
4798            if module.is_retiring() {
4799                continue;
4800            }
4801            let Some(_call) = module.enter() else {
4802                continue;
4803            };
4804            guard("schedule_repeating", || unsafe { f(ud, srv) });
4805        }
4806    }
4807}
4808
4809/// Absolute path of the current world save folder (set on server start).
4810static WORLD_DIR: Mutex<Option<std::path::PathBuf>> = Mutex::new(None);
4811
4812/// Per-world data path: `<world>/yog-data/startup_grants.json`.
4813/// Falls back to the working directory before any server has started.
4814fn startup_grants_path() -> std::path::PathBuf {
4815    let base = WORLD_DIR
4816        .lock()
4817        .ok()
4818        .and_then(|d| d.clone())
4819        .unwrap_or_else(|| std::path::PathBuf::from("."));
4820    base.join("yog-data").join("startup_grants.json")
4821}
4822
4823fn load_startup_granted() {
4824    let h = handlers();
4825    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
4826    // Reset first — in singleplayer the process outlives individual worlds,
4827    // and grant state is per-world.
4828    granted.clear();
4829    h.pending_grants
4830        .lock()
4831        .expect("pending_grants poisoned")
4832        .clear();
4833    let path = startup_grants_path();
4834    let Ok(data) = std::fs::read_to_string(&path) else {
4835        return;
4836    };
4837    let Ok(keys) = serde_json::from_str::<Vec<String>>(&data) else {
4838        yog_logging::warn!("startup_grants.json: invalid JSON, ignoring");
4839        return;
4840    };
4841    for k in keys {
4842        granted.insert(k, true);
4843    }
4844    yog_logging::info!("loaded {} startup grants from disk", granted.len());
4845}
4846
4847fn save_startup_granted(granted: &HashMap<String, bool>) {
4848    let path = startup_grants_path();
4849    if let Some(parent) = path.parent() {
4850        let _ = std::fs::create_dir_all(parent);
4851    }
4852    let keys: Vec<&String> = granted.keys().collect();
4853    match serde_json::to_string(&keys) {
4854        Ok(json) => {
4855            let _ = std::fs::write(&path, json);
4856        }
4857        Err(e) => yog_logging::error!("failed to save startup_grants.json: {}", e),
4858    }
4859}
4860
4861#[no_mangle]
4862pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStarted<'l>(
4863    mut env: JNIEnv<'l>,
4864    _class: JClass<'l>,
4865    world_dir: JString<'l>,
4866) {
4867    let dir = jstr!(env, world_dir);
4868    *WORLD_DIR.lock().expect("WORLD_DIR poisoned") = if dir.is_empty() {
4869        None
4870    } else {
4871        Some(std::path::PathBuf::from(dir))
4872    };
4873    load_startup_granted();
4874    let srv = srv_ptr();
4875    guard("on_server_started", || {
4876        for (module, ud, f) in &handlers().server_started {
4877            if module.is_retiring() {
4878                continue;
4879            }
4880            let Some(_call) = module.enter() else {
4881                continue;
4882            };
4883            unsafe { f(*ud, srv) };
4884        }
4885    });
4886}
4887
4888#[no_mangle]
4889pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStopping<'l>(
4890    _env: JNIEnv<'l>,
4891    _class: JClass<'l>,
4892) {
4893    let srv = srv_ptr();
4894    guard("on_server_stopping", || {
4895        for (module, ud, f) in &handlers().server_stopping {
4896            if module.is_retiring() {
4897                continue;
4898            }
4899            let Some(_call) = module.enter() else {
4900                continue;
4901            };
4902            unsafe { f(*ud, srv) };
4903        }
4904    });
4905}
4906
4907#[no_mangle]
4908pub extern "system" fn Java_dev_yog_NativeBridge_nativeCommandNames<'l>(
4909    env: JNIEnv<'l>,
4910    _class: JClass<'l>,
4911) -> jstring {
4912    let names = handlers()
4913        .commands
4914        .keys()
4915        .cloned()
4916        .collect::<Vec<_>>()
4917        .join("\n");
4918    env.new_string(names)
4919        .map(|s| s.into_raw())
4920        .unwrap_or(std::ptr::null_mut())
4921}
4922
4923#[no_mangle]
4924pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreakPre<'l>(
4925    mut env: JNIEnv<'l>,
4926    _class: JClass<'l>,
4927    player: JString<'l>,
4928    block: JString<'l>,
4929    x: jint,
4930    y: jint,
4931    z: jint,
4932    dimension: JString<'l>,
4933) -> jni::sys::jboolean {
4934    let h = handlers();
4935    if h.block_break.is_empty() {
4936        return 1;
4937    }
4938    let p = match env.get_string(&player) {
4939        Ok(s) => String::from(s),
4940        Err(_) => return 1,
4941    };
4942    let b = match env.get_string(&block) {
4943        Ok(s) => String::from(s),
4944        Err(_) => return 1,
4945    };
4946    let d = match env.get_string(&dimension) {
4947        Ok(s) => String::from(s),
4948        Err(_) => return 1,
4949    };
4950    let ev = yog_abi::YogBlockBreakEvent {
4951        player: YogStr::from_str(&p),
4952        block: YogStr::from_str(&b),
4953        pos: YogBlockPos { x, y, z },
4954        dimension: YogStr::from_str(&d),
4955    };
4956    let srv = srv_ptr();
4957    let mut allow = true;
4958    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4959        for (module, ud, f) in &h.block_break {
4960            if module.is_retiring() {
4961                continue;
4962            }
4963            let Some(_call) = module.enter() else {
4964                continue;
4965            };
4966            if !unsafe { f(*ud, srv, &ev, 0) } {
4967                allow = false;
4968                break;
4969            }
4970        }
4971    }))
4972    .ok();
4973    allow as jni::sys::jboolean
4974}
4975
4976#[no_mangle]
4977pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChatPre<'l>(
4978    mut env: JNIEnv<'l>,
4979    _class: JClass<'l>,
4980    player: JString<'l>,
4981    message: JString<'l>,
4982    dimension: JString<'l>,
4983) -> jni::sys::jboolean {
4984    let h = handlers();
4985    if h.chat.is_empty() {
4986        return 1;
4987    }
4988    let p = match env.get_string(&player) {
4989        Ok(s) => String::from(s),
4990        Err(_) => return 1,
4991    };
4992    let m = match env.get_string(&message) {
4993        Ok(s) => String::from(s),
4994        Err(_) => return 1,
4995    };
4996    let d = match env.get_string(&dimension) {
4997        Ok(s) => String::from(s),
4998        Err(_) => return 1,
4999    };
5000    let ev = yog_abi::YogChatEvent {
5001        player: YogStr::from_str(&p),
5002        message: YogStr::from_str(&m),
5003        dimension: YogStr::from_str(&d),
5004    };
5005    let srv = srv_ptr();
5006    let mut allow = true;
5007    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5008        for (module, ud, f) in &h.chat {
5009            if module.is_retiring() {
5010                continue;
5011            }
5012            let Some(_call) = module.enter() else {
5013                continue;
5014            };
5015            if !unsafe { f(*ud, srv, &ev, 0) } {
5016                allow = false;
5017                break;
5018            }
5019        }
5020    }))
5021    .ok();
5022    allow as jni::sys::jboolean
5023}
5024
5025#[no_mangle]
5026pub extern "system" fn Java_dev_yog_NativeBridge_nativeRecipeJsons<'l>(
5027    env: JNIEnv<'l>,
5028    _class: JClass<'l>,
5029) -> jstring {
5030    let s = handlers()
5031        .recipes
5032        .iter()
5033        .map(|(ns, name, json)| format!("{}\t{}\t{}", ns, name, json))
5034        .collect::<Vec<_>>()
5035        .join("\n");
5036    env.new_string(s)
5037        .map(|s| s.into_raw())
5038        .unwrap_or(std::ptr::null_mut())
5039}
5040
5041#[no_mangle]
5042pub extern "system" fn Java_dev_yog_NativeBridge_nativeDimensionJsons<'l>(
5043    env: JNIEnv<'l>,
5044    _class: JClass<'l>,
5045) -> jstring {
5046    // One line per declared dimension: `id \t def_json`. The host converts
5047    // `def_json` (our YogDimensionDef shape) into vanilla dimension_type /
5048    // dimension datapack JSON — see `yog-dimensions` crate docs.
5049    let s = handlers()
5050        .dimensions
5051        .iter()
5052        .map(|(id, json)| format!("{}\t{}", id, json))
5053        .collect::<Vec<_>>()
5054        .join("\n");
5055    env.new_string(s)
5056        .map(|s| s.into_raw())
5057        .unwrap_or(std::ptr::null_mut())
5058}
5059
5060/// Called by a registered chunk-generator closure (via `ChunkWriter::set_block`)
5061/// to place one block in the chunk currently being generated. Calls back
5062/// into `YogCallbackChunkGenerator.setBlockInGeneratingChunk` on the Java
5063/// side — same thread, since the whole round trip is synchronous.
5064unsafe extern "C" fn chunk_writer_set_block(
5065    _ctx: *mut c_void,
5066    x: i32,
5067    y: i32,
5068    z: i32,
5069    block_id: YogStr,
5070) -> bool {
5071    let Some(mut env) = get_env() else {
5072        return false;
5073    };
5074    let Some(jb) = ys_to_java(&mut env, block_id) else {
5075        return false;
5076    };
5077    env.call_static_method(
5078        "dev/yog/NativeBridge",
5079        "setBlockInGeneratingChunk",
5080        "(IIILjava/lang/String;)Z",
5081        &[
5082            JValue::Int(x),
5083            JValue::Int(y),
5084            JValue::Int(z),
5085            JValue::Object(&jb),
5086        ],
5087    )
5088    .and_then(|v| v.z())
5089    .unwrap_or(false)
5090}
5091
5092#[no_mangle]
5093pub extern "system" fn Java_dev_yog_NativeBridge_nativeGenerateChunk<'l>(
5094    mut env: JNIEnv<'l>,
5095    _class: JClass<'l>,
5096    generator_type_id: JString<'l>,
5097    chunk_x: jint,
5098    chunk_z: jint,
5099    min_y: jint,
5100    height: jint,
5101) {
5102    let id: String = match env.get_string(&generator_type_id) {
5103        Ok(s) => String::from(s),
5104        Err(_) => return,
5105    };
5106    let Some((module, ud, cb)) = handlers().chunk_generators.get(&id).cloned() else {
5107        return;
5108    };
5109    if module.is_retiring() {
5110        return;
5111    }
5112    let Some(_call) = module.enter() else { return };
5113    let writer = yog_abi::YogChunkWriterApi {
5114        chunk_x,
5115        chunk_z,
5116        min_y,
5117        height,
5118        ctx: std::ptr::null_mut(),
5119        set_block: chunk_writer_set_block,
5120    };
5121    guard("chunk_generator", || unsafe {
5122        cb(ud, &writer as *const _);
5123    });
5124}
5125
5126#[no_mangle]
5127pub extern "system" fn Java_dev_yog_NativeBridge_nativeTypedCommandSchemas<'l>(
5128    env: JNIEnv<'l>,
5129    _class: JClass<'l>,
5130) -> jstring {
5131    // One line per DISTINCT (name, schema) pair — a name can have several
5132    // typed registrations (different arg shapes); Brigadier merges repeated
5133    // `dispatcher.register()` calls for the same literal name into one tree,
5134    // so the Java side just needs every distinct schema once each.
5135    let mut lines = Vec::new();
5136    for (name, regs) in handlers().commands.iter() {
5137        let mut seen = std::collections::HashSet::new();
5138        for (_module, schema, _, _) in regs {
5139            if let Some(schema) = schema {
5140                if seen.insert(schema.as_str()) {
5141                    lines.push(format!("{}\t{}", name, schema));
5142                }
5143            }
5144        }
5145    }
5146    env.new_string(lines.join("\n"))
5147        .map(|s| s.into_raw())
5148        .unwrap_or(std::ptr::null_mut())
5149}
5150
5151#[no_mangle]
5152pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnCommand<'l>(
5153    mut env: JNIEnv<'l>,
5154    _class: JClass<'l>,
5155    name: JString<'l>,
5156    args: JString<'l>,
5157    source: JString<'l>,
5158    uuid: JString<'l>,
5159    dimension: JString<'l>,
5160) -> jstring {
5161    let (n, a, s, u, d) = (
5162        env.get_string(&name).map(String::from).unwrap_or_default(),
5163        env.get_string(&args).map(String::from).unwrap_or_default(),
5164        env.get_string(&source)
5165            .map(String::from)
5166            .unwrap_or_default(),
5167        env.get_string(&uuid).map(String::from).unwrap_or_default(),
5168        env.get_string(&dimension)
5169            .map(String::from)
5170            .unwrap_or_default(),
5171    );
5172    let ev = yog_abi::YogCommandEvent {
5173        name: YogStr::from_str(&n),
5174        args: YogStr::from_str(&a),
5175        source: YogStr::from_str(&s),
5176        uuid: YogStr::from_str(&u),
5177        dimension: YogStr::from_str(&d),
5178    };
5179    let h = handlers();
5180    let srv = srv_ptr();
5181    // Actual arg count of this invocation (0 for a bare command with no args).
5182    let actual_argc = if a.is_empty() {
5183        0
5184    } else {
5185        a.split('\t').count()
5186    };
5187    let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5188        let Some(regs) = h.commands.get(&n) else {
5189            return String::new();
5190        };
5191        for (module, schema, ud, f) in regs {
5192            let expected_argc = schema.as_ref().map_or(0, |s| s.split_whitespace().count());
5193            if expected_argc != actual_argc {
5194                continue;
5195            }
5196            if module.is_retiring() {
5197                continue;
5198            }
5199            let Some(_call) = module.enter() else {
5200                continue;
5201            };
5202            let mut buf = [0u8; 4096];
5203            let mut reply_len: u32 = 0;
5204            unsafe {
5205                f(
5206                    *ud,
5207                    srv,
5208                    &ev,
5209                    buf.as_mut_ptr(),
5210                    buf.len() as u32,
5211                    &mut reply_len,
5212                )
5213            };
5214            if reply_len > 0 {
5215                return String::from_utf8_lossy(&buf[..reply_len as usize]).into_owned();
5216            }
5217        }
5218        String::new()
5219    }))
5220    .unwrap_or_else(|_| {
5221        yog_logging::error!("a mod panicked handling command `{}`", n);
5222        String::new()
5223    });
5224
5225    env.new_string(reply)
5226        .map(|s| s.into_raw())
5227        .unwrap_or(std::ptr::null_mut())
5228}
5229
5230#[no_mangle]
5231pub extern "system" fn Java_dev_yog_NativeBridge_nativeItemDefs<'l>(
5232    env: JNIEnv<'l>,
5233    _class: JClass<'l>,
5234) -> jstring {
5235    let s = handlers()
5236        .items
5237        .iter()
5238        .map(|d| {
5239            let mut parts = vec![d.id.clone()];
5240            parts.push(format!("max_stack={}", d.max_stack));
5241            if let Some(n) = &d.name {
5242                parts.push(format!("name={n}"));
5243            }
5244            if let Some(t) = &d.tooltip {
5245                parts.push(format!("tooltip={t}"));
5246            }
5247            if d.max_damage > 0 {
5248                parts.push(format!("max_damage={}", d.max_damage));
5249            }
5250            if d.fire_resistant {
5251                parts.push("fire_resistant=1".into());
5252            }
5253            if d.fuel_ticks > 0 {
5254                parts.push(format!("fuel_ticks={}", d.fuel_ticks));
5255            }
5256            if let Some(f) = &d.food {
5257                parts.push(format!(
5258                    "food={}:{}:{}",
5259                    f.nutrition,
5260                    f.saturation,
5261                    if f.can_always_eat { 1 } else { 0 }
5262                ));
5263            }
5264            parts.join("\t")
5265        })
5266        .collect::<Vec<_>>()
5267        .join("\n");
5268    env.new_string(s)
5269        .map(|s| s.into_raw())
5270        .unwrap_or(std::ptr::null_mut())
5271}
5272
5273#[no_mangle]
5274pub extern "system" fn Java_dev_yog_NativeBridge_nativeBlockDefs<'l>(
5275    env: JNIEnv<'l>,
5276    _class: JClass<'l>,
5277) -> jstring {
5278    let s = handlers()
5279        .blocks
5280        .iter()
5281        .map(|d| {
5282            let mut parts = vec![d.id.clone()];
5283            parts.push(format!("hardness={}", d.hardness));
5284            parts.push(format!("resistance={}", d.resistance));
5285            if let Some(n) = &d.name {
5286                parts.push(format!("name={n}"));
5287            }
5288            if let Some(sh) = d.shape {
5289                parts.push(format!(
5290                    "shape={}:{}:{}:{}:{}:{}",
5291                    sh[0], sh[1], sh[2], sh[3], sh[4], sh[5]
5292                ));
5293            }
5294            if d.light_level > 0 {
5295                parts.push(format!("light={}", d.light_level));
5296            }
5297            if let Some(snd) = &d.sound {
5298                parts.push(format!("sound={snd}"));
5299            }
5300            if d.requires_tool {
5301                parts.push("requires_tool=1".into());
5302            }
5303            if d.no_collision {
5304                parts.push("no_collision=1".into());
5305            }
5306            if d.slipperiness > 0.0 {
5307                parts.push(format!("slipperiness={}", d.slipperiness));
5308            }
5309            if d.connects {
5310                parts.push("connects=1".into());
5311            }
5312            if !d.connect_groups.is_empty() {
5313                parts.push(format!("connect_groups={}", d.connect_groups.join(",")));
5314            }
5315            if let Some(inv) = &d.inventory_id {
5316                parts.push(format!("inventory_id={inv}"));
5317            }
5318            parts.join("\t")
5319        })
5320        .collect::<Vec<_>>()
5321        .join("\n");
5322    env.new_string(s)
5323        .map(|s| s.into_raw())
5324        .unwrap_or(std::ptr::null_mut())
5325}
5326
5327/// Tab/newline-encoded inventory defs — one line per registered
5328/// `InventoryDef` (see `yog_inventory`): `id\tslot_count=N\tlayout=x:y,...
5329/// \tinclude_player_inventory=0|1\tplayer_inv=x:y\tbackground_texture=...\ttitle=...`
5330#[no_mangle]
5331pub extern "system" fn Java_dev_yog_NativeBridge_nativeInventoryDefs<'l>(
5332    env: JNIEnv<'l>,
5333    _class: JClass<'l>,
5334) -> jstring {
5335    let s = handlers()
5336        .inventories
5337        .iter()
5338        .map(|d| {
5339            let mut parts = vec![d.id.clone()];
5340            parts.push(format!("slot_count={}", d.slot_count));
5341            parts.push(format!(
5342                "layout={}",
5343                yog_inventory::encode_layout(&d.resolved_layout())
5344            ));
5345            parts.push(format!(
5346                "include_player_inventory={}",
5347                d.include_player_inventory as u8
5348            ));
5349            parts.push(format!(
5350                "player_inv={}:{}",
5351                d.player_inv_offset.0, d.player_inv_offset.1
5352            ));
5353            if let Some(tex) = &d.background_texture {
5354                parts.push(format!("background_texture={tex}"));
5355            }
5356            if !d.title.is_empty() {
5357                parts.push(format!("title={}", d.title));
5358            }
5359            if let Some((w, h)) = d.background_size {
5360                parts.push(format!("background_size={w}:{h}"));
5361            }
5362            parts.join("\t")
5363        })
5364        .collect::<Vec<_>>()
5365        .join("\n");
5366    env.new_string(s)
5367        .map(|s| s.into_raw())
5368        .unwrap_or(std::ptr::null_mut())
5369}
5370
5371#[no_mangle]
5372pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPacket<'l>(
5373    mut env: JNIEnv<'l>,
5374    _class: JClass<'l>,
5375    channel: JString<'l>,
5376    player: JString<'l>,
5377    payload: JByteArray<'l>,
5378) {
5379    let ch = env
5380        .get_string(&channel)
5381        .map(String::from)
5382        .unwrap_or_default();
5383    let pl = env
5384        .get_string(&player)
5385        .map(String::from)
5386        .unwrap_or_default();
5387    let data = env.convert_byte_array(&payload).unwrap_or_default();
5388    let ev = yog_abi::YogPacketEvent {
5389        channel: YogStr::from_str(&ch),
5390        player: YogStr::from_str(&pl),
5391        payload: data.as_ptr(),
5392        payload_len: data.len() as u32,
5393    };
5394    let h = handlers();
5395    let srv = srv_ptr();
5396    guard("on_packet", || {
5397        if let Some((module, ud, f)) = h.packets.get(&ch) {
5398            if module.is_retiring() {
5399                return;
5400            }
5401            let Some(_call) = module.enter() else { return };
5402            unsafe { f(*ud, srv, &ev) };
5403        }
5404    });
5405}
5406
5407#[no_mangle]
5408pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientPacket<'l>(
5409    mut env: JNIEnv<'l>,
5410    _class: JClass<'l>,
5411    channel: JString<'l>,
5412    payload: JByteArray<'l>,
5413) {
5414    let ch = env
5415        .get_string(&channel)
5416        .map(String::from)
5417        .unwrap_or_default();
5418    let data = env.convert_byte_array(&payload).unwrap_or_default();
5419    let ev = yog_abi::YogPacketEvent {
5420        channel: YogStr::from_str(&ch),
5421        player: YogStr::EMPTY,
5422        payload: data.as_ptr(),
5423        payload_len: data.len() as u32,
5424    };
5425    let h = handlers();
5426    let srv = srv_ptr();
5427    guard("on_client_packet", || {
5428        if let Some((module, ud, f)) = h.client_packets.get(&ch) {
5429            if module.is_retiring() {
5430                return;
5431            }
5432            let Some(_call) = module.enter() else { return };
5433            unsafe { f(*ud, srv, &ev) };
5434        }
5435    });
5436}
5437
5438#[no_mangle]
5439pub extern "system" fn Java_dev_yog_NativeBridge_nativePacketChannels<'l>(
5440    env: JNIEnv<'l>,
5441    _class: JClass<'l>,
5442) -> jstring {
5443    let s = handlers()
5444        .packets
5445        .keys()
5446        .cloned()
5447        .collect::<Vec<_>>()
5448        .join("\n");
5449    env.new_string(s)
5450        .map(|s| s.into_raw())
5451        .unwrap_or(std::ptr::null_mut())
5452}
5453
5454#[no_mangle]
5455pub extern "system" fn Java_dev_yog_NativeBridge_nativeClientPacketChannels<'l>(
5456    env: JNIEnv<'l>,
5457    _class: JClass<'l>,
5458) -> jstring {
5459    let s = handlers()
5460        .client_packets
5461        .keys()
5462        .cloned()
5463        .collect::<Vec<_>>()
5464        .join("\n");
5465    env.new_string(s)
5466        .map(|s| s.into_raw())
5467        .unwrap_or(std::ptr::null_mut())
5468}
5469
5470#[no_mangle]
5471pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawn<'l>(
5472    mut env: JNIEnv<'l>,
5473    _class: JClass<'l>,
5474    entity_type: JString<'l>,
5475    uuid: JString<'l>,
5476    dimension: JString<'l>,
5477) {
5478    let h = handlers();
5479    if h.entity_spawn.is_empty() {
5480        return;
5481    }
5482    let (et, u, d) = (
5483        jstr!(env, entity_type),
5484        jstr!(env, uuid),
5485        jstr!(env, dimension),
5486    );
5487    let ev = yog_abi::YogEntitySpawnEvent {
5488        entity_type: YogStr::from_str(&et),
5489        uuid: YogStr::from_str(&u),
5490        dimension: YogStr::from_str(&d),
5491    };
5492    let srv = srv_ptr();
5493    guard("on_entity_spawn", || {
5494        for (module, ud, f) in &h.entity_spawn {
5495            if module.is_retiring() {
5496                continue;
5497            }
5498            let Some(_call) = module.enter() else {
5499                continue;
5500            };
5501            unsafe { f(*ud, srv, &ev, 1) };
5502        }
5503    });
5504}
5505
5506#[no_mangle]
5507pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawnPre<'l>(
5508    mut env: JNIEnv<'l>,
5509    _class: JClass<'l>,
5510    entity_type: JString<'l>,
5511    uuid: JString<'l>,
5512    dimension: JString<'l>,
5513) -> jni::sys::jboolean {
5514    let h = handlers();
5515    if h.entity_spawn.is_empty() {
5516        return 1;
5517    }
5518    let et = match env.get_string(&entity_type) {
5519        Ok(s) => String::from(s),
5520        Err(_) => return 1,
5521    };
5522    let u = match env.get_string(&uuid) {
5523        Ok(s) => String::from(s),
5524        Err(_) => return 1,
5525    };
5526    let d = match env.get_string(&dimension) {
5527        Ok(s) => String::from(s),
5528        Err(_) => return 1,
5529    };
5530    let ev = yog_abi::YogEntitySpawnEvent {
5531        entity_type: YogStr::from_str(&et),
5532        uuid: YogStr::from_str(&u),
5533        dimension: YogStr::from_str(&d),
5534    };
5535    let srv = srv_ptr();
5536    let mut allow = true;
5537    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5538        for (module, ud, f) in &h.entity_spawn {
5539            if module.is_retiring() {
5540                continue;
5541            }
5542            let Some(_call) = module.enter() else {
5543                continue;
5544            };
5545            if !unsafe { f(*ud, srv, &ev, 0) } {
5546                allow = false;
5547                break;
5548            }
5549        }
5550    }))
5551    .ok();
5552    allow as jni::sys::jboolean
5553}
5554
5555#[no_mangle]
5556pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamagePre<'l>(
5557    mut env: JNIEnv<'l>,
5558    _class: JClass<'l>,
5559    entity_type: JString<'l>,
5560    uuid: JString<'l>,
5561    amount: jfloat,
5562    source: JString<'l>,
5563    dimension: JString<'l>,
5564) -> jni::sys::jboolean {
5565    let h = handlers();
5566    if h.entity_damage.is_empty() {
5567        return 1;
5568    }
5569    let et = match env.get_string(&entity_type) {
5570        Ok(s) => String::from(s),
5571        Err(_) => return 1,
5572    };
5573    let u = match env.get_string(&uuid) {
5574        Ok(s) => String::from(s),
5575        Err(_) => return 1,
5576    };
5577    let s = match env.get_string(&source) {
5578        Ok(s) => String::from(s),
5579        Err(_) => return 1,
5580    };
5581    let d = match env.get_string(&dimension) {
5582        Ok(s) => String::from(s),
5583        Err(_) => return 1,
5584    };
5585    let ev = yog_abi::YogEntityDamageEvent {
5586        entity_type: YogStr::from_str(&et),
5587        uuid: YogStr::from_str(&u),
5588        amount,
5589        source: YogStr::from_str(&s),
5590        dimension: YogStr::from_str(&d),
5591    };
5592    let srv = srv_ptr();
5593    let mut allow = true;
5594    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5595        for (module, ud, f) in &h.entity_damage {
5596            if module.is_retiring() {
5597                continue;
5598            }
5599            let Some(_call) = module.enter() else {
5600                continue;
5601            };
5602            if !unsafe { f(*ud, srv, &ev, 0) } {
5603                allow = false;
5604                break;
5605            }
5606        }
5607    }))
5608    .ok();
5609    allow as jni::sys::jboolean
5610}
5611
5612#[no_mangle]
5613pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlockPre<'l>(
5614    mut env: JNIEnv<'l>,
5615    _class: JClass<'l>,
5616    player: JString<'l>,
5617    block: JString<'l>,
5618    x: jint,
5619    y: jint,
5620    z: jint,
5621    dimension: JString<'l>,
5622) -> jni::sys::jboolean {
5623    let h = handlers();
5624    if h.player_place_block.is_empty() {
5625        return 1;
5626    }
5627    let p = match env.get_string(&player) {
5628        Ok(s) => String::from(s),
5629        Err(_) => return 1,
5630    };
5631    let b = match env.get_string(&block) {
5632        Ok(s) => String::from(s),
5633        Err(_) => return 1,
5634    };
5635    let d = match env.get_string(&dimension) {
5636        Ok(s) => String::from(s),
5637        Err(_) => return 1,
5638    };
5639    let ev = YogPlaceBlockEvent {
5640        player: YogStr::from_str(&p),
5641        block: YogStr::from_str(&b),
5642        pos: YogBlockPos { x, y, z },
5643        dimension: YogStr::from_str(&d),
5644    };
5645    let srv = srv_ptr();
5646    let mut allow = true;
5647    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5648        for (module, ud, f) in &h.player_place_block {
5649            if module.is_retiring() {
5650                continue;
5651            }
5652            let Some(_call) = module.enter() else {
5653                continue;
5654            };
5655            if !unsafe { f(*ud, srv, &ev, 0) } {
5656                allow = false;
5657                break;
5658            }
5659        }
5660    }))
5661    .ok();
5662    allow as jni::sys::jboolean
5663}
5664
5665#[no_mangle]
5666pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlock<'l>(
5667    mut env: JNIEnv<'l>,
5668    _class: JClass<'l>,
5669    player: JString<'l>,
5670    block: JString<'l>,
5671    x: jint,
5672    y: jint,
5673    z: jint,
5674    dimension: JString<'l>,
5675) {
5676    let h = handlers();
5677    if h.player_place_block.is_empty() {
5678        return;
5679    }
5680    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
5681    let ev = YogPlaceBlockEvent {
5682        player: YogStr::from_str(&p),
5683        block: YogStr::from_str(&b),
5684        pos: YogBlockPos { x, y, z },
5685        dimension: YogStr::from_str(&d),
5686    };
5687    let srv = srv_ptr();
5688    guard("on_player_place_block", || {
5689        for (module, ud, f) in &h.player_place_block {
5690            if module.is_retiring() {
5691                continue;
5692            }
5693            let Some(_call) = module.enter() else {
5694                continue;
5695            };
5696            unsafe { f(*ud, srv, &ev, 1) };
5697        }
5698    });
5699}
5700
5701#[no_mangle]
5702pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeathPre<'l>(
5703    mut env: JNIEnv<'l>,
5704    _class: JClass<'l>,
5705    player: JString<'l>,
5706    uuid: JString<'l>,
5707    source: JString<'l>,
5708    dimension: JString<'l>,
5709) -> jni::sys::jboolean {
5710    let h = handlers();
5711    if h.player_death.is_empty() {
5712        return 1;
5713    }
5714    let p = match env.get_string(&player) {
5715        Ok(s) => String::from(s),
5716        Err(_) => return 1,
5717    };
5718    let u = match env.get_string(&uuid) {
5719        Ok(s) => String::from(s),
5720        Err(_) => return 1,
5721    };
5722    let s = match env.get_string(&source) {
5723        Ok(s) => String::from(s),
5724        Err(_) => return 1,
5725    };
5726    let d = match env.get_string(&dimension) {
5727        Ok(s) => String::from(s),
5728        Err(_) => return 1,
5729    };
5730    let ev = YogPlayerDeathEvent {
5731        player: YogStr::from_str(&p),
5732        uuid: YogStr::from_str(&u),
5733        source: YogStr::from_str(&s),
5734        dimension: YogStr::from_str(&d),
5735    };
5736    let srv = srv_ptr();
5737    let mut allow = true;
5738    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5739        for (module, ud, f) in &h.player_death {
5740            if module.is_retiring() {
5741                continue;
5742            }
5743            let Some(_call) = module.enter() else {
5744                continue;
5745            };
5746            if !unsafe { f(*ud, srv, &ev, 0) } {
5747                allow = false;
5748                break;
5749            }
5750        }
5751    }))
5752    .ok();
5753    allow as jni::sys::jboolean
5754}
5755
5756#[no_mangle]
5757pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeath<'l>(
5758    mut env: JNIEnv<'l>,
5759    _class: JClass<'l>,
5760    player: JString<'l>,
5761    uuid: JString<'l>,
5762    source: JString<'l>,
5763    dimension: JString<'l>,
5764) {
5765    let h = handlers();
5766    if h.player_death.is_empty() {
5767        return;
5768    }
5769    let (p, u, s, d) = (
5770        jstr!(env, player),
5771        jstr!(env, uuid),
5772        jstr!(env, source),
5773        jstr!(env, dimension),
5774    );
5775    let ev = YogPlayerDeathEvent {
5776        player: YogStr::from_str(&p),
5777        uuid: YogStr::from_str(&u),
5778        source: YogStr::from_str(&s),
5779        dimension: YogStr::from_str(&d),
5780    };
5781    let srv = srv_ptr();
5782    guard("on_player_death", || {
5783        for (module, ud, f) in &h.player_death {
5784            if module.is_retiring() {
5785                continue;
5786            }
5787            let Some(_call) = module.enter() else {
5788                continue;
5789            };
5790            unsafe { f(*ud, srv, &ev, 1) };
5791        }
5792    });
5793}
5794
5795#[no_mangle]
5796pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerRespawn<'l>(
5797    mut env: JNIEnv<'l>,
5798    _class: JClass<'l>,
5799    player: JString<'l>,
5800    uuid: JString<'l>,
5801    at_anchor: jni::sys::jboolean,
5802    dimension: JString<'l>,
5803) {
5804    let h = handlers();
5805    if h.player_respawn.is_empty() {
5806        return;
5807    }
5808    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
5809    let ev = YogPlayerRespawnEvent {
5810        player: YogStr::from_str(&p),
5811        uuid: YogStr::from_str(&u),
5812        at_anchor: at_anchor != 0,
5813        dimension: YogStr::from_str(&d),
5814    };
5815    let srv = srv_ptr();
5816    guard("on_player_respawn", || {
5817        for (module, ud, f) in &h.player_respawn {
5818            if module.is_retiring() {
5819                continue;
5820            }
5821            let Some(_call) = module.enter() else {
5822                continue;
5823            };
5824            unsafe { f(*ud, srv, &ev, 1) };
5825        }
5826    });
5827}
5828
5829#[no_mangle]
5830pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAdvancement<'l>(
5831    mut env: JNIEnv<'l>,
5832    _class: JClass<'l>,
5833    player: JString<'l>,
5834    uuid: JString<'l>,
5835    advancement: JString<'l>,
5836    dimension: JString<'l>,
5837) {
5838    let h = handlers();
5839    if h.advancement.is_empty() {
5840        return;
5841    }
5842    let (p, u, a, d) = (
5843        jstr!(env, player),
5844        jstr!(env, uuid),
5845        jstr!(env, advancement),
5846        jstr!(env, dimension),
5847    );
5848    let ev = YogAdvancementEvent {
5849        player: YogStr::from_str(&p),
5850        uuid: YogStr::from_str(&u),
5851        advancement: YogStr::from_str(&a),
5852        dimension: YogStr::from_str(&d),
5853    };
5854    let srv = srv_ptr();
5855    guard("on_advancement", || {
5856        for (module, ud, f) in &h.advancement {
5857            if module.is_retiring() {
5858                continue;
5859            }
5860            let Some(_call) = module.enter() else {
5861                continue;
5862            };
5863            unsafe { f(*ud, srv, &ev, 1) };
5864        }
5865    });
5866}
5867
5868#[no_mangle]
5869pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteractPre<'l>(
5870    mut env: JNIEnv<'l>,
5871    _class: JClass<'l>,
5872    player: JString<'l>,
5873    player_uuid: JString<'l>,
5874    entity_type: JString<'l>,
5875    entity_uuid: JString<'l>,
5876    hand: JString<'l>,
5877    dimension: JString<'l>,
5878) -> jni::sys::jboolean {
5879    let h = handlers();
5880    if h.entity_interact.is_empty() {
5881        return 1;
5882    }
5883    let p = match env.get_string(&player) {
5884        Ok(s) => String::from(s),
5885        Err(_) => return 1,
5886    };
5887    let pu = match env.get_string(&player_uuid) {
5888        Ok(s) => String::from(s),
5889        Err(_) => return 1,
5890    };
5891    let et = match env.get_string(&entity_type) {
5892        Ok(s) => String::from(s),
5893        Err(_) => return 1,
5894    };
5895    let eu = match env.get_string(&entity_uuid) {
5896        Ok(s) => String::from(s),
5897        Err(_) => return 1,
5898    };
5899    let ha = match env.get_string(&hand) {
5900        Ok(s) => String::from(s),
5901        Err(_) => return 1,
5902    };
5903    let d = match env.get_string(&dimension) {
5904        Ok(s) => String::from(s),
5905        Err(_) => return 1,
5906    };
5907    let ev = YogEntityInteractEvent {
5908        player: YogStr::from_str(&p),
5909        player_uuid: YogStr::from_str(&pu),
5910        entity_type: YogStr::from_str(&et),
5911        entity_uuid: YogStr::from_str(&eu),
5912        hand: YogStr::from_str(&ha),
5913        dimension: YogStr::from_str(&d),
5914    };
5915    let srv = srv_ptr();
5916    let mut allow = true;
5917    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5918        for (module, ud, f) in &h.entity_interact {
5919            if module.is_retiring() {
5920                continue;
5921            }
5922            let Some(_call) = module.enter() else {
5923                continue;
5924            };
5925            if !unsafe { f(*ud, srv, &ev, 0) } {
5926                allow = false;
5927                break;
5928            }
5929        }
5930    }))
5931    .ok();
5932    allow as jni::sys::jboolean
5933}
5934
5935#[no_mangle]
5936pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteract<'l>(
5937    mut env: JNIEnv<'l>,
5938    _class: JClass<'l>,
5939    player: JString<'l>,
5940    player_uuid: JString<'l>,
5941    entity_type: JString<'l>,
5942    entity_uuid: JString<'l>,
5943    hand: JString<'l>,
5944    dimension: JString<'l>,
5945) {
5946    let h = handlers();
5947    if h.entity_interact.is_empty() {
5948        return;
5949    }
5950    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
5951    let (et, eu, ha, d) = (
5952        jstr!(env, entity_type),
5953        jstr!(env, entity_uuid),
5954        jstr!(env, hand),
5955        jstr!(env, dimension),
5956    );
5957    let ev = YogEntityInteractEvent {
5958        player: YogStr::from_str(&p),
5959        player_uuid: YogStr::from_str(&pu),
5960        entity_type: YogStr::from_str(&et),
5961        entity_uuid: YogStr::from_str(&eu),
5962        hand: YogStr::from_str(&ha),
5963        dimension: YogStr::from_str(&d),
5964    };
5965    let srv = srv_ptr();
5966    guard("on_entity_interact", || {
5967        for (module, ud, f) in &h.entity_interact {
5968            if module.is_retiring() {
5969                continue;
5970            }
5971            let Some(_call) = module.enter() else {
5972                continue;
5973            };
5974            unsafe { f(*ud, srv, &ev, 1) };
5975        }
5976    });
5977}
5978
5979#[no_mangle]
5980pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemCraft<'l>(
5981    mut env: JNIEnv<'l>,
5982    _class: JClass<'l>,
5983    player: JString<'l>,
5984    player_uuid: JString<'l>,
5985    result_item: JString<'l>,
5986    result_count: jint,
5987    dimension: JString<'l>,
5988) {
5989    let h = handlers();
5990    if h.item_craft.is_empty() {
5991        return;
5992    }
5993    let (p, pu, ri, d) = (
5994        jstr!(env, player),
5995        jstr!(env, player_uuid),
5996        jstr!(env, result_item),
5997        jstr!(env, dimension),
5998    );
5999    let ev = YogCraftEvent {
6000        player: YogStr::from_str(&p),
6001        player_uuid: YogStr::from_str(&pu),
6002        result_item: YogStr::from_str(&ri),
6003        result_count: result_count as u32,
6004        dimension: YogStr::from_str(&d),
6005    };
6006    let srv = srv_ptr();
6007    guard("on_item_craft", || {
6008        for (module, ud, f) in &h.item_craft {
6009            if module.is_retiring() {
6010                continue;
6011            }
6012            let Some(_call) = module.enter() else {
6013                continue;
6014            };
6015            unsafe { f(*ud, srv, &ev, 1) };
6016        }
6017    });
6018}
6019
6020#[no_mangle]
6021pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosionPre<'l>(
6022    mut env: JNIEnv<'l>,
6023    _class: JClass<'l>,
6024    dimension: JString<'l>,
6025    x: jdouble,
6026    y: jdouble,
6027    z: jdouble,
6028    power: jfloat,
6029    cause_uuid: JString<'l>,
6030) -> jni::sys::jboolean {
6031    let h = handlers();
6032    if h.explosion.is_empty() {
6033        return 1;
6034    }
6035    let d = match env.get_string(&dimension) {
6036        Ok(s) => String::from(s),
6037        Err(_) => return 1,
6038    };
6039    let cu = match env.get_string(&cause_uuid) {
6040        Ok(s) => String::from(s),
6041        Err(_) => return 1,
6042    };
6043    let ev = YogExplosionEvent {
6044        dimension: YogStr::from_str(&d),
6045        x,
6046        y,
6047        z,
6048        power,
6049        cause_uuid: YogStr::from_str(&cu),
6050    };
6051    let srv = srv_ptr();
6052    let mut allow = true;
6053    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6054        for (module, ud, f) in &h.explosion {
6055            if module.is_retiring() {
6056                continue;
6057            }
6058            let Some(_call) = module.enter() else {
6059                continue;
6060            };
6061            if !unsafe { f(*ud, srv, &ev, 0) } {
6062                allow = false;
6063                break;
6064            }
6065        }
6066    }))
6067    .ok();
6068    allow as jni::sys::jboolean
6069}
6070
6071#[no_mangle]
6072pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosion<'l>(
6073    mut env: JNIEnv<'l>,
6074    _class: JClass<'l>,
6075    dimension: JString<'l>,
6076    x: jdouble,
6077    y: jdouble,
6078    z: jdouble,
6079    power: jfloat,
6080    cause_uuid: JString<'l>,
6081) {
6082    let h = handlers();
6083    if h.explosion.is_empty() {
6084        return;
6085    }
6086    let (d, cu) = (jstr!(env, dimension), jstr!(env, cause_uuid));
6087    let ev = YogExplosionEvent {
6088        dimension: YogStr::from_str(&d),
6089        x,
6090        y,
6091        z,
6092        power,
6093        cause_uuid: YogStr::from_str(&cu),
6094    };
6095    let srv = srv_ptr();
6096    guard("on_explosion", || {
6097        for (module, ud, f) in &h.explosion {
6098            if module.is_retiring() {
6099                continue;
6100            }
6101            let Some(_call) = module.enter() else {
6102                continue;
6103            };
6104            unsafe { f(*ud, srv, &ev, 1) };
6105        }
6106    });
6107}
6108
6109// ── ABI minor 9 JNI entry points ─────────────────────────────────────────────
6110
6111#[no_mangle]
6112pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickupPre<'l>(
6113    mut env: JNIEnv<'l>,
6114    _class: JClass<'l>,
6115    player: JString<'l>,
6116    player_uuid: JString<'l>,
6117    item_id: JString<'l>,
6118    item_count: jint,
6119    entity_uuid: JString<'l>,
6120    dimension: JString<'l>,
6121) -> jni::sys::jboolean {
6122    let h = handlers();
6123    if h.item_pickup.is_empty() {
6124        return 1;
6125    }
6126    let p = match env.get_string(&player) {
6127        Ok(s) => String::from(s),
6128        Err(_) => return 1,
6129    };
6130    let pu = match env.get_string(&player_uuid) {
6131        Ok(s) => String::from(s),
6132        Err(_) => return 1,
6133    };
6134    let ii = match env.get_string(&item_id) {
6135        Ok(s) => String::from(s),
6136        Err(_) => return 1,
6137    };
6138    let eu = match env.get_string(&entity_uuid) {
6139        Ok(s) => String::from(s),
6140        Err(_) => return 1,
6141    };
6142    let d = match env.get_string(&dimension) {
6143        Ok(s) => String::from(s),
6144        Err(_) => return 1,
6145    };
6146    let ev = YogItemPickupEvent {
6147        player: YogStr::from_str(&p),
6148        player_uuid: YogStr::from_str(&pu),
6149        item_id: YogStr::from_str(&ii),
6150        item_count: item_count as u32,
6151        entity_uuid: YogStr::from_str(&eu),
6152        dimension: YogStr::from_str(&d),
6153    };
6154    let srv = srv_ptr();
6155    let mut allow = true;
6156    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6157        for (module, ud, f) in &h.item_pickup {
6158            if module.is_retiring() {
6159                continue;
6160            }
6161            let Some(_call) = module.enter() else {
6162                continue;
6163            };
6164            if !unsafe { f(*ud, srv, &ev, 0) } {
6165                allow = false;
6166                break;
6167            }
6168        }
6169    }))
6170    .ok();
6171    allow as jni::sys::jboolean
6172}
6173
6174#[no_mangle]
6175pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickup<'l>(
6176    mut env: JNIEnv<'l>,
6177    _class: JClass<'l>,
6178    player: JString<'l>,
6179    player_uuid: JString<'l>,
6180    item_id: JString<'l>,
6181    item_count: jint,
6182    entity_uuid: JString<'l>,
6183    dimension: JString<'l>,
6184) {
6185    let h = handlers();
6186    if h.item_pickup.is_empty() {
6187        return;
6188    }
6189    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
6190    let (ii, eu, d) = (
6191        jstr!(env, item_id),
6192        jstr!(env, entity_uuid),
6193        jstr!(env, dimension),
6194    );
6195    let ev = YogItemPickupEvent {
6196        player: YogStr::from_str(&p),
6197        player_uuid: YogStr::from_str(&pu),
6198        item_id: YogStr::from_str(&ii),
6199        item_count: item_count as u32,
6200        entity_uuid: YogStr::from_str(&eu),
6201        dimension: YogStr::from_str(&d),
6202    };
6203    let srv = srv_ptr();
6204    guard("on_item_pickup", || {
6205        for (module, ud, f) in &h.item_pickup {
6206            if module.is_retiring() {
6207                continue;
6208            }
6209            let Some(_call) = module.enter() else {
6210                continue;
6211            };
6212            unsafe { f(*ud, srv, &ev, 1) };
6213        }
6214    });
6215}
6216
6217#[no_mangle]
6218pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerMove<'l>(
6219    mut env: JNIEnv<'l>,
6220    _class: JClass<'l>,
6221    player: JString<'l>,
6222    player_uuid: JString<'l>,
6223    x: jdouble,
6224    y: jdouble,
6225    z: jdouble,
6226    yaw: jfloat,
6227    pitch: jfloat,
6228    dimension: JString<'l>,
6229) {
6230    let h = handlers();
6231    if h.player_move.is_empty() {
6232        return;
6233    }
6234    let (p, pu, d) = (
6235        jstr!(env, player),
6236        jstr!(env, player_uuid),
6237        jstr!(env, dimension),
6238    );
6239    let ev = YogPlayerMoveEvent {
6240        player: YogStr::from_str(&p),
6241        player_uuid: YogStr::from_str(&pu),
6242        x,
6243        y,
6244        z,
6245        yaw,
6246        pitch,
6247        dimension: YogStr::from_str(&d),
6248    };
6249    let srv = srv_ptr();
6250    guard("on_player_move", || {
6251        for (module, ud, f) in &h.player_move {
6252            if module.is_retiring() {
6253                continue;
6254            }
6255            let Some(_call) = module.enter() else {
6256                continue;
6257            };
6258            unsafe { f(*ud, srv, &ev, 1) };
6259        }
6260    });
6261}
6262
6263#[no_mangle]
6264pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpenPre<'l>(
6265    mut env: JNIEnv<'l>,
6266    _class: JClass<'l>,
6267    player: JString<'l>,
6268    player_uuid: JString<'l>,
6269    dimension: JString<'l>,
6270) -> jni::sys::jboolean {
6271    let h = handlers();
6272    if h.container_open.is_empty() {
6273        return 1;
6274    }
6275    let p = match env.get_string(&player) {
6276        Ok(s) => String::from(s),
6277        Err(_) => return 1,
6278    };
6279    let pu = match env.get_string(&player_uuid) {
6280        Ok(s) => String::from(s),
6281        Err(_) => return 1,
6282    };
6283    let d = match env.get_string(&dimension) {
6284        Ok(s) => String::from(s),
6285        Err(_) => return 1,
6286    };
6287    let ev = YogContainerOpenEvent {
6288        player: YogStr::from_str(&p),
6289        player_uuid: YogStr::from_str(&pu),
6290        container_type: YogStr::EMPTY,
6291        dimension: YogStr::from_str(&d),
6292    };
6293    let srv = srv_ptr();
6294    let mut allow = true;
6295    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6296        for (module, ud, f) in &h.container_open {
6297            if module.is_retiring() {
6298                continue;
6299            }
6300            let Some(_call) = module.enter() else {
6301                continue;
6302            };
6303            if !unsafe { f(*ud, srv, &ev, 0) } {
6304                allow = false;
6305                break;
6306            }
6307        }
6308    }))
6309    .ok();
6310    allow as jni::sys::jboolean
6311}
6312
6313#[no_mangle]
6314pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpen<'l>(
6315    mut env: JNIEnv<'l>,
6316    _class: JClass<'l>,
6317    player: JString<'l>,
6318    player_uuid: JString<'l>,
6319    container_type: JString<'l>,
6320    dimension: JString<'l>,
6321) {
6322    let h = handlers();
6323    if h.container_open.is_empty() {
6324        return;
6325    }
6326    let (p, pu, ct, d) = (
6327        jstr!(env, player),
6328        jstr!(env, player_uuid),
6329        jstr!(env, container_type),
6330        jstr!(env, dimension),
6331    );
6332    let ev = YogContainerOpenEvent {
6333        player: YogStr::from_str(&p),
6334        player_uuid: YogStr::from_str(&pu),
6335        container_type: YogStr::from_str(&ct),
6336        dimension: YogStr::from_str(&d),
6337    };
6338    let srv = srv_ptr();
6339    guard("on_container_open", || {
6340        for (module, ud, f) in &h.container_open {
6341            if module.is_retiring() {
6342                continue;
6343            }
6344            let Some(_call) = module.enter() else {
6345                continue;
6346            };
6347            unsafe { f(*ud, srv, &ev, 1) };
6348        }
6349    });
6350}
6351
6352#[no_mangle]
6353pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerClose<'l>(
6354    mut env: JNIEnv<'l>,
6355    _class: JClass<'l>,
6356    player: JString<'l>,
6357    player_uuid: JString<'l>,
6358    dimension: JString<'l>,
6359) {
6360    let h = handlers();
6361    if h.container_close.is_empty() {
6362        return;
6363    }
6364    let (p, pu, d) = (
6365        jstr!(env, player),
6366        jstr!(env, player_uuid),
6367        jstr!(env, dimension),
6368    );
6369    let ev = YogContainerCloseEvent {
6370        player: YogStr::from_str(&p),
6371        player_uuid: YogStr::from_str(&pu),
6372        dimension: YogStr::from_str(&d),
6373    };
6374    let srv = srv_ptr();
6375    guard("on_container_close", || {
6376        for (module, ud, f) in &h.container_close {
6377            if module.is_retiring() {
6378                continue;
6379            }
6380            let Some(_call) = module.enter() else {
6381                continue;
6382            };
6383            unsafe { f(*ud, srv, &ev, 1) };
6384        }
6385    });
6386}
6387
6388#[no_mangle]
6389pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHitPre<'l>(
6390    mut env: JNIEnv<'l>,
6391    _class: JClass<'l>,
6392    projectile_type: JString<'l>,
6393    projectile_uuid: JString<'l>,
6394    shooter_uuid: JString<'l>,
6395    hit_type: JString<'l>,
6396    hit_entity_uuid: JString<'l>,
6397    x: jdouble,
6398    y: jdouble,
6399    z: jdouble,
6400    dimension: JString<'l>,
6401) -> jni::sys::jboolean {
6402    let h = handlers();
6403    if h.projectile_hit.is_empty() {
6404        return 1;
6405    }
6406    let pt = match env.get_string(&projectile_type) {
6407        Ok(s) => String::from(s),
6408        Err(_) => return 1,
6409    };
6410    let pu = match env.get_string(&projectile_uuid) {
6411        Ok(s) => String::from(s),
6412        Err(_) => return 1,
6413    };
6414    let su = match env.get_string(&shooter_uuid) {
6415        Ok(s) => String::from(s),
6416        Err(_) => return 1,
6417    };
6418    let ht = match env.get_string(&hit_type) {
6419        Ok(s) => String::from(s),
6420        Err(_) => return 1,
6421    };
6422    let heu = match env.get_string(&hit_entity_uuid) {
6423        Ok(s) => String::from(s),
6424        Err(_) => return 1,
6425    };
6426    let dim = match env.get_string(&dimension) {
6427        Ok(s) => String::from(s),
6428        Err(_) => return 1,
6429    };
6430    let ev = YogProjectileHitEvent {
6431        projectile_type: YogStr::from_str(&pt),
6432        projectile_uuid: YogStr::from_str(&pu),
6433        shooter_uuid: YogStr::from_str(&su),
6434        hit_type: YogStr::from_str(&ht),
6435        hit_entity_uuid: YogStr::from_str(&heu),
6436        x,
6437        y,
6438        z,
6439        dimension: YogStr::from_str(&dim),
6440    };
6441    let srv = srv_ptr();
6442    let mut allow = true;
6443    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6444        for (module, ud, f) in &h.projectile_hit {
6445            if module.is_retiring() {
6446                continue;
6447            }
6448            let Some(_call) = module.enter() else {
6449                continue;
6450            };
6451            if !unsafe { f(*ud, srv, &ev, 0) } {
6452                allow = false;
6453                break;
6454            }
6455        }
6456    }))
6457    .ok();
6458    allow as jni::sys::jboolean
6459}
6460
6461#[no_mangle]
6462pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHit<'l>(
6463    mut env: JNIEnv<'l>,
6464    _class: JClass<'l>,
6465    projectile_type: JString<'l>,
6466    projectile_uuid: JString<'l>,
6467    shooter_uuid: JString<'l>,
6468    hit_type: JString<'l>,
6469    hit_entity_uuid: JString<'l>,
6470    x: jdouble,
6471    y: jdouble,
6472    z: jdouble,
6473    dimension: JString<'l>,
6474) {
6475    let h = handlers();
6476    if h.projectile_hit.is_empty() {
6477        return;
6478    }
6479    let (pt, pu) = (jstr!(env, projectile_type), jstr!(env, projectile_uuid));
6480    let (su, ht) = (jstr!(env, shooter_uuid), jstr!(env, hit_type));
6481    let (heu, dim) = (jstr!(env, hit_entity_uuid), jstr!(env, dimension));
6482    let ev = YogProjectileHitEvent {
6483        projectile_type: YogStr::from_str(&pt),
6484        projectile_uuid: YogStr::from_str(&pu),
6485        shooter_uuid: YogStr::from_str(&su),
6486        hit_type: YogStr::from_str(&ht),
6487        hit_entity_uuid: YogStr::from_str(&heu),
6488        x,
6489        y,
6490        z,
6491        dimension: YogStr::from_str(&dim),
6492    };
6493    let srv = srv_ptr();
6494    guard("on_projectile_hit", || {
6495        for (module, ud, f) in &h.projectile_hit {
6496            if module.is_retiring() {
6497                continue;
6498            }
6499            let Some(_call) = module.enter() else {
6500                continue;
6501            };
6502            unsafe { f(*ud, srv, &ev, 1) };
6503        }
6504    });
6505}
6506
6507// ── ABI minor 10 — client-side JNI entry points ───────────────────────────────
6508
6509#[no_mangle]
6510pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientTick<'l>(
6511    _env: JNIEnv<'l>,
6512    _class: JClass<'l>,
6513) {
6514    let h = handlers();
6515    if h.client_tick.is_empty() {
6516        return;
6517    }
6518    guard("on_client_tick", || {
6519        for (module, ud, f) in &h.client_tick {
6520            if module.is_retiring() {
6521                continue;
6522            }
6523            let Some(_call) = module.enter() else {
6524                continue;
6525            };
6526            unsafe { f(*ud) };
6527        }
6528    });
6529}
6530
6531#[no_mangle]
6532pub extern "system" fn Java_dev_yog_NativeBridge_nativeGlInit<'l>(
6533    _env: JNIEnv<'l>,
6534    _class: JClass<'l>,
6535) {
6536    if GL.get().is_some() {
6537        return;
6538    }
6539    let mut raw_get_binary: usize = 0;
6540    let mut raw_prog_binary: usize = 0;
6541    let gl = unsafe {
6542        glow::Context::from_loader_function(|sym| {
6543            let Some(mut env) = get_env() else {
6544                return std::ptr::null();
6545            };
6546            let jsym = match env.new_string(sym) {
6547                Ok(s) => s,
6548                Err(_) => return std::ptr::null(),
6549            };
6550            let jsym_obj: JObject = jsym.into();
6551            let val = env.call_static_method(
6552                "dev/yog/NativeBridge",
6553                "glProcAddress",
6554                "(Ljava/lang/String;)J",
6555                &[JValue::Object(&jsym_obj)],
6556            );
6557            let ptr = match val.and_then(|v| v.j()) {
6558                Ok(p) if p != 0 => p as usize as *const _,
6559                _ => std::ptr::null(),
6560            };
6561            // Capture extension pointers while the loader runs.
6562            match sym {
6563                "glGetProgramBinary" => raw_get_binary = ptr as usize,
6564                "glProgramBinary" => raw_prog_binary = ptr as usize,
6565                _ => {}
6566            }
6567            ptr
6568        })
6569    };
6570    let _ = GL.set(GlCtx(gl));
6571    let _ = GL_GET_PROGRAM_BINARY.set(if raw_get_binary != 0 {
6572        Some(raw_get_binary)
6573    } else {
6574        None
6575    });
6576    let _ = GL_PROGRAM_BINARY.set(if raw_prog_binary != 0 {
6577        Some(raw_prog_binary)
6578    } else {
6579        None
6580    });
6581    // `glGetProgramiv` is a core function; always available.  We look it up once here
6582    // to avoid depending on glow internals for the PROGRAM_BINARY_LENGTH query.
6583    if let Some(mut env) = get_env() {
6584        if let Ok(jsym) = env.new_string("glGetProgramiv") {
6585            let jsym_obj: JObject = jsym.into();
6586            if let Ok(jv) = env.call_static_method(
6587                "dev/yog/NativeBridge",
6588                "glProcAddress",
6589                "(Ljava/lang/String;)J",
6590                &[JValue::Object(&jsym_obj)],
6591            ) {
6592                if let Ok(ptr) = jv.j() {
6593                    let _ = GL_GET_PROGRAM_IV.set(if ptr != 0 { Some(ptr as usize) } else { None });
6594                }
6595            }
6596        }
6597    }
6598}
6599
6600#[no_mangle]
6601pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnHudRender<'l>(
6602    _env: JNIEnv<'l>,
6603    _class: JClass<'l>,
6604    delta_tick: jfloat,
6605    screen_w: jint,
6606    screen_h: jint,
6607    scale_factor: jfloat,
6608    player_x: jfloat,
6609    player_y: jfloat,
6610    player_z: jfloat,
6611) {
6612    let h = handlers();
6613    let mut gfx = GFX_FN_TABLE;
6614    gfx.screen_w = screen_w;
6615    gfx.screen_h = screen_h;
6616    gfx.delta_tick = delta_tick;
6617    gfx.scale_factor = scale_factor;
6618    gfx.player_pos = [player_x, player_y, player_z];
6619
6620    // Mod hud_render callbacks.
6621    if !h.hud_render.is_empty() {
6622        guard("on_hud_render", || {
6623            for (module, ud, f) in &h.hud_render {
6624                if module.is_retiring() {
6625                    continue;
6626                }
6627                let Some(_call) = module.enter() else {
6628                    continue;
6629                };
6630                unsafe { f(*ud, &gfx) };
6631            }
6632        });
6633    }
6634
6635    // Render active book UIs.
6636    let active_layers: Vec<UiLayer> = h.active_uis.lock().unwrap().clone();
6637    let sw = screen_w as f32;
6638    let sh = screen_h as f32;
6639    let ctx = unsafe { yog_gfx::GfxContext::from_raw(&gfx as *const _) };
6640    let mut renderers = h.book_renderers.lock().unwrap();
6641    for layer in &active_layers {
6642        if !layer.visible {
6643            continue;
6644        }
6645        if let Some(renderer) = renderers.get_mut(&layer.id) {
6646            renderer.render(&ctx, sw, sh);
6647        }
6648    }
6649}
6650
6651#[no_mangle]
6652pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnWorldRender<'l>(
6653    env: JNIEnv<'l>,
6654    _class: JClass<'l>,
6655    delta_tick: jfloat,
6656    screen_w: jint,
6657    screen_h: jint,
6658    scale_factor: jfloat,
6659    view_proj_arr: JFloatArray<'l>,
6660    cam_x: jfloat,
6661    cam_y: jfloat,
6662    cam_z: jfloat,
6663    player_x: jfloat,
6664    player_y: jfloat,
6665    player_z: jfloat,
6666) {
6667    let h = handlers();
6668    if h.world_render.is_empty() {
6669        return;
6670    }
6671    let mut view_proj = [0f32; 16];
6672    if env
6673        .get_float_array_region(&view_proj_arr, 0, &mut view_proj)
6674        .is_err()
6675    {
6676        return;
6677    }
6678    let mut gfx = GFX_FN_TABLE;
6679    gfx.screen_w = screen_w;
6680    gfx.screen_h = screen_h;
6681    gfx.delta_tick = delta_tick;
6682    gfx.scale_factor = scale_factor;
6683    gfx.view_proj = view_proj;
6684    gfx.camera_pos = [cam_x, cam_y, cam_z];
6685    gfx.player_pos = [player_x, player_y, player_z];
6686    guard("on_world_render", || {
6687        for (module, ud, f) in &h.world_render {
6688            if module.is_retiring() {
6689                continue;
6690            }
6691            let Some(_call) = module.enter() else {
6692                continue;
6693            };
6694            unsafe { f(*ud, &gfx) };
6695        }
6696    });
6697}
6698
6699#[no_mangle]
6700pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnKeyPress<'l>(
6701    _env: JNIEnv<'l>,
6702    _class: JClass<'l>,
6703    key_code: jint,
6704    scan_code: jint,
6705    action: jint,
6706    modifiers: jint,
6707) -> jni::sys::jboolean {
6708    let h = handlers();
6709    if h.key_press.is_empty() {
6710        return 1;
6711    }
6712    let ev = YogKeyPressEvent {
6713        key_code,
6714        scan_code,
6715        action,
6716        modifiers,
6717    };
6718    let mut allow = true;
6719    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6720        for (module, ud, f) in &h.key_press {
6721            if module.is_retiring() {
6722                continue;
6723            }
6724            let Some(_call) = module.enter() else {
6725                continue;
6726            };
6727            if !unsafe { f(*ud, &ev) } {
6728                allow = false;
6729                break;
6730            }
6731        }
6732    }))
6733    .ok();
6734    allow as jni::sys::jboolean
6735}
6736
6737#[no_mangle]
6738pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenOpen<'l>(
6739    mut env: JNIEnv<'l>,
6740    _class: JClass<'l>,
6741    screen_class: JString<'l>,
6742) {
6743    let h = handlers();
6744    if h.screen_open.is_empty() {
6745        return;
6746    }
6747    let sc = match env.get_string(&screen_class) {
6748        Ok(s) => String::from(s),
6749        Err(_) => return,
6750    };
6751    guard("on_screen_open", || {
6752        for (module, ud, f) in &h.screen_open {
6753            if module.is_retiring() {
6754                continue;
6755            }
6756            let Some(_call) = module.enter() else {
6757                continue;
6758            };
6759            unsafe { f(*ud, YogStr::from_str(&sc)) };
6760        }
6761    });
6762}
6763
6764#[no_mangle]
6765pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenClose<'l>(
6766    mut env: JNIEnv<'l>,
6767    _class: JClass<'l>,
6768    screen_class: JString<'l>,
6769) {
6770    let h = handlers();
6771    if h.screen_close.is_empty() {
6772        return;
6773    }
6774    let sc = match env.get_string(&screen_class) {
6775        Ok(s) => String::from(s),
6776        Err(_) => return,
6777    };
6778    guard("on_screen_close", || {
6779        for (module, ud, f) in &h.screen_close {
6780            if module.is_retiring() {
6781                continue;
6782            }
6783            let Some(_call) = module.enter() else {
6784                continue;
6785            };
6786            unsafe { f(*ud, YogStr::from_str(&sc)) };
6787        }
6788    });
6789}
6790
6791mod client_api;
6792mod control_socket;
6793mod images;
6794mod ui_jni;