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.

From Sunrise's modding bookead8a1e

On this page

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 sunrise-mod.toml of your native mod. Keep the [native] pins generated by cargo sunrise-mod new.

toml
[[native.mixin]]
id = "head"
target = "sunrise_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:

rust
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

  • id

    Required
    yes
    Meaning
    The row's name, unique in the mod. Errors name it as mod:id.
  • target

    Required
    yes
    Meaning
    The game function's path (Naming the target).
  • kind

    Required
    yes
    Meaning
    One of the kinds above.
  • helper

    Required
    yes
    Meaning
    The helper's file, a .rs path under src/.
  • bindings

    Required
    when the helper has parameters
    Meaning
    One { 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).
  • cancellable

    Required
    no
    Meaning
    HEAD, BEFORE_CALL, AFTER_CALL, AFTER_ASSIGN: the helper returns ControlFlow and can end the function.
  • selector, require, ordinal

    Required
    one-place kinds
    Meaning
    Which call, how many matches, which match.
  • variable

    Required
    MODIFY_VARIABLE
    Meaning
    { name, ordinal, at = "LOAD" or "STORE", parameter = true for a parameter }. It replaces selector; require and ordinal then count accesses.
  • priority

    Required
    no
    Meaning
    Orders rows of several mods at one place: higher runs first. The default is 100. (Loop slots run the other way.)
  • result

    Required
    MODIFY_ARGS, and AFTER_CALL reading the result
    Meaning
    The selected call's result type. Refused on other kinds.
  • slice, argument

    Required
    no
    Meaning
    slice = { 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: sunrise_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: sunrise_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: sunrise_client::game::level_access::<GameLevel<'_> as LevelAccess>::block_state.

To get the module from the file, start from crates/sunrise-client/src/, which is sunrise_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 sunrise_client::game::autosave (world/ is an area). But src/game/native_hooks/ has no .game-area, so src/game/native_hooks/base.rs is sunrise_client::game::native_hooks::base.

Any function of the game crate can take a mixin. A function in a crate below it, such as sunrise_world, needs the marker #[sunrise_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.

  • E_MIXIN_INVALID

    Message
    <mod>:<row>: invalid target; name the game function's path
    Fix
    Write the target.
  • Message
    … invalid helper; name a Rust file under src/ in this package
    Fix
    Put the helper under src/, ending in .rs.
  • Message
    … invalid hook; a named hook is a mod_api::Hooks method; a mixin names its target
    Fix
    Remove the row's hook (or hook_version) key and name a target, or implement the hook in Hooks.
  • Message
    … invalid target; a mixin targets a game function
    Fix
    The target is in a mod you depend on. Call that mod's public functions instead.
  • E_MIXIN_TARGET_MISSING

    Message
    `<target>: no function <path> in this game build's function index (functions.json), or no crate <crate> in the game's source`
    Fix
    Check the path against the source at your commit, module first.
  • E_MIXIN_TARGET_AMBIGUOUS

    Message
    <target>: several functions have this path (a cfg-gated pair, for one)
    Fix
    Target another function.
  • E_MIXIN_NOT_REPLACEABLE

    Message
    <target>: a function below the game crate takes a replacement only when it carries #[sunrise_mod_api_macros::replaceable]; …
    Fix
    Target a game-crate function or a caller or callee carrying the marker.
  • Message
    <target>: <reason>, such as `it is generic over types or takes impl Trait …`
    Fix
    Target a caller or callee that can be copied.
  • E_MIXIN_SOURCE

    Message
    <target>: <why>, such as <file> differs from this game build's functions.json
    Fix
    The game's source could not be read, or is not the build's: retry the build.
  • E_MIXIN_INDEX

    Message
    <path>: …: the game build's SDK has no function index …, or functions.json describes game build <commit>, not <commit>
    Fix
    The SDK on disk is damaged or another build's: fetch the SDK again.
  • E_OVERWRITE_CONFLICT

    Message
    from the tool: OVERWRITE must be exclusive on <function>; competing injections: <mod>/<row>, …
    Fix
    Keep only one of those mods installed.
  • E_LOOP_ENTRY_REPLACED

    Message
    see Published loops
    Fix
  • E_MIXINS_PATCH

    Message
    tools/mixins/narrow-reference-rule.patch does not apply to horizon-mixins <commit>: <why>
    Fix
    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.

Edit this page on GitHub · Spotted something wrong? Open an issue or ask on Discord.