yog_api/lib.rs
1//! Yog API — the single crate mod authors depend on.
2//!
3//! A facade that re-exports every Yog domain plus the central [`Registry`] hub.
4//! Add a new domain crate, re-export it here, and mods pick it up via
5//! `yog_api::*`. Items are available both flat (`yog_api::Registry`) and
6//! namespaced by domain (`yog_api::world::World`).
7
8pub mod advancements;
9pub mod body;
10mod bus;
11pub mod client;
12mod draw;
13pub mod entities;
14pub mod java;
15pub mod loot;
16pub mod mirror;
17pub mod nanite;
18// The generated code names `::yog_api`, as in a mod (the host's mirrors are made here).
19extern crate self as yog_api;
20pub mod vanilla;
21pub use bus::{EventCx, Flow, IntoFlow, emit};
22pub use service::call;
23mod interop;
24mod lang;
25mod registry;
26mod scheduler;
27mod service;
28
29#[doc(hidden)]
30pub use interop::{__yog_export_registry, __yog_serve, YogExportEntry};
31pub use interop::{call_export, export_address};
32pub use lang::{format_translation, tag_name, tr, tr_args, translation};
33pub use registry::{Mod, ModInfo, Registry, UiHandled, close_ui, installed_mods, open_ui};
34pub use yog_gfx::{
35 GfxContext, core as gfx_core, draw2d as gfx_draw2d, gl as gfx_gl, image as gfx_image,
36};
37
38/// Stable C ABI — re-exported so mods don't need a direct `yog-abi` dependency.
39pub use yog_abi::{ABI_VERSION, YogApi};
40#[doc(hidden)]
41pub use yog_abi::{YogBytes, YogReply, YogStatus};
42
43/// Yog Data — what content definitions and book pages' `data`
44/// (`Registry::on_book_page`) are; re-exported for mods.
45pub use yog_data;
46/// `#[derive(Schema)]`: a type read and written as Yog Data (stores, packets, frames).
47pub use yog_data::Schema;
48/// The names Yog shares — kinds, namespaces, lang keys — for a mod to use as the loader does.
49pub use yog_ids;
50/// The sync primitives Yog code uses (locks that outlive a panic) — a mod's too.
51pub use yog_sync as sync;
52
53pub use java::mod_loaded;
54
55/// Inter-mod communication proc-macros.
56pub use yog_interop::{
57 add_method, bench, import, inject, modify_arg, modify_constant, modify_return, modify_variable,
58 nanite, overwrite, redirect, wrap, yog_export, yog_mirror,
59};
60
61/// Re-exported so `#[yog_export]`-generated code can emit `#[::yog_api::ctor::ctor(unsafe)]`
62/// without mods needing a direct `ctor` dependency. Constructors run when the
63/// mod's `cdylib` is loaded — guaranteed to complete before the runtime calls
64/// `yog_mod_register`, so the export registry is fully populated by then.
65pub use ctor;
66
67#[doc(hidden)]
68pub use std::os::raw::c_void as __c_void;
69#[doc(hidden)]
70pub use yog_abi::{YogGfxApi as __YogGfxApi, YogStr as __YogStr};
71
72/// Export a [`Mod`] as a dynamically loadable Yog mod.
73///
74/// Generates the two C-ABI entry points the runtime looks up:
75/// - `yog_abi_version() -> u32` — version check before loading
76/// - `yog_mod_register(*const YogApi, *const c_char)` — registration entry point,
77/// receives the mod's `id` from its manifest
78///
79/// Put this once at the crate root of a `cdylib` mod:
80///
81/// ```ignore
82/// yog_api::export_mod!(MyMod);
83/// ```
84#[macro_export]
85macro_rules! export_mod {
86 ($mod_ty:ty) => {
87 #[unsafe(no_mangle)]
88 pub extern "C" fn yog_abi_version() -> u32 {
89 $crate::ABI_VERSION
90 }
91
92 /// This mod's injections (`#[inject]`), asked for before the game's
93 /// classes load: Yog Data (`yog_event::nanite::Nanites`) to `reply`.
94 #[unsafe(no_mangle)]
95 pub unsafe extern "C" fn yog_mod_nanites(reply: *const $crate::YogReply) {
96 let bytes = $crate::nanite::__yog_nanites();
97 // SAFETY: the runtime passes a live reply sink.
98 unsafe { $crate::YogReply::send(reply, &bytes) };
99 }
100
101 #[unsafe(no_mangle)]
102 pub unsafe extern "C" fn yog_mod_register(
103 api: *const $crate::YogApi,
104 mod_id_ptr: *const ::std::os::raw::c_char,
105 ) {
106 // Parse mod_id from the C string passed by the runtime.
107 let mod_id: &str = if mod_id_ptr.is_null() {
108 "unknown"
109 } else {
110 // SAFETY: a non-null id is a NUL-terminated string from the runtime.
111 match unsafe { ::std::ffi::CStr::from_ptr(mod_id_ptr) }.to_str() {
112 Ok(s) => s,
113 Err(_) => "unknown",
114 }
115 };
116 // Store for interop use (yog_api::interop::current_mod_id()).
117 $crate::__set_current_mod_id(mod_id);
118 // Every mod is handed the same global `YogApi` table, so any
119 // mod's own pointer works for reconstructing a `Registry` inside
120 // an exported function later — even when called from a thread
121 // that never ran `yog_mod_register` itself.
122 $crate::__set_current_api_ptr(api as usize);
123
124 // Catch panics so they never unwind across this `extern "C"` boundary
125 // back into the runtime (which would be undefined behaviour).
126 let outcome = ::std::panic::catch_unwind(::std::panic::AssertUnwindSafe(|| {
127 // SAFETY: the runtime passes a valid YogApi pointer, verified via
128 // yog_abi_version() and abi_version/size checks before this call.
129 let mut registry = unsafe { $crate::Registry::from_raw(api) };
130 // The world's folder known before the mod's own handlers run.
131 $crate::storage::__know_world(&mut registry);
132 <$mod_ty as $crate::Mod>::register(&mut registry);
133
134 // Blocks and items of `content/**/*.yblock|*.yitem`
135 // (`yog_api::content!()`, self-registered by `ctor`).
136 let content: ::std::vec::Vec<fn(&mut $crate::Registry)> =
137 $crate::__yog_content_registrars().lock().clone();
138 for register in content {
139 register(&mut registry);
140 }
141
142 // Every #[yog_export] function (registered by its `ctor`
143 // when the library loaded) provides `mod_id:name`.
144 for entry in $crate::__yog_export_registry().lock().iter() {
145 registry.provide_export(mod_id, entry);
146 }
147
148 // Its injections' handlers, on their points.
149 $crate::nanite::__subscribe(&mut registry);
150
151 // What it keeps, saved with the world (after the mod's own handlers).
152 $crate::storage::__save_with_world(&mut registry);
153 }));
154 if outcome.is_err() {
155 $crate::error!(
156 "mod {} panicked during register",
157 ::core::stringify!($mod_ty)
158 );
159 }
160 }
161
162 /// Yog-IDLE's screen designer: the version of the protocol below.
163 #[unsafe(no_mangle)]
164 pub extern "C" fn yog_ui_designer_abi() -> u32 {
165 $crate::ui::component::designer::ABI
166 }
167
168 /// Yog-IDLE's screen designer: lists this mod's custom components
169 /// and draws them (see `yog_ui::component::designer`). Never called
170 /// in game — only by the designer host, which loads the mod's
171 /// library built for the developer's machine.
172 #[unsafe(no_mangle)]
173 pub unsafe extern "C" fn yog_ui_designer(
174 request: $crate::YogBytes,
175 gfx: *const $crate::__YogGfxApi,
176 user_data: *mut $crate::__c_void,
177 write: $crate::ui::component::designer::WriteFn,
178 ) -> bool {
179 // SAFETY: forwarded under the same contract.
180 unsafe { $crate::ui::component::designer::call(request, gfx, user_data, write) }
181 }
182 };
183}
184
185/// Registers `.yui` components (types implementing
186/// [`ui::component::Component`]) when the mod's library loads, so screens
187/// can use `<Name …/>` and Yog-IDLE's designer host can draw them. The code
188/// `yog build` generates from a `<Component>` `.yui` calls this — mods
189/// don't write it themselves.
190#[macro_export]
191macro_rules! ui_component {
192 ($($ty:ty),+ $(,)?) => {
193 const _: () = {
194 #[$crate::ctor::ctor(unsafe, crate_path = $crate::ctor)]
195 fn __yog_register_ui_components() {
196 $( $crate::ui::component::register::<$ty>(); )+
197 }
198 };
199 };
200}
201
202/// Compiles in the mod's component `.yui` files that have no code-behind
203/// `.rs` (those with one are pulled in by its `ui_include!`) — call it once,
204/// in `src/lib.rs`:
205///
206/// ```ignore
207/// yog_api::ui_components!();
208/// ```
209///
210/// `yog build`, `yog check` and `yog ui gen` write the list to
211/// `.yog-build/generated/components.g.rs` (a module per component).
212#[macro_export]
213macro_rules! ui_components {
214 () => {
215 include!(concat!(
216 env!("CARGO_MANIFEST_DIR"),
217 "/generated/components.g.rs"
218 ));
219 };
220}
221
222/// Internal: set by `export_mod!` before calling `Mod::register`.
223/// Used by `yog_api::interop::current_mod_id()` so `Interop::export` knows
224/// which mod is calling.
225#[doc(hidden)]
226pub fn __set_current_mod_id(id: &str) {
227 CURRENT_MOD_ID.with(|cell| cell.replace(Some(id.to_string())));
228 let _ = MOD_ID.set(id.to_owned());
229}
230
231/// This mod's id (its manifest's), once the runtime has loaded it.
232pub fn mod_id() -> &'static str {
233 MOD_ID.get().map_or("", String::as_str)
234}
235
236/// This mod's id: each mod's library has its own copy of this crate.
237static MOD_ID: yog_sync::OnceLock<String> = yog_sync::OnceLock::new();
238
239/// Internal: the current mod's id, set during `yog_mod_register`.
240#[doc(hidden)]
241pub fn __current_mod_id() -> Option<String> {
242 CURRENT_MOD_ID.with(|cell| cell.borrow().clone())
243}
244
245/// Internal: the global `YogApi` pointer, set by every mod's `yog_mod_register`
246/// (it's the same singleton table for the whole process). Process-wide (not
247/// thread-local) because `#[yog_export]`-generated wrappers read it whenever
248/// an exported function is *called*, which may happen on any thread, long
249/// after the loading thread's `yog_mod_register` returned.
250#[doc(hidden)]
251pub fn __set_current_api_ptr(ptr: usize) {
252 API_PTR.store(ptr, yog_sync::atomic::Ordering::Release);
253}
254
255/// The `register` functions of `yog_api::content!()` — the content of
256/// `content/**` the build generates — run by `export_mod!` after
257/// `Mod::register`.
258#[doc(hidden)]
259pub fn __yog_content_registrars() -> &'static yog_sync::Mutex<Vec<fn(&mut Registry)>> {
260 static REG: yog_sync::Mutex<Vec<fn(&mut Registry)>> = yog_sync::Mutex::new(Vec::new());
261 ®
262}
263
264#[doc(hidden)]
265pub fn __current_api_ptr() -> usize {
266 API_PTR.load(yog_sync::atomic::Ordering::Acquire)
267}
268
269static API_PTR: yog_sync::atomic::AtomicUsize = yog_sync::atomic::AtomicUsize::new(0);
270
271std::thread_local! {
272 static CURRENT_MOD_ID: std::cell::RefCell<Option<String>> = const { std::cell::RefCell::new(None) };
273}
274
275pub use yog_book::BookRenderer;
276pub use yog_command::CommandContext;
277pub use yog_config::Config;
278pub use yog_core::{
279 BlockHit, BlockInfo, BlockPos, EntityInfo, Face, PlacedBlock, PlayerInfo, Point, Rotation,
280 ScreenSlot, SlotStack, Stack, entity_flags, split_state,
281};
282pub use yog_dimensions::{GeneratedChunk, YogDimensionDef, YogDimensionTypeDef};
283pub use yog_event::{Entity, Event, EventPhase, Message, Player, Service, World};
284/// A packet the server or the client received (`on_packet` / `on_client_packet`).
285pub use yog_event::{client::net::Packet as ClientPacketEvent, server::net::Packet as PacketEvent};
286pub use yog_formats::book::{Book, BookCategory, BookEntry, BookPage};
287pub use yog_inventory::{InventoryDef, SlotLayout};
288pub use yog_network::Packet;
289pub use yog_registry::{
290 ArmorDefense, ArmorMaterial, ArmorPiece, ArmorSlot, BlockDef, BlockProperty, Cooking,
291 EntityDef, EntityKind, Facing, FoodDef, ItemDef, Placement, Recipe, RecipeKind, SoundGroup,
292 StartupGrant, ToolItem, ToolMaterial,
293};
294pub use yog_ui::{
295 Align, Dock, FlexDir, FocusStyle, LayoutNode, Rect, Stretch, UiRoot, Units, widget,
296};
297
298/// Logging macros (`yog_api::info!`, `warn!`, `error!`).
299pub use yog_logging::{error, info, warn};
300
301/// Core types and handles.
302pub mod core {
303 pub use yog_core::*;
304}
305
306/// Events by plane — `event::player::session::Join`, `event::block::Break`, … —
307/// subscribed with `Registry::on` / `before` / `after`.
308pub mod event {
309 pub use yog_event::*;
310}
311
312/// The bus's domains: each one's actions as functions
313/// (`world::get_block(dim, pos)`, `entity::position(uuid)`,
314/// `player::give_item(name, item, count)`) beside its events.
315pub use yog_event::{
316 block, bossbar, chat, entity, game, item, net, particle, player, scoreboard, sound, tag, world,
317};
318
319/// Content registration (custom items / blocks / food).
320pub mod content {
321 pub use yog_registry::*;
322}
323
324/// Networking (raw-byte packets over channels).
325pub mod network {
326 pub use yog_network::*;
327}
328
329/// Commands.
330pub mod command {
331 pub use yog_command::*;
332}
333
334/// Custom dimensions — dimension-type definitions and runtime chunk generation.
335pub mod dimension {
336 pub use yog_dimensions::*;
337}
338
339/// Where the mod keeps its data (typed stores by scope, values kept with the world).
340pub mod storage;
341
342/// Mod configuration (typed key/value files).
343pub mod config {
344 pub use yog_config::*;
345}
346
347/// Guide books: the `.ybook` format and its renderer.
348pub mod book {
349 pub use yog_book::*;
350 pub use yog_formats::book::*;
351}
352
353/// UI framework — flexbox layout + widgets on top of yog-gfx.
354pub mod ui {
355 pub use yog_ui::*;
356}
357
358/// Pulls a `.yui` screen's generated code into the current module — the
359/// code-behind's half of `src/<name>.yui`:
360///
361/// ```ignore
362/// // src/mod_list.rs, next to src/mod_list.yui
363/// yog_api::ui_include!("mod_list");
364/// ```
365///
366/// `<name>` is the `.yui` file's path under `src/` without the extension
367/// (`"screens/options"` for `src/screens/options.yui`). `yog build`,
368/// `yog check` and `yog ui gen` write the code to
369/// `.yog-build/generated/<name>.g.rs` (the build crate's own directory,
370/// `CARGO_MANIFEST_DIR`), so it's never committed and never stale.
371#[macro_export]
372macro_rules! ui_include {
373 ($name:literal) => {
374 include!(concat!(
375 env!("CARGO_MANIFEST_DIR"),
376 "/generated/",
377 $name,
378 ".g.rs"
379 ));
380 };
381}
382
383/// Pulls the mod's `.yres` resources in as module `res` — one type per
384/// resource set, with an accessor per entry:
385///
386/// ```ignore
387/// // src/lib.rs
388/// yog_api::resources!();
389///
390/// use crate::res::{Icons, Strings};
391/// let title = Strings::screen_title(); // the text in the player's language
392/// let count = Strings::mods_count(58); // "{count} mods" → "58 mods"
393/// let logo = Icons::logo(); // an image source, "mymod:images/logo"
394/// ```
395///
396/// `yog build`, `yog check` and `yog res check` generate one
397/// `.yog-build/generated/resources/<Set>.g.rs` per `resources/**/<Set>.yres`
398/// plus `.yog-build/generated/resources.g.rs` including them all (see
399/// Yog-IDLE's `docs/yres.md`); never committed, never stale.
400#[macro_export]
401macro_rules! resources {
402 () => {
403 pub mod res {
404 include!(concat!(
405 env!("CARGO_MANIFEST_DIR"),
406 "/generated/resources.g.rs"
407 ));
408 }
409 };
410}
411
412/// Pulls the mod's blocks and items — `content/**/*.yblock` and `*.yitem`,
413/// made in Yog-IDLE's model editor — in as module `content`, and registers
414/// them (every file without `"register": "manual"`) right after
415/// `Mod::register`:
416///
417/// ```ignore
418/// // src/lib.rs — that's all it takes
419/// yog_api::content!();
420///
421/// // Ids and definitions, for code that needs them:
422/// use crate::content::{Blocks, Items};
423/// let id: &str = Blocks::RUBY_ORE; // "mymod:ruby_ore"
424/// registry.register_item(Items::ruby().max_stack(16)); // a "manual" one, tweaked
425/// ```
426///
427/// `yog build`, `yog check` and `yog content check` generate
428/// `.yog-build/generated/yog-content.g.rs` — never committed, never stale.
429/// The models, blockstates, loot tables, tags and lang entries go into the
430/// `.yog` as assets. See Yog-IDLE's `docs/blocks-items.md`.
431#[macro_export]
432macro_rules! content {
433 () => {
434 pub mod content {
435 include!(concat!(
436 env!("CARGO_MANIFEST_DIR"),
437 "/generated/yog-content.g.rs"
438 ));
439 }
440 };
441}
442
443/// Inventory framework — real Container/Menu screens (BlockEntity-backed),
444/// as opposed to `ui`'s HUD-drawn overlays. See `yog-inventory`'s DESIGN.md.
445pub mod inventory {
446 pub use yog_inventory::*;
447}