utils#

equation#

COMPUTE_VERSION: tuple[int, int] = (26, 3)[source]#

First version with /compute and arithmetic number providers: an equation becomes one command.

PROVIDER_TYPES: dict[Literal['*', '/', '+', '-', '%', ''], str] = {'%': 'floor_mod', '*': 'mul', '+': 'add', '-': 'sub', '/': 'floor_div'}[source]#

Context int provider per operator; floor_div and floor_mod round like scoreboard players operation.

is_macro_argument(value: str) → bool[source]#

Returns True if the value contains a macro argument pattern like $(foo).

>>> is_macro_argument("$(amount)")
True
>>> is_macro_argument("#toto")
False
get_scoreboard_set(
player: str,
scoreboard: str,
value: str | int,
) → str[source]#

Returns a scoreboard players set command string.

>>> get_scoreboard_set("#42", "your_namespace.data", 42)
'scoreboard players set #42 your_namespace.data 42'
get_scoreboard_operation(
player: str,
scoreboard: str,
operator: Literal['*', '/', '+', '-', '%', ''],
source: str,
source_scoreboard: str,
) → str[source]#

Returns a scoreboard players operation command string.

>>> get_scoreboard_operation("@s", "your_namespace.data", "*", "#1000000", "your_namespace.data")
'scoreboard players operation @s your_namespace.data *= #1000000 your_namespace.data'
get_comment_token(
operator: Literal['*', '/', '+', '-', '%', ''],
player: str | int,
scoreboard: str | None,
) → str[source]#

Builds one token for the equation head comment.

>>> get_comment_token("*", "@s", "some_score")
'* @s some_score'
>>> get_comment_token("+", "$(macro_arg)", None)
'+ $(macro_arg)'
>>> get_comment_token("", "#source", None)
'#source'
score_provider(player: str, scoreboard: str) → str | None[source]#

The number provider reading a score, None for a selector a provider cannot name.

>>> score_provider("@s", "kills")
'{type:"score",target:"this",score:"kills"}'
>>> score_provider("#total", "kills")
'{type:"score",target:{type:"fixed",name:"#total"},score:"kills"}'
>>> score_provider("@p", "kills") is None
True
combine_providers(
operator: Literal['*', '/', '+', '-', '%', ''],
left: str | None,
right: str | None,
) → str | None[source]#

The provider of left <operator> right, None when either side cannot be expressed.

>>> combine_providers("+", "1", "2"), combine_providers("/", "7", "2")
('{type:"add",inputs:[1,2]}', '{type:"floor_div",left:7,right:2}')
class BaseEquation(
target_player: str,
target_scoreboard: str | None = None,
)[source]#

Bases: object

Abstract base for chainable scoreboard equation builders.

Subclasses implement render_header and may override __str__. All methods return self to allow method chaining.

player: str[source]#
scoreboard: str[source]#
ops: list[str][source]#
comment_parts: list[str][source]#
provider: str | None[source]#

The running value as a number provider, None once an operand cannot be expressed as one.

uses_compute() → bool[source]#

Whether str() renders one /compute command instead of the scoreboard operations in ops.

render_header() → str[source]#

Returns the human-readable equation comment (without the leading "# ").

store_target() → str[source]#

Where execute store result writes the value, ex: "score @s ns.data".

apply_operation(
player: str | int | BaseEquation,
scoreboard: str | None,
operator: Literal['*', '/', '+', '-', '%', ''],
temp: str = 'temp',
) → BaseEquation[source]#

Appends the scoreboard commands for one arithmetic operation.

An int constant is registered in load as a #<value> fake player, and a macro argument is stored in temp first.

Parameters:
  • player – A selector, fake player, int constant, macro arg, or another equation.

  • scoreboard – Source scoreboard, ignored for int/macro, self.scoreboard when None.

  • operator – One of *, /, +, -, or "" (for assignment via operation).

>>> eq = BaseEquation("@s")  # Its scoreboard defaults to {ctx.project_id}.data
>>> eq.apply_operation("other_player", "other_scoreboard", "/").ops
['scoreboard players operation @s your_namespace.data /= other_player other_scoreboard']
set(
player: str | int,
scoreboard: str | None = None,
) → BaseEquation[source]#

Sets the scoreboard value (assignment, not operation), should be used for the first operation in the chain.

Parameters:
  • player – The value to assign. Can be an int, a macro arg, or a player/selector.

  • scoreboard – Source scoreboard (ignored for int/macro).

>>> # Setting @s in your_namespace.data to 42 and checking the generated commands with .ops
>>> BaseEquation("@s").set(42).ops
['scoreboard players set @s your_namespace.data 42']
>>> # Setting @s in your_namespace.data to a macro argument and checking the generated commands with .ops
>>> BaseEquation("@s").set("$(macro_value)").ops
['$scoreboard players set @s your_namespace.data $(macro_value)']
multiply(
player: str | int | BaseEquation,
scoreboard: str | None = None,
) → BaseEquation[source]#

Multiplies the current scoreboard value. See apply_operation for details.

divide(
player: str | int | BaseEquation,
scoreboard: str | None = None,
) → BaseEquation[source]#

Divides the current scoreboard value. See apply_operation for details .

add(
player: str | int | BaseEquation,
scoreboard: str | None = None,
) → BaseEquation[source]#

Adds to the current scoreboard value. See apply_operation for details.

subtract(
player: str | int | BaseEquation,
scoreboard: str | None = None,
) → BaseEquation[source]#

Subtracts from the current scoreboard value. See apply_operation for details.

modulo(
player: str | int | BaseEquation,
scoreboard: str | None = None,
) → BaseEquation[source]#

Applies modulo to the current scoreboard value. See apply_operation for details.

class ScoreboardEquation(
player: str,
scoreboard: str | None = None,
)[source]#

Bases: BaseEquation

Equation whose result is stored directly in a scoreboard objective.

>>> # Simple equation
>>> str((ScoreboardEquation("@s").set(10) + 5) * (-2) / 3 % 4 - "#toto").splitlines()[0]
'# scoreboard @s your_namespace.data = 10 + 5 * -2 / 3 % 4 - #toto'
>>> # From 26.3 the whole chain is one /compute command of .provider, a macro line when an operand is a macro argument
>>> durability = ScoreboardEquation("#temp_durability", "some_score").set("-$(amount)") * 1000000 / "$(max_damage)" - "#toto"
>>> str(durability).splitlines()[1].split(" compute default integer ")[0]
'$execute store result score #temp_durability some_score run'
>>> (ScoreboardEquation("#x").set("$(amount)") * 1000000 / "$(max_damage)").provider
'{type:"floor_div",left:{type:"mul",inputs:[$(amount),1000000]},right:$(max_damage)}'
>>> # Before 26.3, or with an operand a number provider cannot name, the scoreboard operations in .ops are written instead
>>> for op in durability.ops:
...     print(op)
$scoreboard players set #temp_durability some_score -$(amount)
scoreboard players operation #temp_durability some_score *= #1000000 your_namespace.data
$scoreboard players set #temp_divide your_namespace.data $(max_damage)
scoreboard players operation #temp_durability some_score /= #temp_divide your_namespace.data
scoreboard players operation #temp_durability some_score -= #toto some_score
>>> print(str(ScoreboardEquation("@p").set(1) + "@a"))
# scoreboard @p your_namespace.data = 1 + @a
scoreboard players set @p your_namespace.data 1
scoreboard players operation @p your_namespace.data += @a your_namespace.data
>>> # Combining two Equation instances: the inner one is computed inline
>>> eq4 = ScoreboardEquation("@s").set(10) * 5
>>> eq5 = ScoreboardEquation("#toto", "some_score").set(20) * 2
>>> (eq4 * eq5).provider
'{type:"mul",inputs:[{type:"mul",inputs:[10,5]},{type:"mul",inputs:[20,2]}]}'
class StorageEquation(
storage: str,
path: str,
scale: float = 1.0,
storage_type: str = 'double',
)[source]#

Bases: BaseEquation

Equation that computes via a temp scoreboard, then stores the result in a storage path.

The scale factor is applied when flushing the temp scoreboard value to storage.

>>> equation = StorageEquation("ns:storage", "result", 0.001, "double").set("-$(amount)") * 1000
>>> print(str(equation))
# storage ns:storage result = (-$(amount) * 1000) * 0.001000
$execute store result storage ns:storage result double 0.001000 run compute default integer {type:"mul",inputs:[-$(amount),1000]}
storage: str[source]#
path: str[source]#
scale: float[source]#
storage_type: str[source]#

libs#

lib_archives(
ctx: Context,
pack_type: str,
) → list[str][source]#

Library archives of a pack type, minus the ones filtered out by meta.stewbeet.libs_exclude_patterns.

Patterns are matched against the archive path relative to the libs folder, ex: “resource_pack/ARAM.zip”. An excluded archive is invisible to every plugin: it is neither welded nor copied to a destination.

Parameters:
  • ctx – The beet context.

  • pack_type – Either “datapack” or “resource_pack”.

Returns:

Absolute paths of the archives to ship, in glob order.

loot_table#

TYPED_LOOT_VERSION: tuple[int, int] = (26, 3)[source]#

First Minecraft version dispatching loot functions and conditions on “type”, with single “condition” and “modifier” fields.

result_count_to_suffix(
result_count: int | JsonDict,
) → str[source]#

Suffix of the loot table path giving result_count items, an int or a {“min”, “max”} dict for random counts.

>>> result_count_to_suffix(1)
''
>>> result_count_to_suffix(5)
'_x5'
>>> result_count_to_suffix({"min": 4, "max": 6})
'_x4to6'
>>> result_count_to_suffix({"min": 3, "max": 1})
'_x3'
>>> result_count_to_suffix({"min": 1, "max": 1})
''
>>> result_count_to_suffix({})
''
loot_function(
function: str,
**fields: Any,
) → JsonDict[source]#

Loot function (item modifier) keyed the way the targeted Minecraft version reads it.

>>> loot_function("minecraft:set_count", count=2)
{'type': 'minecraft:set_count', 'count': 2}
loot_condition(
condition: str,
**fields: Any,
) → JsonDict[source]#

Loot condition (predicate) keyed the way the targeted Minecraft version reads it.

>>> loot_condition("minecraft:random_chance", chance=0.5)
{'type': 'minecraft:random_chance', 'chance': 0.5}
loot_modifiers(
functions: list[JsonDict],
) → JsonDict[source]#

Field applying loot functions to a pool entry, to unpack into that entry.

>>> loot_modifiers([loot_function("minecraft:set_count", count=2)])
{'modifier': [{'type': 'minecraft:set_count', 'count': 2}]}
float_score(
objective: str,
target: str = 'this',
) → JsonDict[source]#

Float number provider reading a score, for fields such as set_custom_model_data floats.

Since 26.3 only integer providers read scores, so the score is converted with from_int.

>>> float_score("energy.data")
{'type': 'minecraft:from_int', 'input': {'type': 'minecraft:score', 'target': 'this', 'score': 'energy.data'}}
advancement_conditions(
conditions: list[JsonDict],
) → JsonDict | list[JsonDict][source]#

Value of an advancement trigger field holding conditions, such as “player” or “location”.

A list before 26.3, a single condition since, wrapped in all_of when there are several.

>>> advancement_conditions([loot_condition("minecraft:random_chance", chance=0.5)])
{'type': 'minecraft:random_chance', 'chance': 0.5}
entity_type_field(
entity_type: str,
) → JsonDict[source]#

Entity predicate field matching an entity type or tag, to unpack into the predicate.

>>> entity_type_field("#minecraft:arrows")
{'entity_type': '#minecraft:arrows'}
advancement_entity(
predicate: JsonDict,
) → JsonDict[source]#

Value of an advancement trigger field matching an entity, such as “entity” or “player”.

A bare entity predicate before 26.3, an entity_properties condition on it since.

>>> advancement_entity({"type": "minecraft:pig"})["predicate"]
{'type': 'minecraft:pig'}

models#

Model elements of custom block displays: grown a little, turned, flipped or cut into stairs corners, keeping the world grid.

UVLOCK_TURNS: dict[int, int] = {2: 90, 3: 180, 4: 270}[source]#

Degrees about Y of the model copy shown for each #rotation score, 1 (a placer looking south) showing the model itself.

vanilla_elements(
parent: str,
) → JsonList | None[source]#

A copy of the elements a vanilla model draws, its own or its nearest parent’s, None when none of them draws any.

Answers are kept per Minecraft version in the project cache, so the client jar is only opened for a parent never asked before.

with_margin(
element: JsonDict,
scale: float,
) → JsonDict[source]#

The element scaled by scale about its own center, so none of its faces lies on a face of the host block.

Each face keeps the UVs its original size gave it: the game would read UVs past the texture’s edges from the grown size.

>>> faces = {"north": {"texture": "#side"}, "up": {"uv": [0, 0, 1, 1]}}
>>> element = with_margin({"from": [0, 0, 6], "to": [16, 8, 10], "faces": faces}, 1.25)
>>> element["from"], element["to"], element["faces"]["north"]["uv"], element["faces"]["up"]["uv"]
([-2.0, -1.0, 5.5], [18.0, 9.0, 10.5], [0, 8, 16, 16], [0, 0, 1, 1])
model_with_margin(
model: JsonDict,
scale: float,
) → JsonDict[source]#

The model with each of its own elements scaled by with_margin, unchanged when it has none.

flipped(
element: JsonDict,
) → JsonDict[source]#

A box element mirrored about the horizontal plane through the block center, as a block placed on the upper half is.

Its faces lose their UVs, so they map the texture from the world grid.

>>> faces = {"up": {"texture": "#top", "cullface": "up"}, "down": {"texture": "#bottom"}, "north": {"uv": [0, 8, 16, 16]}}
>>> element = flipped({"from": [0, 0, 0], "to": [16, 8, 16], "faces": faces})
>>> element["from"], element["to"], element["faces"]
([0, 8, 0], [16, 16, 16], {'down': {'texture': '#top', 'cullface': 'down'}, 'up': {'texture': '#bottom'}, 'north': {}})
stairs_corner(
elements: JsonList,
shape: str,
) → JsonList[source]#

The elements of a stairs corner, from those of straight stairs facing south, its faces mapping the texture from the world grid.

An inner corner adds the stairs turned a quarter towards its side, an outer corner keeps what both have in common.

>>> faces = {"up": {"texture": "#t", "uv": [0, 0, 16, 16]}}
>>> straight = [{"from": [0, 0, 0], "to": [16, 8, 16], "faces": faces}, {"from": [0, 8, 8], "to": [16, 16, 16], "faces": faces}]
>>> [(e["from"], e["to"]) for e in stairs_corner(straight, "outer_right")]
[([0, 0, 0], [16, 8, 16]), ([0, 8, 8], [8.0, 16, 16])]
>>> [(e["from"], e["to"]) for e in stairs_corner(straight, "inner_left")][2:]
[([8.0, 8.0, 0.0], [16.0, 16.0, 16.0])]
overlap(
element: JsonDict,
other: JsonDict,
) → JsonDict | None[source]#

The part of a box element inside another, its faces without UVs, None when they do not overlap.

turned(
vector: tuple[float, float, float],
x: int,
y: int,
) → tuple[float, float, float][source]#

A vector turned as a blockstate turns its model.

It turns x degrees about the X axis, then y about the Y axis, clockwise seen from the positive side.

>>> turned((0, 0, -1), 0, 90), turned((0, 1, 0), 180, 0)
((1.0, 0.0, 0.0), (0.0, -1.0, 0.0))
uv_locked(
element: JsonDict,
x: int,
y: int,
) → JsonDict[source]#

A box element turned about the block center.

Its faces lose their UVs, so they map the texture from the world grid as uvlock does.

>>> faces = {"north": {"uv": [0, 8, 16, 16], "texture": "#side"}}
>>> element = uv_locked({"from": [0, 0, 0], "to": [16, 8, 8], "faces": faces}, 0, 90)
>>> element["from"], element["to"], element["faces"]
([8.0, 0.0, 0.0], [16.0, 8.0, 16.0], {'east': {'texture': '#side'}})

persistent_entities#

persistent_item_display(name: str) → str[source]#

Have the load function summon an item_display that stays in the forceloaded chunk, and give its UUID.

Target it with execute as <uuid> instead of summoning and killing a temporary entity every call: a UUID selector is a direct lookup, and the entity is never created twice. The UUID depends only on the project id and the name, and the unload function kills the entity.

Parameters:

name – Unique within the project, ex: “pulverizer_recipe”.

Returns:

The UUID in its hyphenated form, usable as a selector.

post_effects#

/posteffect chains that time themselves from the frame they are applied on.

A post effect has no parameters: the server only sends its id. The one signal a chain gets is that posteffect add allocates its persistent targets at clear_color, so a 1x1 persistent target whose alpha starts at 0 marks frame one. Stamping Globals.GameTime there gives every chain a clock with sub-tick resolution, restarted by each posteffect add.

POST_SHADER_HEADER: str = '#version 330\n#extension GL_ARB_separate_shader_objects : require\n'[source]#

Preamble of every post shader from Minecraft 26.3, where each in and out also needs a layout(location = N).

SCREENQUAD_VERTEX_SHADER: str = 'minecraft:core/screenquad'[source]#

Vanilla fullscreen-triangle vertex shader, emitting texCoord at location 0.

POST_CLOCK_GLSL: str = "#ifndef CLOCK_GLSL\n#define CLOCK_GLSL\n\n// Activation timestamp: GameTime packed across RGB. Alpha 0 is frame one (a fresh persistent target\n// reads back as its clear_color), CLOCK_RUNNING an armed clock, and 1 a clock whose ramps all ended.\n#define CLOCK_RUNNING 0.5\n#define CLOCK_SETTLE_TICKS 1200.0\n\nvec3 clock_pack_time(float t) {\n    vec3 enc = fract(t * vec3(1.0, 255.0, 65025.0));\n    return enc - enc.yzz * vec3(1.0 / 255.0, 1.0 / 255.0, 0.0);\n}\n\nfloat clock_unpack_time(vec3 enc) {\n    return dot(enc, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n}\n\n// Ticks since the clock was armed. A settled clock is long expired, so the 24000-tick wrap of\n// GameTime can only be crossed once while running. A small negative delta is the server's time sync\n// stepping the client clock back, which must hold the ramp at its start rather than end it.\nfloat clock_elapsed(vec4 clock, float gameTime) {\n    if (clock.a < 0.25) return 0.0;\n    if (clock.a > 0.75) return 1.0e6;\n    float delta = gameTime - clock_unpack_time(clock.rgb);\n    if (delta < -0.5) delta += 1.0;\n    return max(delta * 24000.0, 0.0);\n}\n\n// Eased 0 to 1 ramp over `duration` ticks, holding at 1 afterwards.\nfloat clock_ramp(vec4 clock, float gameTime, float duration) {\n    float t = clamp(clock_elapsed(clock, gameTime) / max(duration, 1.0e-4), 0.0, 1.0);\n    return t * t * (3.0 - 2.0 * t);\n}\n\n#endif\n"[source]#

Registered as <ns>:clock.glsl, for the apply shader of a timed_post_effect chain to include.

POST_CLOCK_FSH: str = "#version 330\n#extension GL_ARB_separate_shader_objects : require\n\n#include <minecraft:globals.glsl>\n#ifndef CLOCK_GLSL\n#define CLOCK_GLSL\n\n// Activation timestamp: GameTime packed across RGB. Alpha 0 is frame one (a fresh persistent target\n// reads back as its clear_color), CLOCK_RUNNING an armed clock, and 1 a clock whose ramps all ended.\n#define CLOCK_RUNNING 0.5\n#define CLOCK_SETTLE_TICKS 1200.0\n\nvec3 clock_pack_time(float t) {\n    vec3 enc = fract(t * vec3(1.0, 255.0, 65025.0));\n    return enc - enc.yzz * vec3(1.0 / 255.0, 1.0 / 255.0, 0.0);\n}\n\nfloat clock_unpack_time(vec3 enc) {\n    return dot(enc, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n}\n\n// Ticks since the clock was armed. A settled clock is long expired, so the 24000-tick wrap of\n// GameTime can only be crossed once while running. A small negative delta is the server's time sync\n// stepping the client clock back, which must hold the ramp at its start rather than end it.\nfloat clock_elapsed(vec4 clock, float gameTime) {\n    if (clock.a < 0.25) return 0.0;\n    if (clock.a > 0.75) return 1.0e6;\n    float delta = gameTime - clock_unpack_time(clock.rgb);\n    if (delta < -0.5) delta += 1.0;\n    return max(delta * 24000.0, 0.0);\n}\n\n// Eased 0 to 1 ramp over `duration` ticks, holding at 1 afterwards.\nfloat clock_ramp(vec4 clock, float gameTime, float duration) {\n    float t = clamp(clock_elapsed(clock, gameTime) / max(duration, 1.0e-4), 0.0, 1.0);\n    return t * t * (3.0 - 2.0 * t);\n}\n\n#endif\n\nuniform sampler2D ClockSampler;\n\nlayout(location = 0) in vec2 texCoord;\nlayout(location = 0) out vec4 fragColor;\n\nvoid main() {\n    vec4 clock = texture(ClockSampler, vec2(0.5));\n    if (clock.a < 0.25) {\n        fragColor = vec4(clock_pack_time(GameTime), CLOCK_RUNNING);\n        return;\n    }\n    fragColor = clock_elapsed(clock, GameTime) > CLOCK_SETTLE_TICKS ? vec4(clock.rgb, 1.0) : clock;\n}\n"[source]#

Stamps the activation time on frame one, then marks the clock settled once every ramp has ended.

POST_COPY_FSH: str = '#version 330\n#extension GL_ARB_separate_shader_objects : require\n\nuniform sampler2D InSampler;\n\nlayout(location = 0) in vec2 texCoord;\nlayout(location = 0) out vec4 fragColor;\n\nvoid main() {\n    fragColor = texture(InSampler, texCoord);\n}\n'[source]#

A pass may not sample the target it writes, so the clock and the frame both go through scratch targets.

timed_post_effect(
effect_id: str,
fragment_shader: str,
uniforms: JsonDict,
inputs: list[JsonDict] | None = None,
pre_passes: list[JsonDict] | None = None,
targets: JsonDict | None = None,
) → None[source]#

Register <project_id>:<effect_id>, a /posteffect chain whose clock restarts on every posteffect add.

The apply pass gets ClockSampler and InSampler (bound to minecraft:main), and a last pass copies its output back to main. Its shader includes <project_id>:clock.glsl and calls clock_elapsed(texture(ClockSampler, vec2(0.5)), GameTime). The clock include and the post/clock and post/copy shaders go to the project’s namespace, so two packs never share them.

Parameters:
  • effect_id – Path under assets/<project_id>/post_effect/.

  • fragment_shader – Id of the apply pass shader, ex: “mgs:post/flash”.

  • uniforms – std140 blocks baked into the apply pass, as {block_name: [post_uniform(...)]}.

  • inputs – Extra samplers of the apply pass, whose SamplerInfo entries follow OutSize, ClockSize and InSize.

  • pre_passes – Passes run before the clock, to prepare targets the extra inputs read.

  • targets – The targets those passes write, declared beside the clock’s.

post_uniform(
name: str,
kind: str,
value: float | list[float],
) → JsonDict[source]#

One entry of a baked std140 uniform block.

Parameters:

kind – “int”, “ivec3”, “float”, “vec2”, “vec3”, “vec4” or “matrix4x4”.

>>> post_uniform("Duration", "float", 2.0)
{'name': 'Duration', 'type': 'float', 'value': 2.0}

sounds#

add_sound(
ctx: Context,
sounds: Sound | dict[str, Sound],
name: str,
ns: str = '',
)[source]#

Add a sound to the resource pack, ex: add_sound(ctx, Sound("path/to/sound.ogg"), "my_sound").

Parameters:
  • sounds – A single Sound, or a dict mapping local names to Sounds.

  • name – The identifier used in /playsound command (excluding namespace)

  • ns – The namespace to write the sound to (defaults to ctx.project_id).

versions#

minecraft_version_at_least(version: tuple[int, ...]) → bool[source]#

Whether the project targets the given Minecraft version or a later one.

Projects without a “minecraft” field in their config target the latest version.

>>> minecraft_version_at_least((1, 21)), minecraft_version_at_least((9999,))
(True, False)