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_mc_tex(
2680    id: YogStr,
2681    x: f32,
2682    y: f32,
2683    u0: f32,
2684    v0: f32,
2685    w: f32,
2686    h: f32,
2687    tw: f32,
2688    th: f32,
2689) {
2690    let Some(mut env) = get_env() else { return };
2691    if let Some(ji) = ys_to_java(&mut env, id) {
2692        if env
2693            .call_static_method(
2694                "dev/yog/NativeDraw",
2695                "drawTexture",
2696                // x, y, u0, v0, w, h, tw, th — eight floats. (Nine here made
2697                // every call fail jni-rs's argument-count check before reaching
2698                // Java, so no texture was ever drawn.)
2699                "(Ljava/lang/String;FFFFFFFF)V",
2700                &[
2701                    JValue::Object(&ji),
2702                    JValue::Float(x),
2703                    JValue::Float(y),
2704                    JValue::Float(u0),
2705                    JValue::Float(v0),
2706                    JValue::Float(w),
2707                    JValue::Float(h),
2708                    JValue::Float(tw),
2709                    JValue::Float(th),
2710                ],
2711            )
2712            .is_err()
2713        {
2714            env.exception_clear().ok();
2715        }
2716    }
2717}
2718
2719unsafe extern "C" fn gfx_draw2d_item(id: YogStr, x: f32, y: f32, size: f32) {
2720    let Some(mut env) = get_env() else { return };
2721    if let Some(ji) = ys_to_java(&mut env, id) {
2722        if env
2723            .call_static_method(
2724                "dev/yog/NativeDraw",
2725                "drawItem",
2726                "(Ljava/lang/String;FFF)V",
2727                &[
2728                    JValue::Object(&ji),
2729                    JValue::Float(x),
2730                    JValue::Float(y),
2731                    JValue::Float(size),
2732                ],
2733            )
2734            .is_err()
2735        {
2736            env.exception_clear().ok();
2737        }
2738    }
2739}
2740
2741// ── Static GFX function table (function pointers only — per-frame data filled at call time) ──
2742
2743static GFX_FN_TABLE: YogGfxApi = YogGfxApi {
2744    // Per-frame fields zeroed in the static; actual values are set on the stack per render call.
2745    screen_w: 0,
2746    screen_h: 0,
2747    delta_tick: 0.0,
2748    scale_factor: 1.0,
2749    view_proj: [0.0; 16],
2750    camera_pos: [0.0; 3],
2751    player_pos: [0.0; 3],
2752    _pad1: 0.0,
2753    buf_create: gfx_buf_create,
2754    buf_delete: gfx_buf_delete,
2755    buf_data: gfx_buf_data,
2756    buf_subdata: gfx_buf_subdata,
2757    vao_create: gfx_vao_create,
2758    vao_delete: gfx_vao_delete,
2759    vao_attrib: gfx_vao_attrib,
2760    vao_set_ebo: gfx_vao_set_ebo,
2761    prog_create: gfx_prog_create,
2762    prog_delete: gfx_prog_delete,
2763    prog_uniform_1i: gfx_prog_uniform_1i,
2764    prog_uniform_1f: gfx_prog_uniform_1f,
2765    prog_uniform_2f: gfx_prog_uniform_2f,
2766    prog_uniform_3f: gfx_prog_uniform_3f,
2767    prog_uniform_4f: gfx_prog_uniform_4f,
2768    prog_uniform_mat4: gfx_prog_uniform_mat4,
2769    tex_create: gfx_tex_create,
2770    tex_delete: gfx_tex_delete,
2771    tex_bind: gfx_tex_bind,
2772    tex_from_mc: gfx_tex_from_mc,
2773    draw_arrays: gfx_draw_arrays,
2774    draw_elements: gfx_draw_elements,
2775    set_blend: gfx_set_blend,
2776    set_depth: gfx_set_depth,
2777    set_scissor: gfx_set_scissor,
2778    clear_scissor: gfx_clear_scissor,
2779    set_viewport: gfx_set_viewport,
2780    draw2d_rect: gfx_draw2d_rect,
2781    draw2d_gradient: gfx_draw2d_gradient,
2782    draw2d_text: gfx_draw2d_text,
2783    draw2d_mc_tex: gfx_draw2d_mc_tex,
2784    draw2d_item: gfx_draw2d_item,
2785    draw2d_text_font: gfx_draw2d_text_font,
2786    text_width: gfx_text_width,
2787    draw2d_image: images::gfx_draw2d_image,
2788    image_size: images::gfx_image_size,
2789};
2790
2791// ── YogApi registration functions ─────────────────────────────────────────────
2792//
2793// ctx is *const RwLock<RuntimeHandlers> (cast from *mut c_void) — see
2794// `current_registration()` for how each entry gets tagged with the
2795// `LoadedModule` that's registering it.
2796
2797macro_rules! api_event {
2798    ($name:ident, $field:ident, $fn_ty:ty) => {
2799        unsafe extern "C" fn $name(ctx: *mut c_void, ud: *mut c_void, h: $fn_ty) {
2800            let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2801            let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2802            handlers.$field.push((current_registration(), ud, h));
2803        }
2804    };
2805}
2806
2807api_event!(api_on_block_break, block_break, YogBlockBreakFn);
2808api_event!(api_on_chat, chat, YogChatFn);
2809api_event!(api_on_player_join, player_join, YogPlayerFn);
2810api_event!(api_on_player_leave, player_leave, YogPlayerFn);
2811api_event!(api_on_use_item, use_item, YogUseItemFn);
2812api_event!(api_on_use_block, use_block, YogUseBlockFn);
2813api_event!(api_on_attack_entity, attack_entity, YogAttackEntityFn);
2814api_event!(api_on_entity_damage, entity_damage, YogEntityDamageFn);
2815api_event!(api_on_entity_death, entity_death, YogEntityDeathFn);
2816api_event!(api_on_entity_spawn, entity_spawn, YogEntitySpawnFn);
2817api_event!(
2818    api_on_player_place_block,
2819    player_place_block,
2820    YogPlaceBlockFn
2821);
2822api_event!(api_on_player_death, player_death, YogPlayerDeathFn);
2823api_event!(api_on_player_respawn, player_respawn, YogPlayerRespawnFn);
2824api_event!(api_on_advancement, advancement, YogAdvancementFn);
2825api_event!(api_on_entity_interact, entity_interact, YogEntityInteractFn);
2826api_event!(api_on_item_craft, item_craft, YogCraftFn);
2827api_event!(api_on_explosion, explosion, YogExplosionFn);
2828api_event!(api_on_item_pickup, item_pickup, YogItemPickupFn);
2829api_event!(api_on_player_move, player_move, YogPlayerMoveFn);
2830api_event!(api_on_container_open, container_open, YogContainerOpenFn);
2831api_event!(api_on_container_close, container_close, YogContainerCloseFn);
2832api_event!(api_on_projectile_hit, projectile_hit, YogProjectileHitFn);
2833api_event!(api_on_client_tick, client_tick, YogClientFn);
2834api_event!(api_on_hud_render, hud_render, YogHudRenderFn);
2835api_event!(api_on_world_render, world_render, YogWorldRenderFn);
2836api_event!(api_on_key_press, key_press, YogKeyPressFn);
2837api_event!(api_on_screen_open, screen_open, YogScreenFn);
2838api_event!(api_on_screen_close, screen_close, YogScreenFn);
2839api_event!(api_on_server_tick, server_tick, YogServerFn);
2840api_event!(api_on_server_started, server_started, YogServerFn);
2841api_event!(api_on_server_stopping, server_stopping, YogServerFn);
2842
2843unsafe extern "C" fn api_on_packet(
2844    ctx: *mut c_void,
2845    channel: YogStr,
2846    ud: *mut c_void,
2847    h: YogPacketFn,
2848) {
2849    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2850    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2851    handlers
2852        .packets
2853        .insert(channel.as_str().to_owned(), (current_registration(), ud, h));
2854}
2855
2856unsafe extern "C" fn api_on_client_packet(
2857    ctx: *mut c_void,
2858    channel: YogStr,
2859    ud: *mut c_void,
2860    h: YogPacketFn,
2861) {
2862    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2863    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2864    handlers
2865        .client_packets
2866        .insert(channel.as_str().to_owned(), (current_registration(), ud, h));
2867}
2868
2869unsafe extern "C" fn api_register_command(
2870    ctx: *mut c_void,
2871    name: YogStr,
2872    ud: *mut c_void,
2873    h: YogCommandFn,
2874) {
2875    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2876    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2877    handlers
2878        .commands
2879        .entry(name.as_str().to_owned())
2880        .or_default()
2881        .push((current_registration(), None, ud, h));
2882}
2883
2884unsafe extern "C" fn api_register_typed_command(
2885    ctx: *mut c_void,
2886    name: YogStr,
2887    schema: YogStr,
2888    ud: *mut c_void,
2889    h: YogCommandFn,
2890) {
2891    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2892    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2893    let n = name.as_str().to_owned();
2894    handlers.commands.entry(n).or_default().push((
2895        current_registration(),
2896        Some(schema.as_str().to_owned()),
2897        ud,
2898        h,
2899    ));
2900}
2901
2902unsafe extern "C" fn api_register_recipe_json(
2903    ctx: *mut c_void,
2904    namespace: YogStr,
2905    name: YogStr,
2906    json: YogStr,
2907) {
2908    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2909    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2910    let ns = namespace.as_str().to_owned();
2911    let n = name.as_str().to_owned();
2912    let j = json.as_str().to_owned();
2913    // Feed the recipe to already-registered book renderers (crafting pages).
2914    let full_id = format!("{}:{}", ns, n);
2915    for r in handlers.book_renderers.lock().unwrap().values_mut() {
2916        r.add_recipe(full_id.clone(), &j);
2917    }
2918    handlers.recipes.push((ns, n, j));
2919}
2920
2921unsafe extern "C" fn api_register_item(ctx: *mut c_void, def: *const YogItemDef) {
2922    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2923    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2924    let d = &*def;
2925    let food = if d.food_nutrition > 0 {
2926        Some(FoodDef {
2927            nutrition: d.food_nutrition,
2928            saturation: d.food_saturation,
2929            can_always_eat: d.food_always_eat,
2930        })
2931    } else {
2932        None
2933    };
2934    handlers.items.push(ItemDef {
2935        id: d.id.as_str().to_owned(),
2936        max_stack: d.max_stack as u8,
2937        name: if d.name.is_empty() {
2938            None
2939        } else {
2940            Some(d.name.as_str().to_owned())
2941        },
2942        tooltip: if d.tooltip.is_empty() {
2943            None
2944        } else {
2945            Some(d.tooltip.as_str().to_owned())
2946        },
2947        max_damage: d.max_damage,
2948        fire_resistant: d.fire_resistant,
2949        fuel_ticks: d.fuel_ticks,
2950        food,
2951    });
2952}
2953
2954unsafe extern "C" fn api_register_block(ctx: *mut c_void, def: *const YogBlockDef) {
2955    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
2956    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
2957    let d = &*def;
2958    handlers.blocks.push(BlockDef {
2959        id: d.id.as_str().to_owned(),
2960        hardness: d.hardness,
2961        resistance: d.resistance,
2962        name: if d.name.is_empty() {
2963            None
2964        } else {
2965            Some(d.name.as_str().to_owned())
2966        },
2967        light_level: d.light_level,
2968        sound: if d.sound.is_empty() {
2969            None
2970        } else {
2971            Some(d.sound.as_str().to_owned())
2972        },
2973        requires_tool: d.requires_tool,
2974        no_collision: d.no_collision,
2975        slipperiness: d.slipperiness,
2976        shape: if d.shape == [0.0f32; 6] {
2977            None
2978        } else {
2979            Some(d.shape)
2980        },
2981        connects: d.connects,
2982        connect_groups: if d.connect_groups.is_empty() {
2983            Vec::new()
2984        } else {
2985            d.connect_groups
2986                .as_str()
2987                .split(',')
2988                .map(str::to_owned)
2989                .collect()
2990        },
2991        inventory_id: if d.inventory_id.is_empty() {
2992            None
2993        } else {
2994            Some(d.inventory_id.as_str().to_owned())
2995        },
2996    });
2997}
2998
2999unsafe extern "C" fn api_register_inventory(
3000    ctx: *mut c_void,
3001    def: *const yog_abi::YogInventoryDef,
3002) {
3003    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3004    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3005    let d = &*def;
3006    handlers.inventories.push(yog_inventory::InventoryDef {
3007        id: d.id.as_str().to_owned(),
3008        slot_count: d.slot_count as usize,
3009        layout: yog_inventory::decode_layout(d.layout.as_str()),
3010        include_player_inventory: d.include_player_inventory,
3011        player_inv_offset: (d.player_inv_x, d.player_inv_y),
3012        background_texture: if d.background_texture.is_empty() {
3013            None
3014        } else {
3015            Some(d.background_texture.as_str().to_owned())
3016        },
3017        title: d.title.as_str().to_owned(),
3018        background_size: if d.background_w > 0.0 && d.background_h > 0.0 {
3019            Some((d.background_w, d.background_h))
3020        } else {
3021            None
3022        },
3023    });
3024}
3025
3026unsafe extern "C" fn api_schedule_once(
3027    ctx: *mut c_void,
3028    delay_ticks: u64,
3029    ud: *mut c_void,
3030    h: YogScheduledFn,
3031) {
3032    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3033    let handlers = handlers_lock.write().expect("handlers lock poisoned");
3034    handlers
3035        .scheduler
3036        .lock()
3037        .expect("scheduler poisoned")
3038        .once_tasks
3039        .push(OnceTask {
3040            module: current_registration(),
3041            delay_remaining: delay_ticks,
3042            ud,
3043            f: h,
3044        });
3045}
3046
3047unsafe extern "C" fn api_schedule_repeating(
3048    ctx: *mut c_void,
3049    period_ticks: u64,
3050    ud: *mut c_void,
3051    h: YogScheduledFn,
3052) {
3053    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3054    let handlers = handlers_lock.write().expect("handlers lock poisoned");
3055    handlers
3056        .scheduler
3057        .lock()
3058        .expect("scheduler poisoned")
3059        .repeating_tasks
3060        .push(RepeatingTask {
3061            module: current_registration(),
3062            period: period_ticks,
3063            ticks_left: period_ticks,
3064            ud,
3065            f: h,
3066        });
3067}
3068
3069unsafe extern "C" fn api_register_startup_grant(
3070    ctx: *mut c_void,
3071    grant: *const YogStartupGrantDef,
3072) {
3073    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3074    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3075    let g = &*grant;
3076    let items: Vec<String> = if g.items.is_empty() {
3077        Vec::new()
3078    } else {
3079        unsafe {
3080            g.items
3081                .as_str()
3082                .split('|')
3083                .map(|s: &str| s.to_owned())
3084                .collect()
3085        }
3086    };
3087    let book = if g.book.is_empty() {
3088        None
3089    } else {
3090        Some(unsafe { g.book.as_str().to_owned() })
3091    };
3092    let command = if g.command.is_empty() {
3093        None
3094    } else {
3095        Some(unsafe { g.command.as_str().to_owned() })
3096    };
3097    handlers.startup_grants.push(yog_registry::StartupGrant {
3098        id: unsafe { g.id.as_str().to_owned() },
3099        items,
3100        book,
3101        command,
3102    });
3103}
3104
3105unsafe extern "C" fn api_register_book(ctx: *mut c_void, book_id: YogStr, book_json: YogStr) {
3106    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3107    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3108    let id = unsafe { book_id.as_str().to_owned() };
3109    let json = unsafe { book_json.as_str().to_owned() };
3110    handlers.books.insert(id.clone(), json.clone());
3111    // Parse JSON → Book → BookRenderer so rendering works without Java round-trip.
3112    match serde_json::from_str::<yog_book::Book>(&json) {
3113        Ok(book) => {
3114            let mut renderer = yog_book::BookRenderer::new(book);
3115            // Recipes may register before the book — replay them into the renderer.
3116            for (ns, name, j) in &handlers.recipes {
3117                renderer.add_recipe(format!("{}:{}", ns, name), j);
3118            }
3119            handlers.book_renderers.lock().unwrap().insert(id, renderer);
3120        }
3121        Err(e) => {
3122            yog_logging::warn!(
3123                "book '{}': failed to parse JSON for Rust renderer: {}",
3124                id,
3125                e
3126            );
3127        }
3128    }
3129}
3130
3131unsafe extern "C" fn api_register_dimension_json(ctx: *mut c_void, id: YogStr, json: YogStr) {
3132    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3133    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3134    let id = unsafe { id.as_str().to_owned() };
3135    let json = unsafe { json.as_str().to_owned() };
3136    yog_logging::info!("registered dimension type: {}", id);
3137    handlers.dimensions.insert(id, json);
3138}
3139
3140unsafe extern "C" fn api_register_chunk_generator(
3141    ctx: *mut c_void,
3142    id: YogStr,
3143    ud: *mut c_void,
3144    h: yog_abi::YogChunkGeneratorFn,
3145) {
3146    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3147    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3148    let id = unsafe { id.as_str().to_owned() };
3149    yog_logging::info!("registered chunk generator for dimension: {}", id);
3150    handlers
3151        .chunk_generators
3152        .insert(id, (current_registration(), ud, h));
3153}
3154
3155unsafe extern "C" fn api_register_ui(
3156    ctx: *mut c_void,
3157    ui_id: YogStr,
3158    _layout_json: YogStr,
3159    ud: *mut c_void,
3160    h: yog_abi::YogUIEventFn,
3161) {
3162    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3163    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3164    let id = unsafe { ui_id.as_str().to_owned() };
3165    handlers
3166        .ui_handlers
3167        .insert(id.clone(), (current_registration(), ud, h));
3168    yog_logging::info!("registered UI handler: {}", id);
3169}
3170
3171unsafe extern "C" fn api_on_ui_render(
3172    ctx: *mut c_void,
3173    ui_id: YogStr,
3174    ud: *mut c_void,
3175    h: YogHudRenderFn,
3176) {
3177    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3178    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3179    let id = unsafe { ui_id.as_str().to_owned() };
3180    handlers
3181        .ui_render_handlers
3182        .entry(id)
3183        .or_default()
3184        .push((current_registration(), ud, h));
3185}
3186
3187/// Strip TSV separators so one mod can't corrupt the line format.
3188fn tsv_clean(v: &str) -> String {
3189    v.replace(['\t', '\n', '\r'], " ")
3190}
3191
3192unsafe extern "C" fn api_ui_open(_ctx: *mut c_void, ui_id: YogStr, modal: bool, pause: bool) {
3193    let id = ui_id.as_str().to_string();
3194    if id.is_empty() {
3195        return;
3196    }
3197    let Some(mut env) = get_env() else { return };
3198    let Ok(jid) = env.new_string(&id) else { return };
3199    let jid_obj: JObject = jid.into();
3200    // Java side schedules onto the render thread; no-op on dedicated servers.
3201    if env
3202        .call_static_method(
3203            "dev/yog/NativeBridge",
3204            "openUI",
3205            "(Ljava/lang/String;ZZ)V",
3206            &[
3207                JValue::Object(&jid_obj),
3208                JValue::Bool(modal as u8),
3209                JValue::Bool(pause as u8),
3210            ],
3211        )
3212        .is_err()
3213    {
3214        env.exception_clear().ok();
3215    }
3216}
3217
3218unsafe extern "C" fn api_ui_close(_ctx: *mut c_void, ui_id: YogStr) {
3219    let id = ui_id.as_str().to_string();
3220    let Some(mut env) = get_env() else { return };
3221    let Ok(jid) = env.new_string(&id) else { return };
3222    let jid_obj: JObject = jid.into();
3223    // Java side defers onto the render thread (after the current event) and
3224    // checks the open screen is that Yog UI; no-op on dedicated servers.
3225    if env
3226        .call_static_method(
3227            "dev/yog/NativeBridge",
3228            "closeUI",
3229            "(Ljava/lang/String;)V",
3230            &[JValue::Object(&jid_obj)],
3231        )
3232        .is_err()
3233    {
3234        env.exception_clear().ok();
3235    }
3236}
3237
3238unsafe extern "C" fn api_ui_consume_event(_ctx: *mut c_void) {
3239    ui_jni::consume_event();
3240}
3241
3242unsafe extern "C" fn api_translate(_ctx: *mut c_void, key: YogStr) -> YogOwnedStr {
3243    translate(key.as_str()).map_or(YogOwnedStr::NONE, YogOwnedStr::from_string)
3244}
3245
3246/// The game's text for translation `key` in the current language — `None`
3247/// when no lang file has it (or there's no JVM).
3248fn translate(key: &str) -> Option<String> {
3249    if key.is_empty() {
3250        return None;
3251    }
3252    let mut env = get_env()?;
3253    let jkey: JObject = env.new_string(key).ok()?.into();
3254    let result = env.call_static_method(
3255        "dev/yog/NativeBridge",
3256        "translate",
3257        "(Ljava/lang/String;)Ljava/lang/String;",
3258        &[JValue::Object(&jkey)],
3259    );
3260    let text = match result.and_then(|v| v.l()) {
3261        Ok(obj) if !obj.as_raw().is_null() => env.get_string(&obj.into()).ok().map(String::from),
3262        Ok(_) => None,
3263        Err(_) => {
3264            env.exception_clear().ok();
3265            None
3266        }
3267    };
3268    let _ = env.delete_local_ref(jkey);
3269    text
3270}
3271
3272unsafe extern "C" fn api_mods_list(_ctx: *mut c_void) -> YogOwnedStr {
3273    let mut lines: Vec<String> = Vec::new();
3274    let infos = MOD_INFOS.lock().expect("mod infos lock poisoned").clone();
3275    for m in &infos {
3276        // A `.yres` name/description shows in the player's language.
3277        let localized = |text: &str, key: &str| {
3278            translate(key).map_or_else(|| text.to_string(), |t| tsv_clean(&t))
3279        };
3280        lines.push(format!(
3281            "yog\t{}\t{}\t{}\t{}\t{}",
3282            m[0],
3283            localized(&m[1], &m[5]),
3284            m[2],
3285            m[3],
3286            localized(&m[4], &m[6])
3287        ));
3288    }
3289    // Loader-side (Java) mods, if the host provides them.
3290    if let Some(mut env) = get_env() {
3291        if let Ok(val) = env.call_static_method(
3292            "dev/yog/NativeBridge",
3293            "listPlatformMods",
3294            "()Ljava/lang/String;",
3295            &[],
3296        ) {
3297            if let Ok(obj) = val.l() {
3298                if !obj.as_raw().is_null() {
3299                    if let Ok(js) = env.get_string(&obj.into()) {
3300                        for line in String::from(js).lines() {
3301                            if !line.trim().is_empty() {
3302                                lines.push(format!("platform\t{line}"));
3303                            }
3304                        }
3305                    }
3306                }
3307            }
3308        } else {
3309            env.exception_clear().ok();
3310        }
3311    }
3312    YogOwnedStr::from_string(lines.join("\n"))
3313}
3314
3315unsafe extern "C" fn api_register_menu_entry(ctx: *mut c_void, label: YogStr, ui_id: YogStr) {
3316    let handlers_lock = &*(ctx as *const RwLock<RuntimeHandlers>);
3317    let mut handlers = handlers_lock.write().expect("handlers lock poisoned");
3318    let l = unsafe { label.as_str().to_owned() };
3319    let u = unsafe { ui_id.as_str().to_owned() };
3320    handlers.menu_entries.push((l, u));
3321}
3322
3323#[no_mangle]
3324pub extern "system" fn Java_dev_yog_NativeBridge_nativeBookJson<'l>(
3325    mut env: JNIEnv<'l>,
3326    _class: JClass<'l>,
3327    book_id: JString<'l>,
3328) -> jstring {
3329    let id = match env.get_string(&book_id) {
3330        Ok(s) => String::from(s),
3331        Err(_) => return std::ptr::null_mut(),
3332    };
3333    let json = handlers()
3334        .books
3335        .get(&id)
3336        .cloned()
3337        .unwrap_or_else(|| "null".to_string());
3338    env.new_string(json)
3339        .map(|s| s.into_raw())
3340        .unwrap_or(std::ptr::null_mut())
3341}
3342
3343// ── Table constructors ────────────────────────────────────────────────────────
3344
3345fn build_server_table() -> YogServer {
3346    YogServer {
3347        ctx: std::ptr::null_mut(),
3348        abi_version: ABI_VERSION,
3349        size: std::mem::size_of::<YogServer>() as u32,
3350        free_str: yog_free_str,
3351        broadcast: srv_broadcast,
3352        get_block: srv_get_block,
3353        set_block: srv_set_block,
3354        world_time: srv_world_time,
3355        set_time: srv_set_time,
3356        is_raining: srv_is_raining,
3357        set_weather: srv_set_weather,
3358        give_item: srv_give_item,
3359        player_teleport: srv_player_teleport,
3360        send_to_player: srv_send_to_player,
3361        send_to_server: srv_send_to_server,
3362        kick_player: srv_kick_player,
3363        set_gamemode: srv_set_gamemode,
3364        send_title: srv_send_title,
3365        send_actionbar: srv_send_actionbar,
3366        play_sound: srv_play_sound,
3367        play_sound_player: srv_play_sound_player,
3368        entity_teleport: srv_entity_teleport,
3369        entity_position: srv_entity_position,
3370        entity_rotation: srv_entity_rotation,
3371        entity_health: srv_entity_health,
3372        entity_set_health: srv_entity_set_health,
3373        entity_kill: srv_entity_kill,
3374        spawn_entity: srv_spawn_entity,
3375        entity_add_effect: srv_entity_add_effect,
3376        entity_remove_effect: srv_entity_remove_effect,
3377        entity_clear_effects: srv_entity_clear_effects,
3378        entity_velocity: srv_entity_velocity,
3379        entity_set_velocity: srv_entity_set_velocity,
3380        entity_add_velocity: srv_entity_add_velocity,
3381        has_item_tag: srv_has_item_tag,
3382        has_block_tag: srv_has_block_tag,
3383        drop_loot: srv_drop_loot,
3384        scoreboard_get: srv_scoreboard_get,
3385        scoreboard_set: srv_scoreboard_set,
3386        scoreboard_add: srv_scoreboard_add,
3387        bossbar_create: srv_bossbar_create,
3388        bossbar_remove: srv_bossbar_remove,
3389        bossbar_set_title: srv_bossbar_set_title,
3390        bossbar_set_progress: srv_bossbar_set_progress,
3391        bossbar_set_color: srv_bossbar_set_color,
3392        bossbar_add_player: srv_bossbar_add_player,
3393        bossbar_remove_player: srv_bossbar_remove_player,
3394        bossbar_set_visible: srv_bossbar_set_visible,
3395        game_dir: srv_game_dir,
3396        get_block_nbt: srv_get_block_nbt,
3397        set_block_nbt: srv_set_block_nbt,
3398        get_inventory_slot: srv_get_inventory_slot,
3399        set_inventory_slot: srv_set_inventory_slot,
3400        player_inventory: srv_player_inventory,
3401        player_set_slot: srv_player_set_slot,
3402        player_teleport_dim: srv_player_teleport_dim,
3403        entity_teleport_dim: srv_entity_teleport_dim,
3404        online_players: srv_online_players,
3405        world_entity_count: srv_world_entity_count,
3406        entity_get_nbt: srv_entity_get_nbt,
3407        entity_set_nbt: srv_entity_set_nbt,
3408        spawn_particles: srv_spawn_particles,
3409        entity_attribute_get: srv_entity_attribute_get,
3410        entity_attribute_set: srv_entity_attribute_set,
3411        get_held_item_nbt: srv_get_held_item_nbt,
3412        set_held_item_nbt: srv_set_held_item_nbt,
3413        get_offhand_item_nbt: srv_get_offhand_item_nbt,
3414        set_offhand_item_nbt: srv_set_offhand_item_nbt,
3415        get_slot_item: srv_get_slot_item,
3416        set_slot_item: srv_set_slot_item,
3417    }
3418}
3419
3420// ── Inter-mod communication ──────────────────────────────────────────────────
3421
3422unsafe extern "C" fn interop_export_impl(
3423    _ctx: *mut c_void,
3424    mod_id: YogStr,
3425    symbol: YogStr,
3426    ptr: *const c_void,
3427) {
3428    let mod_id = mod_id.as_str();
3429    let sym = symbol.as_str();
3430    let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3431    registry
3432        .lock()
3433        .expect("interop symbols lock poisoned")
3434        .entry(mod_id.to_string())
3435        .or_default()
3436        .insert(sym.to_string(), ptr as usize);
3437}
3438
3439unsafe extern "C" fn interop_import_impl(
3440    _ctx: *mut c_void,
3441    mod_id: YogStr,
3442    symbol: YogStr,
3443) -> *const c_void {
3444    let mod_id = mod_id.as_str();
3445    let sym = symbol.as_str();
3446    let registry = INTEROP_SYMBOLS.get_or_init(|| Mutex::new(HashMap::new()));
3447    registry
3448        .lock()
3449        .expect("interop symbols lock poisoned")
3450        .get(mod_id)
3451        .and_then(|m: &HashMap<String, usize>| m.get(sym))
3452        .map(|&ptr| ptr as *const c_void)
3453        .unwrap_or(std::ptr::null())
3454}
3455
3456fn build_api_table(ctx: *const RwLock<RuntimeHandlers>, server: *const YogServer) -> YogApi {
3457    YogApi {
3458        abi_version: ABI_VERSION,
3459        size: std::mem::size_of::<YogApi>() as u32,
3460        ctx: ctx as *mut c_void,
3461        server,
3462        on_block_break: api_on_block_break,
3463        on_chat: api_on_chat,
3464        on_player_join: api_on_player_join,
3465        on_player_leave: api_on_player_leave,
3466        on_use_item: api_on_use_item,
3467        on_use_block: api_on_use_block,
3468        on_attack_entity: api_on_attack_entity,
3469        on_entity_damage: api_on_entity_damage,
3470        on_entity_death: api_on_entity_death,
3471        on_entity_spawn: api_on_entity_spawn,
3472        on_player_place_block: api_on_player_place_block,
3473        on_player_death: api_on_player_death,
3474        on_player_respawn: api_on_player_respawn,
3475        on_advancement: api_on_advancement,
3476        on_entity_interact: api_on_entity_interact,
3477        on_item_craft: api_on_item_craft,
3478        on_explosion: api_on_explosion,
3479        on_item_pickup: api_on_item_pickup,
3480        on_player_move: api_on_player_move,
3481        on_container_open: api_on_container_open,
3482        on_container_close: api_on_container_close,
3483        on_projectile_hit: api_on_projectile_hit,
3484        on_server_tick: api_on_server_tick,
3485        on_server_started: api_on_server_started,
3486        on_server_stopping: api_on_server_stopping,
3487        on_packet: api_on_packet,
3488        on_client_packet: api_on_client_packet,
3489        register_command: api_register_command,
3490        register_typed_command: api_register_typed_command,
3491        register_recipe_json: api_register_recipe_json,
3492        register_item: api_register_item,
3493        register_block: api_register_block,
3494        schedule_once: api_schedule_once,
3495        schedule_repeating: api_schedule_repeating,
3496        on_client_tick: api_on_client_tick,
3497        on_hud_render: api_on_hud_render,
3498        on_key_press: api_on_key_press,
3499        on_screen_open: api_on_screen_open,
3500        on_screen_close: api_on_screen_close,
3501        on_world_render: api_on_world_render,
3502        register_startup_grant: api_register_startup_grant,
3503        register_book: api_register_book,
3504        register_ui: api_register_ui,
3505        on_ui_render: api_on_ui_render,
3506        register_menu_entry: api_register_menu_entry,
3507        mods_list: api_mods_list,
3508        free_str: yog_free_str,
3509        ui_open: api_ui_open,
3510        register_inventory: api_register_inventory,
3511        interop_export: interop_export_impl,
3512        interop_import: interop_import_impl,
3513        register_dimension_json: api_register_dimension_json,
3514        register_chunk_generator: api_register_chunk_generator,
3515        ui_close: api_ui_close,
3516        ui_consume_event: api_ui_consume_event,
3517        translate: api_translate,
3518    }
3519}
3520
3521// ── Mod loading ───────────────────────────────────────────────────────────────
3522
3523fn platform_tag() -> String {
3524    format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH)
3525}
3526
3527type AbiVersionFn = unsafe extern "C" fn() -> u32;
3528/// Second arg is a null-terminated C string: the mod's `id` from its manifest.
3529type RegisterFn = unsafe extern "C" fn(*const YogApi, *const std::os::raw::c_char);
3530
3531fn load_mods(dir: &Path, api: &YogApi) {
3532    let entries = match std::fs::read_dir(dir) {
3533        Ok(e) => e,
3534        Err(_) => {
3535            yog_logging::info!("no mods directory at {} — none loaded", dir.display());
3536            return;
3537        }
3538    };
3539
3540    // First pass: collect (mod_id, dependencies, archive_path)
3541    struct ModMeta {
3542        id: String,
3543        deps: Vec<String>,
3544        yog_path: PathBuf,
3545    }
3546    let mut metas: Vec<ModMeta> = Vec::new();
3547    for entry in entries.flatten() {
3548        let path = entry.path();
3549        if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3550            continue;
3551        }
3552        let info = read_mod_info(&path);
3553        let deps = read_mod_deps(&path);
3554        metas.push(ModMeta {
3555            id: info[0].clone(),
3556            deps,
3557            yog_path: path,
3558        });
3559    }
3560
3561    // Topological sort by dependencies (Kahn's algorithm)
3562    let ids: Vec<String> = metas.iter().map(|m| m.id.clone()).collect();
3563    let deps_list: Vec<Vec<String>> = metas.iter().map(|m| m.deps.clone()).collect();
3564    let sorted = match topo_sort_mods(&ids, &deps_list) {
3565        Some(v) => v,
3566        None => {
3567            yog_logging::error!("circular dependency detected — loading in file order");
3568            (0..metas.len()).collect()
3569        }
3570    };
3571
3572    let mut loaded: Vec<LoadedModule> = Vec::new();
3573    for idx in sorted {
3574        let meta = &metas[idx];
3575        let lib_path = match extract_yog(&meta.yog_path) {
3576            Some(p) => p,
3577            None => {
3578                yog_logging::error!(
3579                    "no native for {} in {}",
3580                    platform_tag(),
3581                    meta.yog_path.display()
3582                );
3583                continue;
3584            }
3585        };
3586        if let Some(module) = load_mod_lib(&lib_path, api, &meta.id) {
3587            loaded.push(module);
3588            MOD_INFOS
3589                .lock()
3590                .expect("mod infos lock poisoned")
3591                .push(read_mod_info(&meta.yog_path));
3592        }
3593    }
3594    yog_logging::info!("loaded {} mod(s) from {}", loaded.len(), dir.display());
3595
3596    // Final import resolution pass — after all mods loaded, each mod's pending
3597    // imports can be resolved against the now-complete interop table.
3598    resolve_all_imports(api, &loaded);
3599}
3600
3601/// After all mods loaded, call `__yog_resolve_imports_final` on each library
3602/// to resolve any imports that weren't satisfied during initial registration.
3603fn resolve_all_imports(api: &YogApi, loaded: &[LoadedModule]) {
3604    for module in loaded {
3605        module.with_library(|lib| unsafe {
3606            type ResolveFn = unsafe extern "C" fn(*const YogApi);
3607            if let Ok(resolve) = lib.get::<ResolveFn>(b"__yog_resolve_imports_final") {
3608                resolve(api as *const YogApi);
3609            }
3610        });
3611    }
3612}
3613
3614/// Kahn's algorithm — returns indices in dependency order, or None on cycle.
3615fn topo_sort_mods(ids: &[String], deps_list: &[Vec<String>]) -> Option<Vec<usize>> {
3616    let n = ids.len();
3617    let name_to_idx: HashMap<&str, usize> = ids
3618        .iter()
3619        .enumerate()
3620        .map(|(i, id)| (id.as_str(), i))
3621        .collect();
3622    let mut in_degree = vec![0u32; n];
3623    let mut adj: Vec<Vec<usize>> = vec![Vec::new(); n];
3624    for (i, deps) in deps_list.iter().enumerate() {
3625        for dep in deps {
3626            if let Some(&j) = name_to_idx.get(dep.as_str()) {
3627                adj[j].push(i);
3628                in_degree[i] += 1;
3629            }
3630        }
3631    }
3632    let mut queue: Vec<usize> = (0..n).filter(|&i| in_degree[i] == 0).collect();
3633    let mut order = Vec::with_capacity(n);
3634    while let Some(u) = queue.pop() {
3635        order.push(u);
3636        for &v in &adj[u] {
3637            in_degree[v] -= 1;
3638            if in_degree[v] == 0 {
3639                queue.push(v);
3640            }
3641        }
3642    }
3643    if order.len() == n {
3644        Some(order)
3645    } else {
3646        None
3647    }
3648}
3649
3650/// Loads `path` as a fresh generation of `mod_id` via the shared
3651/// `HotReloader`, validates its ABI, and calls its `yog_mod_register` —
3652/// tagging every handler it registers with the returned `LoadedModule` (see
3653/// `current_registration()`). On any failure the module (if it got as far
3654/// as being tracked by the `HotReloader`) is retired immediately: nothing
3655/// can be executing inside a library that never successfully registered,
3656/// so this always hard-unloads right away rather than lingering.
3657fn load_mod_lib(path: &Path, api: &YogApi, mod_id: &str) -> Option<LoadedModule> {
3658    let module = match unsafe { hot_reloader().load_initial(mod_id, path) } {
3659        Ok(m) => m,
3660        Err(e) => {
3661            yog_logging::error!("failed to load {}: {}", path.display(), e);
3662            return None;
3663        }
3664    };
3665
3666    let abi = module.with_library(|lib| unsafe {
3667        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
3668        Some(abi())
3669    });
3670    match abi.flatten() {
3671        Some(v) if v == ABI_VERSION => {}
3672        Some(v) => {
3673            yog_logging::error!(
3674                "{}: ABI {} incompatible with runtime ABI {}",
3675                path.display(),
3676                v,
3677                ABI_VERSION
3678            );
3679            module.retire(|| {});
3680            return None;
3681        }
3682        None => {
3683            yog_logging::error!("{} is not a Yog mod (no yog_abi_version)", path.display());
3684            module.retire(|| {});
3685            return None;
3686        }
3687    }
3688
3689    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
3690        yog_logging::error!("{}: {}", path.display(), e);
3691        module.retire(|| {});
3692        return None;
3693    }
3694
3695    Some(module)
3696}
3697
3698/// Calls a loaded module's `yog_mod_register`, tagging everything it
3699/// registers with `module` via `CURRENT_REGISTRATION` for the duration of
3700/// the call — used for both a mod's initial load and a later hot-reload.
3701fn invoke_mod_register(module: &LoadedModule, api: &YogApi, mod_id: &str) -> Result<(), String> {
3702    module
3703        .with_library(|lib| unsafe {
3704            let register: Symbol<RegisterFn> = lib
3705                .get(b"yog_mod_register")
3706                .map_err(|_| "missing yog_mod_register".to_string())?;
3707            let mod_id_c = std::ffi::CString::new(mod_id).unwrap();
3708            *CURRENT_REGISTRATION.lock().unwrap() = Some(module.clone());
3709            register(api as *const YogApi, mod_id_c.as_ptr());
3710            *CURRENT_REGISTRATION.lock().unwrap() = None;
3711            Ok(())
3712        })
3713        .unwrap_or_else(|| Err("module was unloaded before registration could run".to_string()))
3714}
3715
3716/// Metadata for a mod file: [id, name, version, authors, description,
3717/// name_key, description_key].
3718/// For .yog archives this comes from the bundled yog.toml; bare native libs
3719/// fall back to the file stem.
3720fn read_mod_info(path: &Path) -> [String; 7] {
3721    let stem = path
3722        .file_stem()
3723        .map(|s| s.to_string_lossy().into_owned())
3724        .unwrap_or_default();
3725    let mut info = [
3726        stem.clone(),
3727        stem,
3728        String::new(),
3729        String::new(),
3730        String::new(),
3731        String::new(),
3732        String::new(),
3733    ];
3734    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3735        return info;
3736    }
3737    let Some(text) = (|| {
3738        let file = std::fs::File::open(path).ok()?;
3739        let mut archive = zip::ZipArchive::new(file).ok()?;
3740        let mut entry = archive.by_name("yog.toml").ok()?;
3741        let mut text = String::new();
3742        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
3743        Some(text)
3744    })() else {
3745        return info;
3746    };
3747    // Minimal parse — enough for id/name/version/description/authors without
3748    // pulling in a TOML dependency. Source manifests keep these under [mod];
3749    // the packaged manifest (written by yog-cli) has them at top level, so
3750    // keys before any section header count too.
3751    let mut in_mod = true;
3752    for line in text.lines() {
3753        let line = line.trim();
3754        if line.starts_with('[') {
3755            in_mod = line == "[mod]";
3756            continue;
3757        }
3758        if !in_mod {
3759            continue;
3760        }
3761        let Some((key, value)) = line.split_once('=') else {
3762            continue;
3763        };
3764        let key = key.trim();
3765        let value = value.trim();
3766        let unquote = |v: &str| v.trim().trim_matches('"').to_string();
3767        match key {
3768            "id" => info[0] = tsv_clean(&unquote(value)),
3769            "name" => info[1] = tsv_clean(&unquote(value)),
3770            "version" => info[2] = tsv_clean(&unquote(value)),
3771            "description" => info[4] = tsv_clean(&unquote(value)),
3772            "name_key" => info[5] = unquote(value),
3773            "description_key" => info[6] = unquote(value),
3774            "authors" => {
3775                let list = value.trim_start_matches('[').trim_end_matches(']');
3776                let authors: Vec<String> = list
3777                    .split(',')
3778                    .map(unquote)
3779                    .filter(|a| !a.is_empty())
3780                    .collect();
3781                info[3] = tsv_clean(&authors.join(", "));
3782            }
3783            _ => {}
3784        }
3785    }
3786    info
3787}
3788
3789/// Parse `[dependencies]` section from yog.toml inside a .yog archive.
3790fn read_mod_deps(path: &Path) -> Vec<String> {
3791    if path.extension().and_then(|e| e.to_str()) != Some("yog") {
3792        return Vec::new();
3793    }
3794    let text = (|| {
3795        let file = std::fs::File::open(path).ok()?;
3796        let mut archive = zip::ZipArchive::new(file).ok()?;
3797        let mut entry = archive.by_name("yog.toml").ok()?;
3798        let mut text = String::new();
3799        std::io::Read::read_to_string(&mut entry, &mut text).ok()?;
3800        Some(text)
3801    })();
3802    let Some(text) = text else { return Vec::new() };
3803    let mut deps = Vec::new();
3804    let mut in_deps = false;
3805    for line in text.lines() {
3806        let line = line.trim();
3807        if line.starts_with('[') {
3808            in_deps = line == "[dependencies]";
3809            continue;
3810        }
3811        if !in_deps {
3812            continue;
3813        }
3814        // `mod_id = "1.0"` or `mod_id = "*"` — we only care about the key (mod_id)
3815        if let Some((key, _)) = line.split_once('=') {
3816            deps.push(key.trim().to_string());
3817        }
3818    }
3819    deps
3820}
3821
3822fn extract_yog(path: &Path) -> Option<PathBuf> {
3823    let file = std::fs::File::open(path).ok()?;
3824    let mut archive = zip::ZipArchive::new(file).ok()?;
3825    let prefix = format!("natives/{}/", platform_tag());
3826    let mut entry_name = None;
3827    for i in 0..archive.len() {
3828        let f = archive.by_index(i).ok()?;
3829        if f.name().starts_with(&prefix) && !f.name().ends_with('/') {
3830            entry_name = Some(f.name().to_string());
3831            break;
3832        }
3833    }
3834    let entry_name = entry_name?;
3835    let ext = Path::new(&entry_name)
3836        .extension()
3837        .and_then(|e| e.to_str())
3838        .unwrap_or("bin");
3839    let stem = path.file_stem()?.to_string_lossy().into_owned();
3840    // A fresh name per extraction: a hot reload must never truncate the
3841    // library the game still has mapped, and `dlopen` of an already-loaded
3842    // path would just hand back the old module.
3843    static EXTRACTIONS: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);
3844    let n = EXTRACTIONS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3845    let out =
3846        std::env::temp_dir().join(format!("yog-{}-{}-{}.{}", stem, std::process::id(), n, ext));
3847    let mut entry = archive.by_name(&entry_name).ok()?;
3848    let mut out_file = std::fs::File::create(&out).ok()?;
3849    std::io::copy(&mut entry, &mut out_file).ok()?;
3850    Some(out)
3851}
3852
3853// ── Dispatcher helpers ────────────────────────────────────────────────────────
3854
3855fn srv_ptr() -> *const YogServer {
3856    SERVER.get().expect("yog: SERVER not initialised") as *const YogServer
3857}
3858
3859// ── JNI entry points ──────────────────────────────────────────────────────────
3860
3861#[no_mangle]
3862pub extern "system" fn Java_dev_yog_NativeBridge_nativeInit<'l>(
3863    mut env: JNIEnv<'l>,
3864    _class: JClass<'l>,
3865    mods_dir: JString<'l>,
3866) {
3867    if let Ok(vm) = env.get_java_vm() {
3868        let _ = JAVA_VM.set(vm);
3869    }
3870
3871    let dir = env
3872        .get_string(&mods_dir)
3873        .map(String::from)
3874        .unwrap_or_default();
3875
3876    // Build YogServer and store in static (gets a stable address).
3877    let _ = SERVER.set(build_server_table());
3878    let server_ptr = SERVER.get().unwrap() as *const YogServer;
3879
3880    // Publish HANDLERS *before* any mod registers — its address is then
3881    // `'static`-stable for the runtime's entire lifetime, unlike the old
3882    // design (a temporary heap `Box` moved into `HANDLERS` only after
3883    // `nativeInit` returned, silently invalidating the `ctx` pointer any
3884    // later re-registration — e.g. a hot-reload — would have needed).
3885    let handlers_lock = HANDLERS.get_or_init(|| RwLock::new(RuntimeHandlers::new()));
3886    let handlers_ptr = handlers_lock as *const RwLock<RuntimeHandlers>;
3887
3888    let api: &'static YogApi = API_TABLE.get_or_init(|| build_api_table(handlers_ptr, server_ptr));
3889
3890    let _ = HOT_RELOADER.get_or_init(|| HotReloader::new(RuntimeModuleRegistry));
3891
3892    guard("mod loading", || {
3893        load_mods(Path::new(&dir), api);
3894    });
3895
3896    control_socket::start_if_requested();
3897
3898    yog_logging::info!("runtime initialised — the gate is open.");
3899}
3900
3901#[no_mangle]
3902pub extern "system" fn Java_dev_yog_NativeBridge_nativeHotReload<'l>(
3903    mut env: JNIEnv<'l>,
3904    _class: JClass<'l>,
3905    mod_id: JString<'l>,
3906    new_yog_path: JString<'l>,
3907) -> jni::sys::jboolean {
3908    let Ok(mod_id) = env.get_string(&mod_id).map(String::from) else {
3909        return 0;
3910    };
3911    let Ok(yog_path) = env.get_string(&new_yog_path).map(String::from) else {
3912        return 0;
3913    };
3914    let ok = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
3915        trigger_hot_reload(&mod_id, Path::new(&yog_path))
3916    }))
3917    .unwrap_or(false);
3918    ok as jni::sys::jboolean
3919}
3920
3921/// Rebuilds and re-registers `mod_id` from a freshly built `.yog` at
3922/// `new_yog_path`: extracts the current platform's native, loads it as a
3923/// new generation via the shared `HotReloader` (which retires the previous
3924/// generation per its hybrid soft/hard-unload policy — hard-unloaded right
3925/// away if nothing's mid-call, deferred otherwise), then calls its
3926/// `yog_mod_register` again so its handlers get tagged under the new
3927/// generation. How this actually gets triggered — a keybind, a file-watch,
3928/// an IDE-driven socket — is a separate, later concern; this only needs to
3929/// work correctly once called.
3930fn trigger_hot_reload(mod_id: &str, new_yog_path: &Path) -> bool {
3931    let Some(native_path) = extract_yog(new_yog_path) else {
3932        yog_logging::error!(
3933            "hot-reload {}: no native for {} in {}",
3934            mod_id,
3935            platform_tag(),
3936            new_yog_path.display()
3937        );
3938        return false;
3939    };
3940
3941    let api = API_TABLE.get().expect("yog: nativeInit not called yet");
3942
3943    let module = match unsafe { hot_reloader().reload(mod_id, &native_path) } {
3944        Ok(m) => m,
3945        Err(e) => {
3946            yog_logging::error!(
3947                "hot-reload {}: failed to load {}: {}",
3948                mod_id,
3949                native_path.display(),
3950                e
3951            );
3952            return false;
3953        }
3954    };
3955
3956    let abi = module.with_library(|lib| unsafe {
3957        let abi: Symbol<AbiVersionFn> = lib.get(b"yog_abi_version").ok()?;
3958        Some(abi())
3959    });
3960    match abi.flatten() {
3961        Some(v) if v == ABI_VERSION => {}
3962        other => {
3963            yog_logging::error!(
3964                "hot-reload {}: ABI {:?} incompatible with runtime ABI {} — mod has no active handlers until a compatible reload succeeds",
3965                mod_id,
3966                other,
3967                ABI_VERSION
3968            );
3969            return false;
3970        }
3971    }
3972
3973    if let Err(e) = invoke_mod_register(&module, api, mod_id) {
3974        yog_logging::error!("hot-reload {}: {}", mod_id, e);
3975        return false;
3976    }
3977
3978    yog_logging::info!("hot-reloaded mod {}", mod_id);
3979    true
3980}
3981
3982#[no_mangle]
3983pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreak<'l>(
3984    mut env: JNIEnv<'l>,
3985    _class: JClass<'l>,
3986    player: JString<'l>,
3987    block: JString<'l>,
3988    x: jint,
3989    y: jint,
3990    z: jint,
3991    dimension: JString<'l>,
3992) {
3993    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
3994    let ev = yog_abi::YogBlockBreakEvent {
3995        player: YogStr::from_str(&p),
3996        block: YogStr::from_str(&b),
3997        pos: YogBlockPos { x, y, z },
3998        dimension: YogStr::from_str(&d),
3999    };
4000    let srv = srv_ptr();
4001    guard("on_block_break", || {
4002        for (module, ud, f) in &handlers().block_break {
4003            if module.is_retiring() {
4004                continue;
4005            }
4006            let Some(_call) = module.enter() else {
4007                continue;
4008            };
4009            unsafe { f(*ud, srv, &ev, 1) };
4010        }
4011    });
4012}
4013
4014#[no_mangle]
4015pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChat<'l>(
4016    mut env: JNIEnv<'l>,
4017    _class: JClass<'l>,
4018    player: JString<'l>,
4019    message: JString<'l>,
4020    dimension: JString<'l>,
4021) {
4022    let (p, m, d) = (
4023        jstr!(env, player),
4024        jstr!(env, message),
4025        jstr!(env, dimension),
4026    );
4027    let ev = yog_abi::YogChatEvent {
4028        player: YogStr::from_str(&p),
4029        message: YogStr::from_str(&m),
4030        dimension: YogStr::from_str(&d),
4031    };
4032    let srv = srv_ptr();
4033    guard("on_chat", || {
4034        for (module, ud, f) in &handlers().chat {
4035            if module.is_retiring() {
4036                continue;
4037            }
4038            let Some(_call) = module.enter() else {
4039                continue;
4040            };
4041            unsafe { f(*ud, srv, &ev, 1) };
4042        }
4043    });
4044}
4045
4046#[no_mangle]
4047pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerJoin<'l>(
4048    mut env: JNIEnv<'l>,
4049    _class: JClass<'l>,
4050    player: JString<'l>,
4051    uuid: JString<'l>,
4052    dimension: JString<'l>,
4053) {
4054    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4055    let ev = yog_abi::YogPlayerEvent {
4056        player: YogStr::from_str(&p),
4057        uuid: YogStr::from_str(&u),
4058        dimension: YogStr::from_str(&d),
4059    };
4060    let srv = srv_ptr();
4061    guard("on_player_join", || {
4062        for (module, ud, f) in &handlers().player_join {
4063            if module.is_retiring() {
4064                continue;
4065            }
4066            let Some(_call) = module.enter() else {
4067                continue;
4068            };
4069            unsafe { f(*ud, srv, &ev, 1) };
4070        }
4071    });
4072    // Queue startup grants: giving items directly inside the join callback
4073    // fails for the host of a freshly created world (player not fully in the
4074    // world yet), so grants are processed a few server ticks later.
4075    let h = handlers();
4076    if !h.startup_grants.is_empty() {
4077        h.pending_grants
4078            .lock()
4079            .expect("pending_grants poisoned")
4080            .push((p, u, 0));
4081    }
4082}
4083
4084/// Try to fulfil pending startup grants. Called each server tick; a grant is
4085/// only marked as given (and persisted) after `give_item` actually succeeds.
4086fn process_pending_grants() {
4087    let h = handlers();
4088    let mut pending = match h.pending_grants.try_lock() {
4089        Ok(g) => g,
4090        Err(_) => return,
4091    };
4092    if pending.is_empty() {
4093        return;
4094    }
4095    // Wait a couple of ticks after join before the first attempt.
4096    const FIRST_TRY_TICK: u32 = 2;
4097    // Give up after 30 seconds — the player probably left.
4098    const MAX_TICKS: u32 = 600;
4099
4100    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
4101    let mut still_pending = Vec::new();
4102    let mut any_new = false;
4103
4104    for (p, u, ticks) in pending.drain(..) {
4105        if ticks < FIRST_TRY_TICK {
4106            still_pending.push((p, u, ticks + 1));
4107            continue;
4108        }
4109        let mut all_ok = true;
4110        for sg in &h.startup_grants {
4111            let key = format!("{}::{}", u, sg.id);
4112            if granted.contains_key(&key) {
4113                continue;
4114            }
4115            let mut ok = true;
4116            for item_id in &sg.items {
4117                ok &= unsafe {
4118                    srv_give_item(
4119                        std::ptr::null_mut(),
4120                        YogStr::from_str(&p),
4121                        YogStr::from_str(item_id),
4122                        1,
4123                    )
4124                };
4125            }
4126            if let Some(_book) = &sg.book {
4127                ok &= unsafe {
4128                    srv_give_item(
4129                        std::ptr::null_mut(),
4130                        YogStr::from_str(&p),
4131                        YogStr::from_str("minecraft:written_book"),
4132                        1,
4133                    )
4134                };
4135            }
4136            if ok {
4137                yog_logging::info!("startup grant {} given to {}", sg.id, p);
4138                granted.insert(key, true);
4139                any_new = true;
4140            } else {
4141                all_ok = false;
4142            }
4143        }
4144        if !all_ok && ticks < MAX_TICKS {
4145            still_pending.push((p, u, ticks + 1));
4146        }
4147    }
4148    *pending = still_pending;
4149    if any_new {
4150        save_startup_granted(&granted);
4151    }
4152}
4153
4154#[no_mangle]
4155pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerLeave<'l>(
4156    mut env: JNIEnv<'l>,
4157    _class: JClass<'l>,
4158    player: JString<'l>,
4159    uuid: JString<'l>,
4160    dimension: JString<'l>,
4161) {
4162    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
4163    let ev = yog_abi::YogPlayerEvent {
4164        player: YogStr::from_str(&p),
4165        uuid: YogStr::from_str(&u),
4166        dimension: YogStr::from_str(&d),
4167    };
4168    let srv = srv_ptr();
4169    guard("on_player_leave", || {
4170        for (module, ud, f) in &handlers().player_leave {
4171            if module.is_retiring() {
4172                continue;
4173            }
4174            let Some(_call) = module.enter() else {
4175                continue;
4176            };
4177            unsafe { f(*ud, srv, &ev, 1) };
4178        }
4179    });
4180}
4181
4182#[no_mangle]
4183pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItem<'l>(
4184    mut env: JNIEnv<'l>,
4185    _class: JClass<'l>,
4186    player: JString<'l>,
4187    item: JString<'l>,
4188    sneaking: jni::sys::jboolean,
4189    dimension: JString<'l>,
4190) {
4191    let (p, i, d) = (jstr!(env, player), jstr!(env, item), jstr!(env, dimension));
4192    let ev = yog_abi::YogUseItemEvent {
4193        player: YogStr::from_str(&p),
4194        item: YogStr::from_str(&i),
4195        sneaking: sneaking != 0,
4196        dimension: YogStr::from_str(&d),
4197    };
4198    let srv = srv_ptr();
4199    guard("on_use_item", || {
4200        for (module, ud, f) in &handlers().use_item {
4201            if module.is_retiring() {
4202                continue;
4203            }
4204            let Some(_call) = module.enter() else {
4205                continue;
4206            };
4207            unsafe { f(*ud, srv, &ev, 1) };
4208        }
4209    });
4210}
4211
4212#[no_mangle]
4213pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseItemPre<'l>(
4214    mut env: JNIEnv<'l>,
4215    _class: JClass<'l>,
4216    player: JString<'l>,
4217    item: JString<'l>,
4218    sneaking: jni::sys::jboolean,
4219    dimension: JString<'l>,
4220) -> jni::sys::jboolean {
4221    let h = handlers();
4222    if h.use_item.is_empty() {
4223        return 1;
4224    }
4225    let p = match env.get_string(&player) {
4226        Ok(s) => String::from(s),
4227        Err(_) => return 1,
4228    };
4229    let i = match env.get_string(&item) {
4230        Ok(s) => String::from(s),
4231        Err(_) => return 1,
4232    };
4233    let d = match env.get_string(&dimension) {
4234        Ok(s) => String::from(s),
4235        Err(_) => return 1,
4236    };
4237    let ev = yog_abi::YogUseItemEvent {
4238        player: YogStr::from_str(&p),
4239        item: YogStr::from_str(&i),
4240        sneaking: sneaking != 0,
4241        dimension: YogStr::from_str(&d),
4242    };
4243    let srv = srv_ptr();
4244    let mut allow = true;
4245    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4246        for (module, ud, f) in &h.use_item {
4247            if module.is_retiring() {
4248                continue;
4249            }
4250            let Some(_call) = module.enter() else {
4251                continue;
4252            };
4253            if !unsafe { f(*ud, srv, &ev, 0) } {
4254                allow = false;
4255                break;
4256            }
4257        }
4258    }))
4259    .ok();
4260    allow as jni::sys::jboolean
4261}
4262
4263#[no_mangle]
4264pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlock<'l>(
4265    mut env: JNIEnv<'l>,
4266    _class: JClass<'l>,
4267    player: JString<'l>,
4268    block: JString<'l>,
4269    x: jint,
4270    y: jint,
4271    z: jint,
4272    dimension: JString<'l>,
4273) {
4274    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
4275    let ev = yog_abi::YogUseBlockEvent {
4276        player: YogStr::from_str(&p),
4277        block: YogStr::from_str(&b),
4278        pos: YogBlockPos { x, y, z },
4279        dimension: YogStr::from_str(&d),
4280    };
4281    let srv = srv_ptr();
4282    guard("on_use_block", || {
4283        for (module, ud, f) in &handlers().use_block {
4284            if module.is_retiring() {
4285                continue;
4286            }
4287            let Some(_call) = module.enter() else {
4288                continue;
4289            };
4290            unsafe { f(*ud, srv, &ev, 1) };
4291        }
4292    });
4293}
4294
4295#[no_mangle]
4296pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnUseBlockPre<'l>(
4297    mut env: JNIEnv<'l>,
4298    _class: JClass<'l>,
4299    player: JString<'l>,
4300    block: JString<'l>,
4301    x: jint,
4302    y: jint,
4303    z: jint,
4304    dimension: JString<'l>,
4305) -> jni::sys::jboolean {
4306    let h = handlers();
4307    if h.use_block.is_empty() {
4308        return 1;
4309    }
4310    let p = match env.get_string(&player) {
4311        Ok(s) => String::from(s),
4312        Err(_) => return 1,
4313    };
4314    let b = match env.get_string(&block) {
4315        Ok(s) => String::from(s),
4316        Err(_) => return 1,
4317    };
4318    let d = match env.get_string(&dimension) {
4319        Ok(s) => String::from(s),
4320        Err(_) => return 1,
4321    };
4322    let ev = yog_abi::YogUseBlockEvent {
4323        player: YogStr::from_str(&p),
4324        block: YogStr::from_str(&b),
4325        pos: YogBlockPos { x, y, z },
4326        dimension: YogStr::from_str(&d),
4327    };
4328    let srv = srv_ptr();
4329    let mut allow = true;
4330    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4331        for (module, ud, f) in &h.use_block {
4332            if module.is_retiring() {
4333                continue;
4334            }
4335            let Some(_call) = module.enter() else {
4336                continue;
4337            };
4338            if !unsafe { f(*ud, srv, &ev, 0) } {
4339                allow = false;
4340                break;
4341            }
4342        }
4343    }))
4344    .ok();
4345    allow as jni::sys::jboolean
4346}
4347
4348#[no_mangle]
4349pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAttackEntity<'l>(
4350    mut env: JNIEnv<'l>,
4351    _class: JClass<'l>,
4352    player: JString<'l>,
4353    target_type: JString<'l>,
4354    target_uuid: JString<'l>,
4355    dimension: JString<'l>,
4356) {
4357    let (p, tt, tu, d) = (
4358        jstr!(env, player),
4359        jstr!(env, target_type),
4360        jstr!(env, target_uuid),
4361        jstr!(env, dimension),
4362    );
4363    let ev = yog_abi::YogAttackEntityEvent {
4364        player: YogStr::from_str(&p),
4365        target_type: YogStr::from_str(&tt),
4366        target_uuid: YogStr::from_str(&tu),
4367        dimension: YogStr::from_str(&d),
4368    };
4369    let srv = srv_ptr();
4370    guard("on_attack_entity", || {
4371        for (module, ud, f) in &handlers().attack_entity {
4372            if module.is_retiring() {
4373                continue;
4374            }
4375            let Some(_call) = module.enter() else {
4376                continue;
4377            };
4378            unsafe { f(*ud, srv, &ev, 1) };
4379        }
4380    });
4381}
4382
4383#[no_mangle]
4384pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamage<'l>(
4385    mut env: JNIEnv<'l>,
4386    _class: JClass<'l>,
4387    entity_type: JString<'l>,
4388    uuid: JString<'l>,
4389    amount: jfloat,
4390    source: JString<'l>,
4391    dimension: JString<'l>,
4392) {
4393    let (et, u, s, d) = (
4394        jstr!(env, entity_type),
4395        jstr!(env, uuid),
4396        jstr!(env, source),
4397        jstr!(env, dimension),
4398    );
4399    let ev = yog_abi::YogEntityDamageEvent {
4400        entity_type: YogStr::from_str(&et),
4401        uuid: YogStr::from_str(&u),
4402        amount,
4403        source: YogStr::from_str(&s),
4404        dimension: YogStr::from_str(&d),
4405    };
4406    let srv = srv_ptr();
4407    guard("on_entity_damage", || {
4408        for (module, ud, f) in &handlers().entity_damage {
4409            if module.is_retiring() {
4410                continue;
4411            }
4412            let Some(_call) = module.enter() else {
4413                continue;
4414            };
4415            unsafe { f(*ud, srv, &ev, 1) };
4416        }
4417    });
4418}
4419
4420#[no_mangle]
4421pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDeath<'l>(
4422    mut env: JNIEnv<'l>,
4423    _class: JClass<'l>,
4424    entity_type: JString<'l>,
4425    uuid: JString<'l>,
4426    source: JString<'l>,
4427    dimension: JString<'l>,
4428) {
4429    let (et, u, s, d) = (
4430        jstr!(env, entity_type),
4431        jstr!(env, uuid),
4432        jstr!(env, source),
4433        jstr!(env, dimension),
4434    );
4435    let ev = yog_abi::YogEntityDeathEvent {
4436        entity_type: YogStr::from_str(&et),
4437        uuid: YogStr::from_str(&u),
4438        source: YogStr::from_str(&s),
4439        dimension: YogStr::from_str(&d),
4440    };
4441    let srv = srv_ptr();
4442    guard("on_entity_death", || {
4443        for (module, ud, f) in &handlers().entity_death {
4444            if module.is_retiring() {
4445                continue;
4446            }
4447            let Some(_call) = module.enter() else {
4448                continue;
4449            };
4450            unsafe { f(*ud, srv, &ev, 1) };
4451        }
4452    });
4453}
4454
4455#[no_mangle]
4456pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnTick<'l>(
4457    _env: JNIEnv<'l>,
4458    _class: JClass<'l>,
4459) {
4460    let h = handlers();
4461    let srv = srv_ptr();
4462    guard("on_tick", || {
4463        for (module, ud, f) in &h.server_tick {
4464            if module.is_retiring() {
4465                continue;
4466            }
4467            let Some(_call) = module.enter() else {
4468                continue;
4469            };
4470            unsafe { f(*ud, srv) };
4471        }
4472    });
4473
4474    guard("startup_grants", process_pending_grants);
4475
4476    // Scheduler — once tasks
4477    {
4478        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
4479        let mut to_fire: Vec<(LoadedModule, *mut c_void, YogScheduledFn)> = Vec::new();
4480        let mut remaining = Vec::new();
4481        for task in sched.once_tasks.drain(..) {
4482            if task.delay_remaining == 0 {
4483                to_fire.push((task.module.clone(), task.ud, task.f));
4484            } else {
4485                remaining.push(OnceTask {
4486                    delay_remaining: task.delay_remaining - 1,
4487                    ..task
4488                });
4489            }
4490        }
4491        sched.once_tasks = remaining;
4492        drop(sched);
4493        for (module, ud, f) in to_fire {
4494            if module.is_retiring() {
4495                continue;
4496            }
4497            let Some(_call) = module.enter() else {
4498                continue;
4499            };
4500            guard("schedule_once", || unsafe { f(ud, srv) });
4501        }
4502    }
4503
4504    // Scheduler — repeating tasks
4505    {
4506        let mut sched = h.scheduler.lock().expect("scheduler poisoned");
4507        let mut to_fire: Vec<(LoadedModule, *mut c_void, YogScheduledFn)> = Vec::new();
4508        for task in &mut sched.repeating_tasks {
4509            if task.ticks_left == 0 {
4510                to_fire.push((task.module.clone(), task.ud, task.f));
4511                task.ticks_left = task.period;
4512            } else {
4513                task.ticks_left -= 1;
4514            }
4515        }
4516        drop(sched);
4517        for (module, ud, f) in to_fire {
4518            if module.is_retiring() {
4519                continue;
4520            }
4521            let Some(_call) = module.enter() else {
4522                continue;
4523            };
4524            guard("schedule_repeating", || unsafe { f(ud, srv) });
4525        }
4526    }
4527}
4528
4529/// Absolute path of the current world save folder (set on server start).
4530static WORLD_DIR: Mutex<Option<std::path::PathBuf>> = Mutex::new(None);
4531
4532/// Per-world data path: `<world>/yog-data/startup_grants.json`.
4533/// Falls back to the working directory before any server has started.
4534fn startup_grants_path() -> std::path::PathBuf {
4535    let base = WORLD_DIR
4536        .lock()
4537        .ok()
4538        .and_then(|d| d.clone())
4539        .unwrap_or_else(|| std::path::PathBuf::from("."));
4540    base.join("yog-data").join("startup_grants.json")
4541}
4542
4543fn load_startup_granted() {
4544    let h = handlers();
4545    let mut granted = h.startup_granted.lock().expect("startup_granted poisoned");
4546    // Reset first — in singleplayer the process outlives individual worlds,
4547    // and grant state is per-world.
4548    granted.clear();
4549    h.pending_grants
4550        .lock()
4551        .expect("pending_grants poisoned")
4552        .clear();
4553    let path = startup_grants_path();
4554    let Ok(data) = std::fs::read_to_string(&path) else {
4555        return;
4556    };
4557    let Ok(keys) = serde_json::from_str::<Vec<String>>(&data) else {
4558        yog_logging::warn!("startup_grants.json: invalid JSON, ignoring");
4559        return;
4560    };
4561    for k in keys {
4562        granted.insert(k, true);
4563    }
4564    yog_logging::info!("loaded {} startup grants from disk", granted.len());
4565}
4566
4567fn save_startup_granted(granted: &HashMap<String, bool>) {
4568    let path = startup_grants_path();
4569    if let Some(parent) = path.parent() {
4570        let _ = std::fs::create_dir_all(parent);
4571    }
4572    let keys: Vec<&String> = granted.keys().collect();
4573    match serde_json::to_string(&keys) {
4574        Ok(json) => {
4575            let _ = std::fs::write(&path, json);
4576        }
4577        Err(e) => yog_logging::error!("failed to save startup_grants.json: {}", e),
4578    }
4579}
4580
4581#[no_mangle]
4582pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStarted<'l>(
4583    mut env: JNIEnv<'l>,
4584    _class: JClass<'l>,
4585    world_dir: JString<'l>,
4586) {
4587    let dir = jstr!(env, world_dir);
4588    *WORLD_DIR.lock().expect("WORLD_DIR poisoned") = if dir.is_empty() {
4589        None
4590    } else {
4591        Some(std::path::PathBuf::from(dir))
4592    };
4593    load_startup_granted();
4594    let srv = srv_ptr();
4595    guard("on_server_started", || {
4596        for (module, ud, f) in &handlers().server_started {
4597            if module.is_retiring() {
4598                continue;
4599            }
4600            let Some(_call) = module.enter() else {
4601                continue;
4602            };
4603            unsafe { f(*ud, srv) };
4604        }
4605    });
4606}
4607
4608#[no_mangle]
4609pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnServerStopping<'l>(
4610    _env: JNIEnv<'l>,
4611    _class: JClass<'l>,
4612) {
4613    let srv = srv_ptr();
4614    guard("on_server_stopping", || {
4615        for (module, ud, f) in &handlers().server_stopping {
4616            if module.is_retiring() {
4617                continue;
4618            }
4619            let Some(_call) = module.enter() else {
4620                continue;
4621            };
4622            unsafe { f(*ud, srv) };
4623        }
4624    });
4625}
4626
4627#[no_mangle]
4628pub extern "system" fn Java_dev_yog_NativeBridge_nativeCommandNames<'l>(
4629    env: JNIEnv<'l>,
4630    _class: JClass<'l>,
4631) -> jstring {
4632    let names = handlers()
4633        .commands
4634        .keys()
4635        .cloned()
4636        .collect::<Vec<_>>()
4637        .join("\n");
4638    env.new_string(names)
4639        .map(|s| s.into_raw())
4640        .unwrap_or(std::ptr::null_mut())
4641}
4642
4643#[no_mangle]
4644pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnBlockBreakPre<'l>(
4645    mut env: JNIEnv<'l>,
4646    _class: JClass<'l>,
4647    player: JString<'l>,
4648    block: JString<'l>,
4649    x: jint,
4650    y: jint,
4651    z: jint,
4652    dimension: JString<'l>,
4653) -> jni::sys::jboolean {
4654    let h = handlers();
4655    if h.block_break.is_empty() {
4656        return 1;
4657    }
4658    let p = match env.get_string(&player) {
4659        Ok(s) => String::from(s),
4660        Err(_) => return 1,
4661    };
4662    let b = match env.get_string(&block) {
4663        Ok(s) => String::from(s),
4664        Err(_) => return 1,
4665    };
4666    let d = match env.get_string(&dimension) {
4667        Ok(s) => String::from(s),
4668        Err(_) => return 1,
4669    };
4670    let ev = yog_abi::YogBlockBreakEvent {
4671        player: YogStr::from_str(&p),
4672        block: YogStr::from_str(&b),
4673        pos: YogBlockPos { x, y, z },
4674        dimension: YogStr::from_str(&d),
4675    };
4676    let srv = srv_ptr();
4677    let mut allow = true;
4678    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4679        for (module, ud, f) in &h.block_break {
4680            if module.is_retiring() {
4681                continue;
4682            }
4683            let Some(_call) = module.enter() else {
4684                continue;
4685            };
4686            if !unsafe { f(*ud, srv, &ev, 0) } {
4687                allow = false;
4688                break;
4689            }
4690        }
4691    }))
4692    .ok();
4693    allow as jni::sys::jboolean
4694}
4695
4696#[no_mangle]
4697pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnChatPre<'l>(
4698    mut env: JNIEnv<'l>,
4699    _class: JClass<'l>,
4700    player: JString<'l>,
4701    message: JString<'l>,
4702    dimension: JString<'l>,
4703) -> jni::sys::jboolean {
4704    let h = handlers();
4705    if h.chat.is_empty() {
4706        return 1;
4707    }
4708    let p = match env.get_string(&player) {
4709        Ok(s) => String::from(s),
4710        Err(_) => return 1,
4711    };
4712    let m = match env.get_string(&message) {
4713        Ok(s) => String::from(s),
4714        Err(_) => return 1,
4715    };
4716    let d = match env.get_string(&dimension) {
4717        Ok(s) => String::from(s),
4718        Err(_) => return 1,
4719    };
4720    let ev = yog_abi::YogChatEvent {
4721        player: YogStr::from_str(&p),
4722        message: YogStr::from_str(&m),
4723        dimension: YogStr::from_str(&d),
4724    };
4725    let srv = srv_ptr();
4726    let mut allow = true;
4727    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4728        for (module, ud, f) in &h.chat {
4729            if module.is_retiring() {
4730                continue;
4731            }
4732            let Some(_call) = module.enter() else {
4733                continue;
4734            };
4735            if !unsafe { f(*ud, srv, &ev, 0) } {
4736                allow = false;
4737                break;
4738            }
4739        }
4740    }))
4741    .ok();
4742    allow as jni::sys::jboolean
4743}
4744
4745#[no_mangle]
4746pub extern "system" fn Java_dev_yog_NativeBridge_nativeRecipeJsons<'l>(
4747    env: JNIEnv<'l>,
4748    _class: JClass<'l>,
4749) -> jstring {
4750    let s = handlers()
4751        .recipes
4752        .iter()
4753        .map(|(ns, name, json)| format!("{}\t{}\t{}", ns, name, json))
4754        .collect::<Vec<_>>()
4755        .join("\n");
4756    env.new_string(s)
4757        .map(|s| s.into_raw())
4758        .unwrap_or(std::ptr::null_mut())
4759}
4760
4761#[no_mangle]
4762pub extern "system" fn Java_dev_yog_NativeBridge_nativeDimensionJsons<'l>(
4763    env: JNIEnv<'l>,
4764    _class: JClass<'l>,
4765) -> jstring {
4766    // One line per declared dimension: `id \t def_json`. The host converts
4767    // `def_json` (our YogDimensionDef shape) into vanilla dimension_type /
4768    // dimension datapack JSON — see `yog-dimensions` crate docs.
4769    let s = handlers()
4770        .dimensions
4771        .iter()
4772        .map(|(id, json)| format!("{}\t{}", id, json))
4773        .collect::<Vec<_>>()
4774        .join("\n");
4775    env.new_string(s)
4776        .map(|s| s.into_raw())
4777        .unwrap_or(std::ptr::null_mut())
4778}
4779
4780/// Called by a registered chunk-generator closure (via `ChunkWriter::set_block`)
4781/// to place one block in the chunk currently being generated. Calls back
4782/// into `YogCallbackChunkGenerator.setBlockInGeneratingChunk` on the Java
4783/// side — same thread, since the whole round trip is synchronous.
4784unsafe extern "C" fn chunk_writer_set_block(
4785    _ctx: *mut c_void,
4786    x: i32,
4787    y: i32,
4788    z: i32,
4789    block_id: YogStr,
4790) -> bool {
4791    let Some(mut env) = get_env() else {
4792        return false;
4793    };
4794    let Some(jb) = ys_to_java(&mut env, block_id) else {
4795        return false;
4796    };
4797    env.call_static_method(
4798        "dev/yog/NativeBridge",
4799        "setBlockInGeneratingChunk",
4800        "(IIILjava/lang/String;)Z",
4801        &[
4802            JValue::Int(x),
4803            JValue::Int(y),
4804            JValue::Int(z),
4805            JValue::Object(&jb),
4806        ],
4807    )
4808    .and_then(|v| v.z())
4809    .unwrap_or(false)
4810}
4811
4812#[no_mangle]
4813pub extern "system" fn Java_dev_yog_NativeBridge_nativeGenerateChunk<'l>(
4814    mut env: JNIEnv<'l>,
4815    _class: JClass<'l>,
4816    generator_type_id: JString<'l>,
4817    chunk_x: jint,
4818    chunk_z: jint,
4819    min_y: jint,
4820    height: jint,
4821) {
4822    let id: String = match env.get_string(&generator_type_id) {
4823        Ok(s) => String::from(s),
4824        Err(_) => return,
4825    };
4826    let Some((module, ud, cb)) = handlers().chunk_generators.get(&id).cloned() else {
4827        return;
4828    };
4829    if module.is_retiring() {
4830        return;
4831    }
4832    let Some(_call) = module.enter() else { return };
4833    let writer = yog_abi::YogChunkWriterApi {
4834        chunk_x,
4835        chunk_z,
4836        min_y,
4837        height,
4838        ctx: std::ptr::null_mut(),
4839        set_block: chunk_writer_set_block,
4840    };
4841    guard("chunk_generator", || unsafe {
4842        cb(ud, &writer as *const _);
4843    });
4844}
4845
4846#[no_mangle]
4847pub extern "system" fn Java_dev_yog_NativeBridge_nativeTypedCommandSchemas<'l>(
4848    env: JNIEnv<'l>,
4849    _class: JClass<'l>,
4850) -> jstring {
4851    // One line per DISTINCT (name, schema) pair — a name can have several
4852    // typed registrations (different arg shapes); Brigadier merges repeated
4853    // `dispatcher.register()` calls for the same literal name into one tree,
4854    // so the Java side just needs every distinct schema once each.
4855    let mut lines = Vec::new();
4856    for (name, regs) in handlers().commands.iter() {
4857        let mut seen = std::collections::HashSet::new();
4858        for (_module, schema, _, _) in regs {
4859            if let Some(schema) = schema {
4860                if seen.insert(schema.as_str()) {
4861                    lines.push(format!("{}\t{}", name, schema));
4862                }
4863            }
4864        }
4865    }
4866    env.new_string(lines.join("\n"))
4867        .map(|s| s.into_raw())
4868        .unwrap_or(std::ptr::null_mut())
4869}
4870
4871#[no_mangle]
4872pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnCommand<'l>(
4873    mut env: JNIEnv<'l>,
4874    _class: JClass<'l>,
4875    name: JString<'l>,
4876    args: JString<'l>,
4877    source: JString<'l>,
4878    uuid: JString<'l>,
4879    dimension: JString<'l>,
4880) -> jstring {
4881    let (n, a, s, u, d) = (
4882        env.get_string(&name).map(String::from).unwrap_or_default(),
4883        env.get_string(&args).map(String::from).unwrap_or_default(),
4884        env.get_string(&source)
4885            .map(String::from)
4886            .unwrap_or_default(),
4887        env.get_string(&uuid).map(String::from).unwrap_or_default(),
4888        env.get_string(&dimension)
4889            .map(String::from)
4890            .unwrap_or_default(),
4891    );
4892    let ev = yog_abi::YogCommandEvent {
4893        name: YogStr::from_str(&n),
4894        args: YogStr::from_str(&a),
4895        source: YogStr::from_str(&s),
4896        uuid: YogStr::from_str(&u),
4897        dimension: YogStr::from_str(&d),
4898    };
4899    let h = handlers();
4900    let srv = srv_ptr();
4901    // Actual arg count of this invocation (0 for a bare command with no args).
4902    let actual_argc = if a.is_empty() {
4903        0
4904    } else {
4905        a.split('\t').count()
4906    };
4907    let reply = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
4908        let Some(regs) = h.commands.get(&n) else {
4909            return String::new();
4910        };
4911        for (module, schema, ud, f) in regs {
4912            let expected_argc = schema.as_ref().map_or(0, |s| s.split_whitespace().count());
4913            if expected_argc != actual_argc {
4914                continue;
4915            }
4916            if module.is_retiring() {
4917                continue;
4918            }
4919            let Some(_call) = module.enter() else {
4920                continue;
4921            };
4922            let mut buf = [0u8; 4096];
4923            let mut reply_len: u32 = 0;
4924            unsafe {
4925                f(
4926                    *ud,
4927                    srv,
4928                    &ev,
4929                    buf.as_mut_ptr(),
4930                    buf.len() as u32,
4931                    &mut reply_len,
4932                )
4933            };
4934            if reply_len > 0 {
4935                return String::from_utf8_lossy(&buf[..reply_len as usize]).into_owned();
4936            }
4937        }
4938        String::new()
4939    }))
4940    .unwrap_or_else(|_| {
4941        yog_logging::error!("a mod panicked handling command `{}`", n);
4942        String::new()
4943    });
4944
4945    env.new_string(reply)
4946        .map(|s| s.into_raw())
4947        .unwrap_or(std::ptr::null_mut())
4948}
4949
4950#[no_mangle]
4951pub extern "system" fn Java_dev_yog_NativeBridge_nativeItemDefs<'l>(
4952    env: JNIEnv<'l>,
4953    _class: JClass<'l>,
4954) -> jstring {
4955    let s = handlers()
4956        .items
4957        .iter()
4958        .map(|d| {
4959            let mut parts = vec![d.id.clone()];
4960            parts.push(format!("max_stack={}", d.max_stack));
4961            if let Some(n) = &d.name {
4962                parts.push(format!("name={n}"));
4963            }
4964            if let Some(t) = &d.tooltip {
4965                parts.push(format!("tooltip={t}"));
4966            }
4967            if d.max_damage > 0 {
4968                parts.push(format!("max_damage={}", d.max_damage));
4969            }
4970            if d.fire_resistant {
4971                parts.push("fire_resistant=1".into());
4972            }
4973            if d.fuel_ticks > 0 {
4974                parts.push(format!("fuel_ticks={}", d.fuel_ticks));
4975            }
4976            if let Some(f) = &d.food {
4977                parts.push(format!(
4978                    "food={}:{}:{}",
4979                    f.nutrition,
4980                    f.saturation,
4981                    if f.can_always_eat { 1 } else { 0 }
4982                ));
4983            }
4984            parts.join("\t")
4985        })
4986        .collect::<Vec<_>>()
4987        .join("\n");
4988    env.new_string(s)
4989        .map(|s| s.into_raw())
4990        .unwrap_or(std::ptr::null_mut())
4991}
4992
4993#[no_mangle]
4994pub extern "system" fn Java_dev_yog_NativeBridge_nativeBlockDefs<'l>(
4995    env: JNIEnv<'l>,
4996    _class: JClass<'l>,
4997) -> jstring {
4998    let s = handlers()
4999        .blocks
5000        .iter()
5001        .map(|d| {
5002            let mut parts = vec![d.id.clone()];
5003            parts.push(format!("hardness={}", d.hardness));
5004            parts.push(format!("resistance={}", d.resistance));
5005            if let Some(n) = &d.name {
5006                parts.push(format!("name={n}"));
5007            }
5008            if let Some(sh) = d.shape {
5009                parts.push(format!(
5010                    "shape={}:{}:{}:{}:{}:{}",
5011                    sh[0], sh[1], sh[2], sh[3], sh[4], sh[5]
5012                ));
5013            }
5014            if d.light_level > 0 {
5015                parts.push(format!("light={}", d.light_level));
5016            }
5017            if let Some(snd) = &d.sound {
5018                parts.push(format!("sound={snd}"));
5019            }
5020            if d.requires_tool {
5021                parts.push("requires_tool=1".into());
5022            }
5023            if d.no_collision {
5024                parts.push("no_collision=1".into());
5025            }
5026            if d.slipperiness > 0.0 {
5027                parts.push(format!("slipperiness={}", d.slipperiness));
5028            }
5029            if d.connects {
5030                parts.push("connects=1".into());
5031            }
5032            if !d.connect_groups.is_empty() {
5033                parts.push(format!("connect_groups={}", d.connect_groups.join(",")));
5034            }
5035            if let Some(inv) = &d.inventory_id {
5036                parts.push(format!("inventory_id={inv}"));
5037            }
5038            parts.join("\t")
5039        })
5040        .collect::<Vec<_>>()
5041        .join("\n");
5042    env.new_string(s)
5043        .map(|s| s.into_raw())
5044        .unwrap_or(std::ptr::null_mut())
5045}
5046
5047/// Tab/newline-encoded inventory defs — one line per registered
5048/// `InventoryDef` (see `yog_inventory`): `id\tslot_count=N\tlayout=x:y,...
5049/// \tinclude_player_inventory=0|1\tplayer_inv=x:y\tbackground_texture=...\ttitle=...`
5050#[no_mangle]
5051pub extern "system" fn Java_dev_yog_NativeBridge_nativeInventoryDefs<'l>(
5052    env: JNIEnv<'l>,
5053    _class: JClass<'l>,
5054) -> jstring {
5055    let s = handlers()
5056        .inventories
5057        .iter()
5058        .map(|d| {
5059            let mut parts = vec![d.id.clone()];
5060            parts.push(format!("slot_count={}", d.slot_count));
5061            parts.push(format!(
5062                "layout={}",
5063                yog_inventory::encode_layout(&d.resolved_layout())
5064            ));
5065            parts.push(format!(
5066                "include_player_inventory={}",
5067                d.include_player_inventory as u8
5068            ));
5069            parts.push(format!(
5070                "player_inv={}:{}",
5071                d.player_inv_offset.0, d.player_inv_offset.1
5072            ));
5073            if let Some(tex) = &d.background_texture {
5074                parts.push(format!("background_texture={tex}"));
5075            }
5076            if !d.title.is_empty() {
5077                parts.push(format!("title={}", d.title));
5078            }
5079            if let Some((w, h)) = d.background_size {
5080                parts.push(format!("background_size={w}:{h}"));
5081            }
5082            parts.join("\t")
5083        })
5084        .collect::<Vec<_>>()
5085        .join("\n");
5086    env.new_string(s)
5087        .map(|s| s.into_raw())
5088        .unwrap_or(std::ptr::null_mut())
5089}
5090
5091#[no_mangle]
5092pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPacket<'l>(
5093    mut env: JNIEnv<'l>,
5094    _class: JClass<'l>,
5095    channel: JString<'l>,
5096    player: JString<'l>,
5097    payload: JByteArray<'l>,
5098) {
5099    let ch = env
5100        .get_string(&channel)
5101        .map(String::from)
5102        .unwrap_or_default();
5103    let pl = env
5104        .get_string(&player)
5105        .map(String::from)
5106        .unwrap_or_default();
5107    let data = env.convert_byte_array(&payload).unwrap_or_default();
5108    let ev = yog_abi::YogPacketEvent {
5109        channel: YogStr::from_str(&ch),
5110        player: YogStr::from_str(&pl),
5111        payload: data.as_ptr(),
5112        payload_len: data.len() as u32,
5113    };
5114    let h = handlers();
5115    let srv = srv_ptr();
5116    guard("on_packet", || {
5117        if let Some((module, ud, f)) = h.packets.get(&ch) {
5118            if module.is_retiring() {
5119                return;
5120            }
5121            let Some(_call) = module.enter() else { return };
5122            unsafe { f(*ud, srv, &ev) };
5123        }
5124    });
5125}
5126
5127#[no_mangle]
5128pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientPacket<'l>(
5129    mut env: JNIEnv<'l>,
5130    _class: JClass<'l>,
5131    channel: JString<'l>,
5132    payload: JByteArray<'l>,
5133) {
5134    let ch = env
5135        .get_string(&channel)
5136        .map(String::from)
5137        .unwrap_or_default();
5138    let data = env.convert_byte_array(&payload).unwrap_or_default();
5139    let ev = yog_abi::YogPacketEvent {
5140        channel: YogStr::from_str(&ch),
5141        player: YogStr::EMPTY,
5142        payload: data.as_ptr(),
5143        payload_len: data.len() as u32,
5144    };
5145    let h = handlers();
5146    let srv = srv_ptr();
5147    guard("on_client_packet", || {
5148        if let Some((module, ud, f)) = h.client_packets.get(&ch) {
5149            if module.is_retiring() {
5150                return;
5151            }
5152            let Some(_call) = module.enter() else { return };
5153            unsafe { f(*ud, srv, &ev) };
5154        }
5155    });
5156}
5157
5158#[no_mangle]
5159pub extern "system" fn Java_dev_yog_NativeBridge_nativePacketChannels<'l>(
5160    env: JNIEnv<'l>,
5161    _class: JClass<'l>,
5162) -> jstring {
5163    let s = handlers()
5164        .packets
5165        .keys()
5166        .cloned()
5167        .collect::<Vec<_>>()
5168        .join("\n");
5169    env.new_string(s)
5170        .map(|s| s.into_raw())
5171        .unwrap_or(std::ptr::null_mut())
5172}
5173
5174#[no_mangle]
5175pub extern "system" fn Java_dev_yog_NativeBridge_nativeClientPacketChannels<'l>(
5176    env: JNIEnv<'l>,
5177    _class: JClass<'l>,
5178) -> jstring {
5179    let s = handlers()
5180        .client_packets
5181        .keys()
5182        .cloned()
5183        .collect::<Vec<_>>()
5184        .join("\n");
5185    env.new_string(s)
5186        .map(|s| s.into_raw())
5187        .unwrap_or(std::ptr::null_mut())
5188}
5189
5190#[no_mangle]
5191pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawn<'l>(
5192    mut env: JNIEnv<'l>,
5193    _class: JClass<'l>,
5194    entity_type: JString<'l>,
5195    uuid: JString<'l>,
5196    dimension: JString<'l>,
5197) {
5198    let h = handlers();
5199    if h.entity_spawn.is_empty() {
5200        return;
5201    }
5202    let (et, u, d) = (
5203        jstr!(env, entity_type),
5204        jstr!(env, uuid),
5205        jstr!(env, dimension),
5206    );
5207    let ev = yog_abi::YogEntitySpawnEvent {
5208        entity_type: YogStr::from_str(&et),
5209        uuid: YogStr::from_str(&u),
5210        dimension: YogStr::from_str(&d),
5211    };
5212    let srv = srv_ptr();
5213    guard("on_entity_spawn", || {
5214        for (module, ud, f) in &h.entity_spawn {
5215            if module.is_retiring() {
5216                continue;
5217            }
5218            let Some(_call) = module.enter() else {
5219                continue;
5220            };
5221            unsafe { f(*ud, srv, &ev, 1) };
5222        }
5223    });
5224}
5225
5226#[no_mangle]
5227pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntitySpawnPre<'l>(
5228    mut env: JNIEnv<'l>,
5229    _class: JClass<'l>,
5230    entity_type: JString<'l>,
5231    uuid: JString<'l>,
5232    dimension: JString<'l>,
5233) -> jni::sys::jboolean {
5234    let h = handlers();
5235    if h.entity_spawn.is_empty() {
5236        return 1;
5237    }
5238    let et = match env.get_string(&entity_type) {
5239        Ok(s) => String::from(s),
5240        Err(_) => return 1,
5241    };
5242    let u = match env.get_string(&uuid) {
5243        Ok(s) => String::from(s),
5244        Err(_) => return 1,
5245    };
5246    let d = match env.get_string(&dimension) {
5247        Ok(s) => String::from(s),
5248        Err(_) => return 1,
5249    };
5250    let ev = yog_abi::YogEntitySpawnEvent {
5251        entity_type: YogStr::from_str(&et),
5252        uuid: YogStr::from_str(&u),
5253        dimension: YogStr::from_str(&d),
5254    };
5255    let srv = srv_ptr();
5256    let mut allow = true;
5257    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5258        for (module, ud, f) in &h.entity_spawn {
5259            if module.is_retiring() {
5260                continue;
5261            }
5262            let Some(_call) = module.enter() else {
5263                continue;
5264            };
5265            if !unsafe { f(*ud, srv, &ev, 0) } {
5266                allow = false;
5267                break;
5268            }
5269        }
5270    }))
5271    .ok();
5272    allow as jni::sys::jboolean
5273}
5274
5275#[no_mangle]
5276pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityDamagePre<'l>(
5277    mut env: JNIEnv<'l>,
5278    _class: JClass<'l>,
5279    entity_type: JString<'l>,
5280    uuid: JString<'l>,
5281    amount: jfloat,
5282    source: JString<'l>,
5283    dimension: JString<'l>,
5284) -> jni::sys::jboolean {
5285    let h = handlers();
5286    if h.entity_damage.is_empty() {
5287        return 1;
5288    }
5289    let et = match env.get_string(&entity_type) {
5290        Ok(s) => String::from(s),
5291        Err(_) => return 1,
5292    };
5293    let u = match env.get_string(&uuid) {
5294        Ok(s) => String::from(s),
5295        Err(_) => return 1,
5296    };
5297    let s = match env.get_string(&source) {
5298        Ok(s) => String::from(s),
5299        Err(_) => return 1,
5300    };
5301    let d = match env.get_string(&dimension) {
5302        Ok(s) => String::from(s),
5303        Err(_) => return 1,
5304    };
5305    let ev = yog_abi::YogEntityDamageEvent {
5306        entity_type: YogStr::from_str(&et),
5307        uuid: YogStr::from_str(&u),
5308        amount,
5309        source: YogStr::from_str(&s),
5310        dimension: YogStr::from_str(&d),
5311    };
5312    let srv = srv_ptr();
5313    let mut allow = true;
5314    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5315        for (module, ud, f) in &h.entity_damage {
5316            if module.is_retiring() {
5317                continue;
5318            }
5319            let Some(_call) = module.enter() else {
5320                continue;
5321            };
5322            if !unsafe { f(*ud, srv, &ev, 0) } {
5323                allow = false;
5324                break;
5325            }
5326        }
5327    }))
5328    .ok();
5329    allow as jni::sys::jboolean
5330}
5331
5332#[no_mangle]
5333pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlockPre<'l>(
5334    mut env: JNIEnv<'l>,
5335    _class: JClass<'l>,
5336    player: JString<'l>,
5337    block: JString<'l>,
5338    x: jint,
5339    y: jint,
5340    z: jint,
5341    dimension: JString<'l>,
5342) -> jni::sys::jboolean {
5343    let h = handlers();
5344    if h.player_place_block.is_empty() {
5345        return 1;
5346    }
5347    let p = match env.get_string(&player) {
5348        Ok(s) => String::from(s),
5349        Err(_) => return 1,
5350    };
5351    let b = match env.get_string(&block) {
5352        Ok(s) => String::from(s),
5353        Err(_) => return 1,
5354    };
5355    let d = match env.get_string(&dimension) {
5356        Ok(s) => String::from(s),
5357        Err(_) => return 1,
5358    };
5359    let ev = YogPlaceBlockEvent {
5360        player: YogStr::from_str(&p),
5361        block: YogStr::from_str(&b),
5362        pos: YogBlockPos { x, y, z },
5363        dimension: YogStr::from_str(&d),
5364    };
5365    let srv = srv_ptr();
5366    let mut allow = true;
5367    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5368        for (module, ud, f) in &h.player_place_block {
5369            if module.is_retiring() {
5370                continue;
5371            }
5372            let Some(_call) = module.enter() else {
5373                continue;
5374            };
5375            if !unsafe { f(*ud, srv, &ev, 0) } {
5376                allow = false;
5377                break;
5378            }
5379        }
5380    }))
5381    .ok();
5382    allow as jni::sys::jboolean
5383}
5384
5385#[no_mangle]
5386pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlaceBlock<'l>(
5387    mut env: JNIEnv<'l>,
5388    _class: JClass<'l>,
5389    player: JString<'l>,
5390    block: JString<'l>,
5391    x: jint,
5392    y: jint,
5393    z: jint,
5394    dimension: JString<'l>,
5395) {
5396    let h = handlers();
5397    if h.player_place_block.is_empty() {
5398        return;
5399    }
5400    let (p, b, d) = (jstr!(env, player), jstr!(env, block), jstr!(env, dimension));
5401    let ev = YogPlaceBlockEvent {
5402        player: YogStr::from_str(&p),
5403        block: YogStr::from_str(&b),
5404        pos: YogBlockPos { x, y, z },
5405        dimension: YogStr::from_str(&d),
5406    };
5407    let srv = srv_ptr();
5408    guard("on_player_place_block", || {
5409        for (module, ud, f) in &h.player_place_block {
5410            if module.is_retiring() {
5411                continue;
5412            }
5413            let Some(_call) = module.enter() else {
5414                continue;
5415            };
5416            unsafe { f(*ud, srv, &ev, 1) };
5417        }
5418    });
5419}
5420
5421#[no_mangle]
5422pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeathPre<'l>(
5423    mut env: JNIEnv<'l>,
5424    _class: JClass<'l>,
5425    player: JString<'l>,
5426    uuid: JString<'l>,
5427    source: JString<'l>,
5428    dimension: JString<'l>,
5429) -> jni::sys::jboolean {
5430    let h = handlers();
5431    if h.player_death.is_empty() {
5432        return 1;
5433    }
5434    let p = match env.get_string(&player) {
5435        Ok(s) => String::from(s),
5436        Err(_) => return 1,
5437    };
5438    let u = match env.get_string(&uuid) {
5439        Ok(s) => String::from(s),
5440        Err(_) => return 1,
5441    };
5442    let s = match env.get_string(&source) {
5443        Ok(s) => String::from(s),
5444        Err(_) => return 1,
5445    };
5446    let d = match env.get_string(&dimension) {
5447        Ok(s) => String::from(s),
5448        Err(_) => return 1,
5449    };
5450    let ev = YogPlayerDeathEvent {
5451        player: YogStr::from_str(&p),
5452        uuid: YogStr::from_str(&u),
5453        source: YogStr::from_str(&s),
5454        dimension: YogStr::from_str(&d),
5455    };
5456    let srv = srv_ptr();
5457    let mut allow = true;
5458    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5459        for (module, ud, f) in &h.player_death {
5460            if module.is_retiring() {
5461                continue;
5462            }
5463            let Some(_call) = module.enter() else {
5464                continue;
5465            };
5466            if !unsafe { f(*ud, srv, &ev, 0) } {
5467                allow = false;
5468                break;
5469            }
5470        }
5471    }))
5472    .ok();
5473    allow as jni::sys::jboolean
5474}
5475
5476#[no_mangle]
5477pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerDeath<'l>(
5478    mut env: JNIEnv<'l>,
5479    _class: JClass<'l>,
5480    player: JString<'l>,
5481    uuid: JString<'l>,
5482    source: JString<'l>,
5483    dimension: JString<'l>,
5484) {
5485    let h = handlers();
5486    if h.player_death.is_empty() {
5487        return;
5488    }
5489    let (p, u, s, d) = (
5490        jstr!(env, player),
5491        jstr!(env, uuid),
5492        jstr!(env, source),
5493        jstr!(env, dimension),
5494    );
5495    let ev = YogPlayerDeathEvent {
5496        player: YogStr::from_str(&p),
5497        uuid: YogStr::from_str(&u),
5498        source: YogStr::from_str(&s),
5499        dimension: YogStr::from_str(&d),
5500    };
5501    let srv = srv_ptr();
5502    guard("on_player_death", || {
5503        for (module, ud, f) in &h.player_death {
5504            if module.is_retiring() {
5505                continue;
5506            }
5507            let Some(_call) = module.enter() else {
5508                continue;
5509            };
5510            unsafe { f(*ud, srv, &ev, 1) };
5511        }
5512    });
5513}
5514
5515#[no_mangle]
5516pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerRespawn<'l>(
5517    mut env: JNIEnv<'l>,
5518    _class: JClass<'l>,
5519    player: JString<'l>,
5520    uuid: JString<'l>,
5521    at_anchor: jni::sys::jboolean,
5522    dimension: JString<'l>,
5523) {
5524    let h = handlers();
5525    if h.player_respawn.is_empty() {
5526        return;
5527    }
5528    let (p, u, d) = (jstr!(env, player), jstr!(env, uuid), jstr!(env, dimension));
5529    let ev = YogPlayerRespawnEvent {
5530        player: YogStr::from_str(&p),
5531        uuid: YogStr::from_str(&u),
5532        at_anchor: at_anchor != 0,
5533        dimension: YogStr::from_str(&d),
5534    };
5535    let srv = srv_ptr();
5536    guard("on_player_respawn", || {
5537        for (module, ud, f) in &h.player_respawn {
5538            if module.is_retiring() {
5539                continue;
5540            }
5541            let Some(_call) = module.enter() else {
5542                continue;
5543            };
5544            unsafe { f(*ud, srv, &ev, 1) };
5545        }
5546    });
5547}
5548
5549#[no_mangle]
5550pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnAdvancement<'l>(
5551    mut env: JNIEnv<'l>,
5552    _class: JClass<'l>,
5553    player: JString<'l>,
5554    uuid: JString<'l>,
5555    advancement: JString<'l>,
5556    dimension: JString<'l>,
5557) {
5558    let h = handlers();
5559    if h.advancement.is_empty() {
5560        return;
5561    }
5562    let (p, u, a, d) = (
5563        jstr!(env, player),
5564        jstr!(env, uuid),
5565        jstr!(env, advancement),
5566        jstr!(env, dimension),
5567    );
5568    let ev = YogAdvancementEvent {
5569        player: YogStr::from_str(&p),
5570        uuid: YogStr::from_str(&u),
5571        advancement: YogStr::from_str(&a),
5572        dimension: YogStr::from_str(&d),
5573    };
5574    let srv = srv_ptr();
5575    guard("on_advancement", || {
5576        for (module, ud, f) in &h.advancement {
5577            if module.is_retiring() {
5578                continue;
5579            }
5580            let Some(_call) = module.enter() else {
5581                continue;
5582            };
5583            unsafe { f(*ud, srv, &ev, 1) };
5584        }
5585    });
5586}
5587
5588#[no_mangle]
5589pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteractPre<'l>(
5590    mut env: JNIEnv<'l>,
5591    _class: JClass<'l>,
5592    player: JString<'l>,
5593    player_uuid: JString<'l>,
5594    entity_type: JString<'l>,
5595    entity_uuid: JString<'l>,
5596    hand: JString<'l>,
5597    dimension: JString<'l>,
5598) -> jni::sys::jboolean {
5599    let h = handlers();
5600    if h.entity_interact.is_empty() {
5601        return 1;
5602    }
5603    let p = match env.get_string(&player) {
5604        Ok(s) => String::from(s),
5605        Err(_) => return 1,
5606    };
5607    let pu = match env.get_string(&player_uuid) {
5608        Ok(s) => String::from(s),
5609        Err(_) => return 1,
5610    };
5611    let et = match env.get_string(&entity_type) {
5612        Ok(s) => String::from(s),
5613        Err(_) => return 1,
5614    };
5615    let eu = match env.get_string(&entity_uuid) {
5616        Ok(s) => String::from(s),
5617        Err(_) => return 1,
5618    };
5619    let ha = match env.get_string(&hand) {
5620        Ok(s) => String::from(s),
5621        Err(_) => return 1,
5622    };
5623    let d = match env.get_string(&dimension) {
5624        Ok(s) => String::from(s),
5625        Err(_) => return 1,
5626    };
5627    let ev = YogEntityInteractEvent {
5628        player: YogStr::from_str(&p),
5629        player_uuid: YogStr::from_str(&pu),
5630        entity_type: YogStr::from_str(&et),
5631        entity_uuid: YogStr::from_str(&eu),
5632        hand: YogStr::from_str(&ha),
5633        dimension: YogStr::from_str(&d),
5634    };
5635    let srv = srv_ptr();
5636    let mut allow = true;
5637    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5638        for (module, ud, f) in &h.entity_interact {
5639            if module.is_retiring() {
5640                continue;
5641            }
5642            let Some(_call) = module.enter() else {
5643                continue;
5644            };
5645            if !unsafe { f(*ud, srv, &ev, 0) } {
5646                allow = false;
5647                break;
5648            }
5649        }
5650    }))
5651    .ok();
5652    allow as jni::sys::jboolean
5653}
5654
5655#[no_mangle]
5656pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnEntityInteract<'l>(
5657    mut env: JNIEnv<'l>,
5658    _class: JClass<'l>,
5659    player: JString<'l>,
5660    player_uuid: JString<'l>,
5661    entity_type: JString<'l>,
5662    entity_uuid: JString<'l>,
5663    hand: JString<'l>,
5664    dimension: JString<'l>,
5665) {
5666    let h = handlers();
5667    if h.entity_interact.is_empty() {
5668        return;
5669    }
5670    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
5671    let (et, eu, ha, d) = (
5672        jstr!(env, entity_type),
5673        jstr!(env, entity_uuid),
5674        jstr!(env, hand),
5675        jstr!(env, dimension),
5676    );
5677    let ev = YogEntityInteractEvent {
5678        player: YogStr::from_str(&p),
5679        player_uuid: YogStr::from_str(&pu),
5680        entity_type: YogStr::from_str(&et),
5681        entity_uuid: YogStr::from_str(&eu),
5682        hand: YogStr::from_str(&ha),
5683        dimension: YogStr::from_str(&d),
5684    };
5685    let srv = srv_ptr();
5686    guard("on_entity_interact", || {
5687        for (module, ud, f) in &h.entity_interact {
5688            if module.is_retiring() {
5689                continue;
5690            }
5691            let Some(_call) = module.enter() else {
5692                continue;
5693            };
5694            unsafe { f(*ud, srv, &ev, 1) };
5695        }
5696    });
5697}
5698
5699#[no_mangle]
5700pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemCraft<'l>(
5701    mut env: JNIEnv<'l>,
5702    _class: JClass<'l>,
5703    player: JString<'l>,
5704    player_uuid: JString<'l>,
5705    result_item: JString<'l>,
5706    result_count: jint,
5707    dimension: JString<'l>,
5708) {
5709    let h = handlers();
5710    if h.item_craft.is_empty() {
5711        return;
5712    }
5713    let (p, pu, ri, d) = (
5714        jstr!(env, player),
5715        jstr!(env, player_uuid),
5716        jstr!(env, result_item),
5717        jstr!(env, dimension),
5718    );
5719    let ev = YogCraftEvent {
5720        player: YogStr::from_str(&p),
5721        player_uuid: YogStr::from_str(&pu),
5722        result_item: YogStr::from_str(&ri),
5723        result_count: result_count as u32,
5724        dimension: YogStr::from_str(&d),
5725    };
5726    let srv = srv_ptr();
5727    guard("on_item_craft", || {
5728        for (module, ud, f) in &h.item_craft {
5729            if module.is_retiring() {
5730                continue;
5731            }
5732            let Some(_call) = module.enter() else {
5733                continue;
5734            };
5735            unsafe { f(*ud, srv, &ev, 1) };
5736        }
5737    });
5738}
5739
5740#[no_mangle]
5741pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosionPre<'l>(
5742    mut env: JNIEnv<'l>,
5743    _class: JClass<'l>,
5744    dimension: JString<'l>,
5745    x: jdouble,
5746    y: jdouble,
5747    z: jdouble,
5748    power: jfloat,
5749    cause_uuid: JString<'l>,
5750) -> jni::sys::jboolean {
5751    let h = handlers();
5752    if h.explosion.is_empty() {
5753        return 1;
5754    }
5755    let d = match env.get_string(&dimension) {
5756        Ok(s) => String::from(s),
5757        Err(_) => return 1,
5758    };
5759    let cu = match env.get_string(&cause_uuid) {
5760        Ok(s) => String::from(s),
5761        Err(_) => return 1,
5762    };
5763    let ev = YogExplosionEvent {
5764        dimension: YogStr::from_str(&d),
5765        x,
5766        y,
5767        z,
5768        power,
5769        cause_uuid: YogStr::from_str(&cu),
5770    };
5771    let srv = srv_ptr();
5772    let mut allow = true;
5773    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5774        for (module, ud, f) in &h.explosion {
5775            if module.is_retiring() {
5776                continue;
5777            }
5778            let Some(_call) = module.enter() else {
5779                continue;
5780            };
5781            if !unsafe { f(*ud, srv, &ev, 0) } {
5782                allow = false;
5783                break;
5784            }
5785        }
5786    }))
5787    .ok();
5788    allow as jni::sys::jboolean
5789}
5790
5791#[no_mangle]
5792pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnExplosion<'l>(
5793    mut env: JNIEnv<'l>,
5794    _class: JClass<'l>,
5795    dimension: JString<'l>,
5796    x: jdouble,
5797    y: jdouble,
5798    z: jdouble,
5799    power: jfloat,
5800    cause_uuid: JString<'l>,
5801) {
5802    let h = handlers();
5803    if h.explosion.is_empty() {
5804        return;
5805    }
5806    let (d, cu) = (jstr!(env, dimension), jstr!(env, cause_uuid));
5807    let ev = YogExplosionEvent {
5808        dimension: YogStr::from_str(&d),
5809        x,
5810        y,
5811        z,
5812        power,
5813        cause_uuid: YogStr::from_str(&cu),
5814    };
5815    let srv = srv_ptr();
5816    guard("on_explosion", || {
5817        for (module, ud, f) in &h.explosion {
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// ── ABI minor 9 JNI entry points ─────────────────────────────────────────────
5830
5831#[no_mangle]
5832pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickupPre<'l>(
5833    mut env: JNIEnv<'l>,
5834    _class: JClass<'l>,
5835    player: JString<'l>,
5836    player_uuid: JString<'l>,
5837    item_id: JString<'l>,
5838    item_count: jint,
5839    entity_uuid: JString<'l>,
5840    dimension: JString<'l>,
5841) -> jni::sys::jboolean {
5842    let h = handlers();
5843    if h.item_pickup.is_empty() {
5844        return 1;
5845    }
5846    let p = match env.get_string(&player) {
5847        Ok(s) => String::from(s),
5848        Err(_) => return 1,
5849    };
5850    let pu = match env.get_string(&player_uuid) {
5851        Ok(s) => String::from(s),
5852        Err(_) => return 1,
5853    };
5854    let ii = match env.get_string(&item_id) {
5855        Ok(s) => String::from(s),
5856        Err(_) => return 1,
5857    };
5858    let eu = match env.get_string(&entity_uuid) {
5859        Ok(s) => String::from(s),
5860        Err(_) => return 1,
5861    };
5862    let d = match env.get_string(&dimension) {
5863        Ok(s) => String::from(s),
5864        Err(_) => return 1,
5865    };
5866    let ev = YogItemPickupEvent {
5867        player: YogStr::from_str(&p),
5868        player_uuid: YogStr::from_str(&pu),
5869        item_id: YogStr::from_str(&ii),
5870        item_count: item_count as u32,
5871        entity_uuid: YogStr::from_str(&eu),
5872        dimension: YogStr::from_str(&d),
5873    };
5874    let srv = srv_ptr();
5875    let mut allow = true;
5876    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
5877        for (module, ud, f) in &h.item_pickup {
5878            if module.is_retiring() {
5879                continue;
5880            }
5881            let Some(_call) = module.enter() else {
5882                continue;
5883            };
5884            if !unsafe { f(*ud, srv, &ev, 0) } {
5885                allow = false;
5886                break;
5887            }
5888        }
5889    }))
5890    .ok();
5891    allow as jni::sys::jboolean
5892}
5893
5894#[no_mangle]
5895pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnItemPickup<'l>(
5896    mut env: JNIEnv<'l>,
5897    _class: JClass<'l>,
5898    player: JString<'l>,
5899    player_uuid: JString<'l>,
5900    item_id: JString<'l>,
5901    item_count: jint,
5902    entity_uuid: JString<'l>,
5903    dimension: JString<'l>,
5904) {
5905    let h = handlers();
5906    if h.item_pickup.is_empty() {
5907        return;
5908    }
5909    let (p, pu) = (jstr!(env, player), jstr!(env, player_uuid));
5910    let (ii, eu, d) = (
5911        jstr!(env, item_id),
5912        jstr!(env, entity_uuid),
5913        jstr!(env, dimension),
5914    );
5915    let ev = YogItemPickupEvent {
5916        player: YogStr::from_str(&p),
5917        player_uuid: YogStr::from_str(&pu),
5918        item_id: YogStr::from_str(&ii),
5919        item_count: item_count as u32,
5920        entity_uuid: YogStr::from_str(&eu),
5921        dimension: YogStr::from_str(&d),
5922    };
5923    let srv = srv_ptr();
5924    guard("on_item_pickup", || {
5925        for (module, ud, f) in &h.item_pickup {
5926            if module.is_retiring() {
5927                continue;
5928            }
5929            let Some(_call) = module.enter() else {
5930                continue;
5931            };
5932            unsafe { f(*ud, srv, &ev, 1) };
5933        }
5934    });
5935}
5936
5937#[no_mangle]
5938pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnPlayerMove<'l>(
5939    mut env: JNIEnv<'l>,
5940    _class: JClass<'l>,
5941    player: JString<'l>,
5942    player_uuid: JString<'l>,
5943    x: jdouble,
5944    y: jdouble,
5945    z: jdouble,
5946    yaw: jfloat,
5947    pitch: jfloat,
5948    dimension: JString<'l>,
5949) {
5950    let h = handlers();
5951    if h.player_move.is_empty() {
5952        return;
5953    }
5954    let (p, pu, d) = (
5955        jstr!(env, player),
5956        jstr!(env, player_uuid),
5957        jstr!(env, dimension),
5958    );
5959    let ev = YogPlayerMoveEvent {
5960        player: YogStr::from_str(&p),
5961        player_uuid: YogStr::from_str(&pu),
5962        x,
5963        y,
5964        z,
5965        yaw,
5966        pitch,
5967        dimension: YogStr::from_str(&d),
5968    };
5969    let srv = srv_ptr();
5970    guard("on_player_move", || {
5971        for (module, ud, f) in &h.player_move {
5972            if module.is_retiring() {
5973                continue;
5974            }
5975            let Some(_call) = module.enter() else {
5976                continue;
5977            };
5978            unsafe { f(*ud, srv, &ev, 1) };
5979        }
5980    });
5981}
5982
5983#[no_mangle]
5984pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpenPre<'l>(
5985    mut env: JNIEnv<'l>,
5986    _class: JClass<'l>,
5987    player: JString<'l>,
5988    player_uuid: JString<'l>,
5989    dimension: JString<'l>,
5990) -> jni::sys::jboolean {
5991    let h = handlers();
5992    if h.container_open.is_empty() {
5993        return 1;
5994    }
5995    let p = match env.get_string(&player) {
5996        Ok(s) => String::from(s),
5997        Err(_) => return 1,
5998    };
5999    let pu = match env.get_string(&player_uuid) {
6000        Ok(s) => String::from(s),
6001        Err(_) => return 1,
6002    };
6003    let d = match env.get_string(&dimension) {
6004        Ok(s) => String::from(s),
6005        Err(_) => return 1,
6006    };
6007    let ev = YogContainerOpenEvent {
6008        player: YogStr::from_str(&p),
6009        player_uuid: YogStr::from_str(&pu),
6010        container_type: YogStr::EMPTY,
6011        dimension: YogStr::from_str(&d),
6012    };
6013    let srv = srv_ptr();
6014    let mut allow = true;
6015    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6016        for (module, ud, f) in &h.container_open {
6017            if module.is_retiring() {
6018                continue;
6019            }
6020            let Some(_call) = module.enter() else {
6021                continue;
6022            };
6023            if !unsafe { f(*ud, srv, &ev, 0) } {
6024                allow = false;
6025                break;
6026            }
6027        }
6028    }))
6029    .ok();
6030    allow as jni::sys::jboolean
6031}
6032
6033#[no_mangle]
6034pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerOpen<'l>(
6035    mut env: JNIEnv<'l>,
6036    _class: JClass<'l>,
6037    player: JString<'l>,
6038    player_uuid: JString<'l>,
6039    container_type: JString<'l>,
6040    dimension: JString<'l>,
6041) {
6042    let h = handlers();
6043    if h.container_open.is_empty() {
6044        return;
6045    }
6046    let (p, pu, ct, d) = (
6047        jstr!(env, player),
6048        jstr!(env, player_uuid),
6049        jstr!(env, container_type),
6050        jstr!(env, dimension),
6051    );
6052    let ev = YogContainerOpenEvent {
6053        player: YogStr::from_str(&p),
6054        player_uuid: YogStr::from_str(&pu),
6055        container_type: YogStr::from_str(&ct),
6056        dimension: YogStr::from_str(&d),
6057    };
6058    let srv = srv_ptr();
6059    guard("on_container_open", || {
6060        for (module, ud, f) in &h.container_open {
6061            if module.is_retiring() {
6062                continue;
6063            }
6064            let Some(_call) = module.enter() else {
6065                continue;
6066            };
6067            unsafe { f(*ud, srv, &ev, 1) };
6068        }
6069    });
6070}
6071
6072#[no_mangle]
6073pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnContainerClose<'l>(
6074    mut env: JNIEnv<'l>,
6075    _class: JClass<'l>,
6076    player: JString<'l>,
6077    player_uuid: JString<'l>,
6078    dimension: JString<'l>,
6079) {
6080    let h = handlers();
6081    if h.container_close.is_empty() {
6082        return;
6083    }
6084    let (p, pu, d) = (
6085        jstr!(env, player),
6086        jstr!(env, player_uuid),
6087        jstr!(env, dimension),
6088    );
6089    let ev = YogContainerCloseEvent {
6090        player: YogStr::from_str(&p),
6091        player_uuid: YogStr::from_str(&pu),
6092        dimension: YogStr::from_str(&d),
6093    };
6094    let srv = srv_ptr();
6095    guard("on_container_close", || {
6096        for (module, ud, f) in &h.container_close {
6097            if module.is_retiring() {
6098                continue;
6099            }
6100            let Some(_call) = module.enter() else {
6101                continue;
6102            };
6103            unsafe { f(*ud, srv, &ev, 1) };
6104        }
6105    });
6106}
6107
6108#[no_mangle]
6109pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHitPre<'l>(
6110    mut env: JNIEnv<'l>,
6111    _class: JClass<'l>,
6112    projectile_type: JString<'l>,
6113    projectile_uuid: JString<'l>,
6114    shooter_uuid: JString<'l>,
6115    hit_type: JString<'l>,
6116    hit_entity_uuid: JString<'l>,
6117    x: jdouble,
6118    y: jdouble,
6119    z: jdouble,
6120    dimension: JString<'l>,
6121) -> jni::sys::jboolean {
6122    let h = handlers();
6123    if h.projectile_hit.is_empty() {
6124        return 1;
6125    }
6126    let pt = match env.get_string(&projectile_type) {
6127        Ok(s) => String::from(s),
6128        Err(_) => return 1,
6129    };
6130    let pu = match env.get_string(&projectile_uuid) {
6131        Ok(s) => String::from(s),
6132        Err(_) => return 1,
6133    };
6134    let su = match env.get_string(&shooter_uuid) {
6135        Ok(s) => String::from(s),
6136        Err(_) => return 1,
6137    };
6138    let ht = match env.get_string(&hit_type) {
6139        Ok(s) => String::from(s),
6140        Err(_) => return 1,
6141    };
6142    let heu = match env.get_string(&hit_entity_uuid) {
6143        Ok(s) => String::from(s),
6144        Err(_) => return 1,
6145    };
6146    let dim = match env.get_string(&dimension) {
6147        Ok(s) => String::from(s),
6148        Err(_) => return 1,
6149    };
6150    let ev = YogProjectileHitEvent {
6151        projectile_type: YogStr::from_str(&pt),
6152        projectile_uuid: YogStr::from_str(&pu),
6153        shooter_uuid: YogStr::from_str(&su),
6154        hit_type: YogStr::from_str(&ht),
6155        hit_entity_uuid: YogStr::from_str(&heu),
6156        x,
6157        y,
6158        z,
6159        dimension: YogStr::from_str(&dim),
6160    };
6161    let srv = srv_ptr();
6162    let mut allow = true;
6163    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6164        for (module, ud, f) in &h.projectile_hit {
6165            if module.is_retiring() {
6166                continue;
6167            }
6168            let Some(_call) = module.enter() else {
6169                continue;
6170            };
6171            if !unsafe { f(*ud, srv, &ev, 0) } {
6172                allow = false;
6173                break;
6174            }
6175        }
6176    }))
6177    .ok();
6178    allow as jni::sys::jboolean
6179}
6180
6181#[no_mangle]
6182pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnProjectileHit<'l>(
6183    mut env: JNIEnv<'l>,
6184    _class: JClass<'l>,
6185    projectile_type: JString<'l>,
6186    projectile_uuid: JString<'l>,
6187    shooter_uuid: JString<'l>,
6188    hit_type: JString<'l>,
6189    hit_entity_uuid: JString<'l>,
6190    x: jdouble,
6191    y: jdouble,
6192    z: jdouble,
6193    dimension: JString<'l>,
6194) {
6195    let h = handlers();
6196    if h.projectile_hit.is_empty() {
6197        return;
6198    }
6199    let (pt, pu) = (jstr!(env, projectile_type), jstr!(env, projectile_uuid));
6200    let (su, ht) = (jstr!(env, shooter_uuid), jstr!(env, hit_type));
6201    let (heu, dim) = (jstr!(env, hit_entity_uuid), jstr!(env, dimension));
6202    let ev = YogProjectileHitEvent {
6203        projectile_type: YogStr::from_str(&pt),
6204        projectile_uuid: YogStr::from_str(&pu),
6205        shooter_uuid: YogStr::from_str(&su),
6206        hit_type: YogStr::from_str(&ht),
6207        hit_entity_uuid: YogStr::from_str(&heu),
6208        x,
6209        y,
6210        z,
6211        dimension: YogStr::from_str(&dim),
6212    };
6213    let srv = srv_ptr();
6214    guard("on_projectile_hit", || {
6215        for (module, ud, f) in &h.projectile_hit {
6216            if module.is_retiring() {
6217                continue;
6218            }
6219            let Some(_call) = module.enter() else {
6220                continue;
6221            };
6222            unsafe { f(*ud, srv, &ev, 1) };
6223        }
6224    });
6225}
6226
6227// ── ABI minor 10 — client-side JNI entry points ───────────────────────────────
6228
6229#[no_mangle]
6230pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnClientTick<'l>(
6231    _env: JNIEnv<'l>,
6232    _class: JClass<'l>,
6233) {
6234    let h = handlers();
6235    if h.client_tick.is_empty() {
6236        return;
6237    }
6238    guard("on_client_tick", || {
6239        for (module, ud, f) in &h.client_tick {
6240            if module.is_retiring() {
6241                continue;
6242            }
6243            let Some(_call) = module.enter() else {
6244                continue;
6245            };
6246            unsafe { f(*ud) };
6247        }
6248    });
6249}
6250
6251#[no_mangle]
6252pub extern "system" fn Java_dev_yog_NativeBridge_nativeGlInit<'l>(
6253    _env: JNIEnv<'l>,
6254    _class: JClass<'l>,
6255) {
6256    if GL.get().is_some() {
6257        return;
6258    }
6259    let mut raw_get_binary: usize = 0;
6260    let mut raw_prog_binary: usize = 0;
6261    let gl = unsafe {
6262        glow::Context::from_loader_function(|sym| {
6263            let Some(mut env) = get_env() else {
6264                return std::ptr::null();
6265            };
6266            let jsym = match env.new_string(sym) {
6267                Ok(s) => s,
6268                Err(_) => return std::ptr::null(),
6269            };
6270            let jsym_obj: JObject = jsym.into();
6271            let val = env.call_static_method(
6272                "dev/yog/NativeBridge",
6273                "glProcAddress",
6274                "(Ljava/lang/String;)J",
6275                &[JValue::Object(&jsym_obj)],
6276            );
6277            let ptr = match val.and_then(|v| v.j()) {
6278                Ok(p) if p != 0 => p as usize as *const _,
6279                _ => std::ptr::null(),
6280            };
6281            // Capture extension pointers while the loader runs.
6282            match sym {
6283                "glGetProgramBinary" => raw_get_binary = ptr as usize,
6284                "glProgramBinary" => raw_prog_binary = ptr as usize,
6285                _ => {}
6286            }
6287            ptr
6288        })
6289    };
6290    let _ = GL.set(GlCtx(gl));
6291    let _ = GL_GET_PROGRAM_BINARY.set(if raw_get_binary != 0 {
6292        Some(raw_get_binary)
6293    } else {
6294        None
6295    });
6296    let _ = GL_PROGRAM_BINARY.set(if raw_prog_binary != 0 {
6297        Some(raw_prog_binary)
6298    } else {
6299        None
6300    });
6301    // `glGetProgramiv` is a core function; always available.  We look it up once here
6302    // to avoid depending on glow internals for the PROGRAM_BINARY_LENGTH query.
6303    if let Some(mut env) = get_env() {
6304        if let Ok(jsym) = env.new_string("glGetProgramiv") {
6305            let jsym_obj: JObject = jsym.into();
6306            if let Ok(jv) = env.call_static_method(
6307                "dev/yog/NativeBridge",
6308                "glProcAddress",
6309                "(Ljava/lang/String;)J",
6310                &[JValue::Object(&jsym_obj)],
6311            ) {
6312                if let Ok(ptr) = jv.j() {
6313                    let _ = GL_GET_PROGRAM_IV.set(if ptr != 0 { Some(ptr as usize) } else { None });
6314                }
6315            }
6316        }
6317    }
6318}
6319
6320#[no_mangle]
6321pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnHudRender<'l>(
6322    _env: JNIEnv<'l>,
6323    _class: JClass<'l>,
6324    delta_tick: jfloat,
6325    screen_w: jint,
6326    screen_h: jint,
6327    scale_factor: jfloat,
6328    player_x: jfloat,
6329    player_y: jfloat,
6330    player_z: jfloat,
6331) {
6332    let h = handlers();
6333    let mut gfx = GFX_FN_TABLE;
6334    gfx.screen_w = screen_w;
6335    gfx.screen_h = screen_h;
6336    gfx.delta_tick = delta_tick;
6337    gfx.scale_factor = scale_factor;
6338    gfx.player_pos = [player_x, player_y, player_z];
6339
6340    // Mod hud_render callbacks.
6341    if !h.hud_render.is_empty() {
6342        guard("on_hud_render", || {
6343            for (module, ud, f) in &h.hud_render {
6344                if module.is_retiring() {
6345                    continue;
6346                }
6347                let Some(_call) = module.enter() else {
6348                    continue;
6349                };
6350                unsafe { f(*ud, &gfx) };
6351            }
6352        });
6353    }
6354
6355    // Render active book UIs.
6356    let active_layers: Vec<UiLayer> = h.active_uis.lock().unwrap().clone();
6357    let sw = screen_w as f32;
6358    let sh = screen_h as f32;
6359    let ctx = unsafe { yog_gfx::GfxContext::from_raw(&gfx as *const _) };
6360    let mut renderers = h.book_renderers.lock().unwrap();
6361    for layer in &active_layers {
6362        if !layer.visible {
6363            continue;
6364        }
6365        if let Some(renderer) = renderers.get_mut(&layer.id) {
6366            renderer.render(&ctx, sw, sh);
6367        }
6368    }
6369}
6370
6371#[no_mangle]
6372pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnWorldRender<'l>(
6373    env: JNIEnv<'l>,
6374    _class: JClass<'l>,
6375    delta_tick: jfloat,
6376    screen_w: jint,
6377    screen_h: jint,
6378    scale_factor: jfloat,
6379    view_proj_arr: JFloatArray<'l>,
6380    cam_x: jfloat,
6381    cam_y: jfloat,
6382    cam_z: jfloat,
6383    player_x: jfloat,
6384    player_y: jfloat,
6385    player_z: jfloat,
6386) {
6387    let h = handlers();
6388    if h.world_render.is_empty() {
6389        return;
6390    }
6391    let mut view_proj = [0f32; 16];
6392    if env
6393        .get_float_array_region(&view_proj_arr, 0, &mut view_proj)
6394        .is_err()
6395    {
6396        return;
6397    }
6398    let mut gfx = GFX_FN_TABLE;
6399    gfx.screen_w = screen_w;
6400    gfx.screen_h = screen_h;
6401    gfx.delta_tick = delta_tick;
6402    gfx.scale_factor = scale_factor;
6403    gfx.view_proj = view_proj;
6404    gfx.camera_pos = [cam_x, cam_y, cam_z];
6405    gfx.player_pos = [player_x, player_y, player_z];
6406    guard("on_world_render", || {
6407        for (module, ud, f) in &h.world_render {
6408            if module.is_retiring() {
6409                continue;
6410            }
6411            let Some(_call) = module.enter() else {
6412                continue;
6413            };
6414            unsafe { f(*ud, &gfx) };
6415        }
6416    });
6417}
6418
6419#[no_mangle]
6420pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnKeyPress<'l>(
6421    _env: JNIEnv<'l>,
6422    _class: JClass<'l>,
6423    key_code: jint,
6424    scan_code: jint,
6425    action: jint,
6426    modifiers: jint,
6427) -> jni::sys::jboolean {
6428    let h = handlers();
6429    if h.key_press.is_empty() {
6430        return 1;
6431    }
6432    let ev = YogKeyPressEvent {
6433        key_code,
6434        scan_code,
6435        action,
6436        modifiers,
6437    };
6438    let mut allow = true;
6439    std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
6440        for (module, ud, f) in &h.key_press {
6441            if module.is_retiring() {
6442                continue;
6443            }
6444            let Some(_call) = module.enter() else {
6445                continue;
6446            };
6447            if !unsafe { f(*ud, &ev) } {
6448                allow = false;
6449                break;
6450            }
6451        }
6452    }))
6453    .ok();
6454    allow as jni::sys::jboolean
6455}
6456
6457#[no_mangle]
6458pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenOpen<'l>(
6459    mut env: JNIEnv<'l>,
6460    _class: JClass<'l>,
6461    screen_class: JString<'l>,
6462) {
6463    let h = handlers();
6464    if h.screen_open.is_empty() {
6465        return;
6466    }
6467    let sc = match env.get_string(&screen_class) {
6468        Ok(s) => String::from(s),
6469        Err(_) => return,
6470    };
6471    guard("on_screen_open", || {
6472        for (module, ud, f) in &h.screen_open {
6473            if module.is_retiring() {
6474                continue;
6475            }
6476            let Some(_call) = module.enter() else {
6477                continue;
6478            };
6479            unsafe { f(*ud, YogStr::from_str(&sc)) };
6480        }
6481    });
6482}
6483
6484#[no_mangle]
6485pub extern "system" fn Java_dev_yog_NativeBridge_nativeOnScreenClose<'l>(
6486    mut env: JNIEnv<'l>,
6487    _class: JClass<'l>,
6488    screen_class: JString<'l>,
6489) {
6490    let h = handlers();
6491    if h.screen_close.is_empty() {
6492        return;
6493    }
6494    let sc = match env.get_string(&screen_class) {
6495        Ok(s) => String::from(s),
6496        Err(_) => return,
6497    };
6498    guard("on_screen_close", || {
6499        for (module, ud, f) in &h.screen_close {
6500            if module.is_retiring() {
6501                continue;
6502            }
6503            let Some(_call) = module.enter() else {
6504                continue;
6505            };
6506            unsafe { f(*ud, YogStr::from_str(&sc)) };
6507        }
6508    });
6509}
6510
6511mod control_socket;
6512mod images;
6513mod ui_jni;