Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Mixins: [[native.mixin]]

A mixin changes one game function. You name the function and the place in it (its start, its return value, one call inside it, or its whole body), and write your code there as a small Rust function, the helper.

Use a mixin when you need private fields, a change in the middle of a function, or a new body. To run code at the start or end of a function with mod_api values, an [[inject]] listener is enough.

Example

This mixin runs at the start of on_tick_rate_changed, the server's /tick rate handler. It reads the private Game::clock field and cancels the handler at a chosen tick rate.

Add this row to the horizon-mod.toml of your native mod. Keep the [native] pins generated by cargo horizon-mod new.

[[native.mixin]]
id = "head"
target = "horizon_client::game::autosave::Game<'_>::on_tick_rate_changed"
kind = "HEAD"
cancellable = true
helper = "src/mixins/head.rs"
bindings = [{ name = "game", ty = "&mut Game<'_>", value = "&mut *self" }]

src/mixins/head.rs, the helper:

fn head(game: &mut Game<'_>) -> ::core::ops::ControlFlow<()> {
    if game.clock.rate() == 13.0 {
        return ::core::ops::ControlFlow::Break(());
    }
    ::core::ops::ControlFlow::Continue(())
}

bindings says what each helper parameter gets: here game gets &mut *self, the Game the function was called on. With cancellable = true the helper returns ControlFlow<()>: Break(()) makes the function return at once, and Continue(()) lets it run. For a function that returns R, the helper returns ControlFlow<R>, and Break(value) returns value.

When it builds, the build log shows Function replacement: 1 functions patched by 1 mixins, without rebuilding the game (…).

Writing a helper

The helper file holds exactly one function: private, safe, with no attributes and no generic parameters (except the impl FnOnce parameter of WRAP_OPERATION). The name is free, and the file has no use lines.

  • It sees what the target's module sees: its items, imports and private fields (read the top of the target's file). That is why Game works in the helper and in ty. Write other names as full paths, such as ::core::ops::ControlFlow. crate:: is the game crate.
  • A field or method it can't see needs a bridge. A local variable needs a $local:NAME:N binding.
  • It calls your mod's crate by its Rust name: the package name with - turned into _. Don't declare helper files as modules in src/lib.rs. Shared code that needs private game items goes in a support module.

Kinds

kindYour helper runsIt returns
HEADat the start of the function(), or ControlFlow<()> with cancellable = true
RETURNon the value the function returns ($value)the value to return
OVERWRITEinstead of the whole body; one mod per functionthe function's return type
BEFORE_CALL, AFTER_CALLbefore or after one call in the body()
AFTER_ASSIGNafter one statement that stores a call's result (let x = f();, x = f();)()
MODIFY_ARG, MODIFY_ARGSon one argument, or all arguments as a tuple, of one callthe new argument(s)
MODIFY_CONSTANTon one literal in the bodythe new value
MODIFY_VARIABLEon one read or write of a local or parameterthe new value
MODIFY_EXPRESSION_VALUEon the value of one call in the body ($value)the new value
WRAP_OPERATIONaround one call, which you get as $operation and may run or notthe call's type

The other kinds act on one place in the body, which a selector names as source text. For a call, write the callee without arguments: autosave_interval or self.next_autosave_interval. For MODIFY_EXPRESSION_VALUE, write the whole expression: autosave_interval(rate). MODIFY_VARIABLE uses variable instead. require is how many matches the body has (inside slice, if set), and ordinal picks one, from 0.

Fields

FieldRequiredMeaning
idyesThe row's name, unique in the mod. Errors name it as mod:id.
targetyesThe game function's path (Naming the target).
kindyesOne of the kinds above.
helperyesThe helper's file, a .rs path under src/.
bindingswhen the helper has parametersOne { name, ty, value } per helper parameter, in order. name and ty repeat the parameter. value is a target parameter or its borrow (self, &*self, &mut *self, rate), or a tool value (below).
cancellablenoHEAD, BEFORE_CALL, AFTER_CALL, AFTER_ASSIGN: the helper returns ControlFlow and can end the function.
selector, require, ordinalone-place kindsWhich call, how many matches, which match.
variableMODIFY_VARIABLE{ name, ordinal, at = "LOAD" or "STORE", parameter = true for a parameter }. It replaces selector; require and ordinal then count accesses.
prioritynoOrders rows of several mods at one place: higher runs first. The default is 100. (Loop slots run the other way.)
resultMODIFY_ARGS, and AFTER_CALL reading the resultThe selected call's result type. Refused on other kinds.
slice, argumentnoslice = { from = { selector, ordinal, require } } narrows the search to a region; argument picks an argument. Both are in the tool's docs below.
Tool valueThe helper gets
$valueThe value being changed: the return value, the expression's value, or the argument, constant or variable.
$arg0, $arg1, …An argument of the selected call (WRAP_OPERATION).
$argsAll arguments of the selected call, as a tuple (MODIFY_ARGS).
$receiverThe receiver of a selected method call (WRAP_OPERATION); the first binding, and the operation's first parameter.
$operationThe selected call, as impl FnOnce(args) -> result (WRAP_OPERATION); the last binding.
$local:NAME:N, $local_ref:NAME:N, $local_mut:NAME:NThe Nth local named NAME in the body, from 0: by value, & or &mut.

horizon-mixins documents every kind and binding in full: Mixin API and advanced injections. Read these files at the mixins revision pinned in your manifest when checking tool-specific syntax.

Naming the target

A target is the function's module path, then its type and name:

  • a method: horizon_client::game::autosave::Game<'_>::on_tick_rate_changed, where the module is the one holding the impl block and the type is written as there, lifetimes included;
  • a free function: horizon_client::game::commands::misc::millis;
  • a trait method: the module of the impl Trait for Type block, then <Type as Trait> as written, then the function: horizon_client::game::level_access::<GameLevel<'_> as LevelAccess>::block_state.

To get the module from the file, start from crates/horizon-client/src/, which is horizon_client. A folder directly under src/game/ that holds a .game-area file is an area, and an area is not a module.

So src/game/world/autosave.rs is horizon_client::game::autosave (world/ is an area). But src/game/native_hooks/ has no .game-area, so src/game/native_hooks/base.rs is horizon_client::game::native_hooks::base.

Any function of the game crate can take a mixin. A function in a crate below it, such as horizon_world, needs the marker #[horizon_mod_api_macros::replaceable] in its source. Otherwise, target a replaceable caller or callee.

These functions are refused:

  • generic over types or consts, or inside an impl block that is;
  • taking impl Trait, returning !, or taking self by value;
  • const, async, unsafe or #[inline(always)];
  • existing only under a cfg;
  • a body that declares a static, thread-local, macro_rules! or impl;
  • a body that uses a location-dependent macro such as file!, line!, module_path!, include! or env!;
  • a body that uses a non-exported crate-local macro defined outside its module path. Macros defined in the target module or its ancestors are copied with the function.

The one generic function you can target is a published loop's body.

With other mods

Several mods' rows on one function all apply. An OVERWRITE must be the only mixin on its function, from any mod including its own. An [[inject]] listener may share a function with mixins: head listeners run first, then the mixed-in function, then return listeners.

Errors

A row the build can't apply stops the build, naming the mod, the row and the reason. <…> is filled in.

CodeMessageFix
E_MIXIN_INVALID<mod>:<row>: invalid target; name the game function's pathWrite the target.
… invalid helper; name a Rust file under src/ in this packagePut the helper under src/, ending in .rs.
… invalid hook; a named hook is a mod_api::Hooks method; a mixin names its targetRemove the row's hook (or hook_version) key and name a target, or implement the hook in Hooks.
… invalid target; a mixin targets a game functionThe target is in a mod you depend on. Call that mod's public functions instead.
E_MIXIN_TARGET_MISSING<target>: no function `<path>` in this game build's function index (functions.json), or no crate `<crate>` in the game's sourceCheck the path against the source at your commit, module first.
E_MIXIN_TARGET_AMBIGUOUS<target>: several functions have this path (a cfg-gated pair, for one)Target another function.
E_MIXIN_NOT_REPLACEABLE<target>: a function below the game crate takes a replacement only when it carries #[horizon_mod_api_macros::replaceable]; …Target a game-crate function or a caller or callee carrying the marker.
<target>: <reason>, such as it is generic over types or takes `impl Trait` …Target a caller or callee that can be copied.
E_MIXIN_SOURCE<target>: <why>, such as <file> differs from this game build's functions.jsonThe game's source could not be read, or is not the build's: retry the build.
E_MIXIN_INDEX<path>: …: the game build's SDK has no function index …, or functions.json describes game build <commit>, not <commit>The SDK on disk is damaged or another build's: fetch the SDK again.
E_OVERWRITE_CONFLICTfrom the tool: OVERWRITE must be exclusive on <function>; competing injections: <mod>/<row>, …Keep only one of those mods installed.
E_LOOP_ENTRY_REPLACEDsee Published loops
E_MIXINS_PATCHtools/mixins/narrow-reference-rule.patch does not apply to horizon-mixins <commit>: <why>Not your mod: report it on the game.

The tool's own codes, such as E_MATCH_COUNT and E_UNSUPPORTED_SITE, mean a selector, count or binding does not fit the body; its docs list them. A helper with a wrong type is a compiler error under your mod's id.