Mods for NeoForge and Fabric
The client
A mod adds its client side in code, which the Obsidian client runs: screens, HUD overlays, renderers, key bindings and the rest. Content the client has to know keeps vanilla clients out (see Blocks and items): players need NeoForge or Fabric with the matching mod, or the Obsidian client with the mod. Build and pack a mod as described in Building and packing.
Client plugins
A mod whose side is client or both also runs on the Obsidian client, which registers its content like a server
(see the mod system). Its plugin class implements IClientPlugin to register its client side. The
client API is its own package, Obsidian.API.Client, which the mod references besides Obsidian.API; servers ship
it too, so the same plugin class loads on them. The client calls ConfigureClient after ConfigureRegistry when it
loads its mods, at startup and on each reload (see below). Servers never call it.
- Registering. What
ConfigureClientregisters takes effect when it returns; if it throws, the mod fails to load. Registering later, through a registry the mod kept, throwsInvalidOperationException, butConnectionandScreensstay usable for as long as the client runs. Registrations are for the mod's own content, with identifiers in its namespace, and registering one twice throwsArgumentException. - Translations. Put them in
assets/<namespace>/lang/en_us.json, with other languages beside it (fr_fr.json, say); missing ones fall back to English. An item's default name usesitem.<namespace>.<path>(orblock.<namespace>.<path>for a block's item), with slashes as dots:ruby:tools/hammerusesitem.ruby.tools.hammer.
IClientRegistry.RegisterBlockEntityShapes(string blockEntityType, Func<IReadOnlyDictionary<string, object?>, BlockShapes?> provider) gives a mod's block entity type its collision
and outline shapes on the client, from its latest synced update data. Register the type in ConfigureRegistry on
both sides with RegisterBlockEntity<T>, then the provider in ConfigureClient.
- The provider gets plain NBT values: numbers, strings and arrays, compounds as dictionaries and lists as
List<object?>. It runs on a reading thread, once per update, so keep it pure and thread-safe. - Picking, the selection outline and the player's collision use the shapes, whatever the resource pack's models.
- Returning null or throwing uses the state's usual shapes.
registry.RegisterBlockEntityShapes("ruby:cable_bus", data =>
{
var connected = data.TryGetValue("connected", out var value) && value is byte flag && flag != 0;
BoundingBox[] boxes = connected
? [new(new VectorD(0.375, 0.375, 0), new VectorD(0.625, 0.625, 1))]
: [new(new VectorD(0.375), new VectorD(0.625))];
return new BlockShapes(boxes, boxes);
});
Use the same pure shape-building helper in the server's GetShapes and the client provider to keep them equal.
IClientRegistry.RegisterBlockEntityModel(string blockEntityType, BlockEntityModelProperties model) adds model
parts from a block entity's synced data to its block's model as the world is meshed, like NeoForge's model data: a
cable's arms, the parts on its sides, facades. Models declares the block models the parts may name (for example
ruby:part/cable_side for assets/ruby/models/part/cable_side.json). Provider gets the same NBT values as a shape
provider and the block's IBlock state, and returns a BlockModelData, or null for the block state's model alone:
Parts:BlockModelPart(Model, X, Y, UvLock), a declared model turned in quarter turns like a blockstate file's.Offset, in sixteenths of a block from -16 to 16, moves it after the turn, so one model can fill each of a drive's slots:new BlockModelPart("ruby:part/drive_cell", Y: 90) { Offset = new VectorF(0, slot * 3, 0) }.Faces:BlockModelFace(From, To, Face, Texture), one face of a box in sixteenths of a block, with any block texture (minecraft:block/stone) and an optionalCullFace,TintIndex,ShadeandLightEmission(0 to 15). They're for textures chosen by data, like a facade showing another block's texture.ReplacesBlockModel: the parts and faces replace the block state's model rather than add to it.
The parts and faces are lit, tinted, layered and culled like the block's own model (render types and emissive elements are described in plugin-archives.md), but don't change how the block culls its neighbours. The provider runs on a meshing thread, once per update and block state, so keep it pure. A part naming an undeclared model, or a provider that fails, draws the block state's model and is logged.
The provider sees only its own block. For a model that follows its neighbours, like a cable connecting to them, the
server works out the connections, puts them in GetUpdateData (or block state properties) and sends an update when
they change. Connections alone need no block entity: ObsidianMod's cable (ObsidianMod/Cable) keeps them in block
state properties, drawn by a multipart blockstate.
string[] sides = ["north", "east", "south", "west"];
registry.RegisterBlockEntityModel("ruby:cable_bus", new BlockEntityModelProperties
{
Models = ["ruby:part/cable_core", "ruby:part/cable_side"],
Provider = (data, block) =>
{
// The server's update data says which sides connect, and which side has a facade of which texture.
var parts = new List<BlockModelPart> { new("ruby:part/cable_core") };
for (var i = 0; i < sides.Length; i++)
{
if (data.TryGetValue(sides[i], out var value) && value is byte connected && connected != 0)
parts.Add(new("ruby:part/cable_side", Y: i * 90));
}
BlockModelFace[] faces = data.TryGetValue("facade", out var facade) && facade is string texture
? [new(new VectorF(0, 0, 0), new VectorF(16, 16, 1), BlockFace.North, texture)
{ CullFace = BlockFace.North }]
: [];
return new BlockModelData
{
Parts = parts,
Faces = faces,
ReplacesBlockModel = true
};
}
});
IClientRegistry.RegisterBlockEntityRenderer(string blockEntityType, BlockEntityRendererProperties renderer) draws
a block entity type's moving parts each frame, like vanilla's block entity renderers: a gear spinning while a machine
works, a door sliding open. Model data is meshed with the world and only changes with an update; a renderer's parts
move in between. Models declares the models the parts may name. A renderer has a provider, code, or both:
Providergets the block entity's latest update data and block state, and returns theBlockEntityRenderParts to draw, or null for none. It runs once per update, and the client animates the parts each frame without calling the mod. A part draws a declaredModelandFaces(without culling or tints), scaled byScale, turned aboutPivot(in sixteenths, the block's centre by default) aroundAxis(up by default), then moved byOffset. Its angle isAngledegrees plusSpeeddegrees per tick since the game tickSince, so it turns smoothly. The client follows the server level's tick count (ILevel.Time): a machine that starts working puts the tick in its update data.Rendereris code, anIBlockEntityRenderer, whoseRender(BlockEntity blockEntity, float partialTick, IBlockEntityRenderBuffer buffer)runs each frame with the mod's live client instance (seeBlockEntity.ClientTickin Block entities). It draws declared models (buffer.Model(part, transform)) and faces (buffer.Face(face, transform)) withMatrix4x4transforms in blocks from the block's lowest corner. It runs on the game thread likeClientTick, so it reads the instance's fields without locking and interpolates withpartialTick. Keep it short and free of allocations, as the frame waits for it.
If either throws, the error is logged and the block entity draws nothing from it until its next update. Block entities
are drawn within 64 blocks of the camera and while in view. The client only has a block entity's data once the server
sends it, so a type with a renderer should return update data from GetUpdateData, even an empty compound, to be
drawn as soon as it's placed.
// The grinder spins its wheel while it works: the server puts "working_since" in its update data (the level's Time
// when it started) and leaves it out when it stops, sending an update each time.
registry.RegisterBlockEntityRenderer("ruby:grinder", new BlockEntityRendererProperties
{
Models = ["ruby:part/grinder_wheel"],
Provider = (data, block) =>
{
// A wheel facing north turns about the north-south axis; one facing east is turned a quarter turn first.
var east = block.GetProperty("facing") is "east" or "west";
var wheel = new BlockModelPart("ruby:part/grinder_wheel", Y: east ? 90 : 0);
if (data.TryGetValue("working_since", out var value) && value is long since)
{
return
[
new BlockEntityRenderPart
{
Model = wheel,
Axis = east ? new VectorF(1, 0, 0) : new VectorF(0, 0, 1),
Speed = 18,
Since = since
}
];
}
return [new BlockEntityRenderPart { Model = wheel }];
}
});
A mod's items are drawn from their item model definitions, assets/<ns>/items/<item>.json, like vanilla's (see
Item models below). Like NeoForge's item model registration events, the mod adds what those definitions can name:
RegisterItemCondition(string property, Func<ItemStack, ItemModelContext, bool> condition),RegisterItemSelect(string property, Func<ItemStack, ItemModelContext, string?> select)andRegisterItemRange(string property, Func<ItemStack, ItemModelContext, float> range)register a property that aminecraft:condition,minecraft:selectorminecraft:range_dispatchmodel names, like"property": "ruby:charge". Each reads the stack with its components, the mod's own included (see Item components), and anItemModelContext: theDisplayContext, theHolderIdof the entity holding or showing the stack (IClientWorld.GetEntitytakes it), and the world'sGameTimeandDayTime. A select returning null draws itsfallback. The three kinds are separate, so one identifier can name one of each.RegisterItemRenderer(string specialModelType, ItemRendererProperties renderer)draws aminecraft:specialmodel type in code, like NeoForge's special model renderers: a definition's{"type": "minecraft:special", "model": {"type": "ruby:gem_display"}, "base": "ruby:item/gem"}draws with the type'sIItemRenderer. ItsRender(ItemStack stack, ItemModelContext context, IItemRenderBuffer buffer)draws declaredModelsand faces like a block entity renderer's code, with transforms in the item's model space (0 to 1). The base model'sdisplaytransform then places it in every context.
A property's value is kept per stack and display context until either changes, so it's worked out about once a tick rather than every frame: keep properties pure. One that throws gives its default (false, the fallback, 0). A renderer runs each frame, so keep it short and free of allocations; if it throws, or the mod is gone, the base model is drawn instead.
// The gem's definition, assets/ruby/items/gem.json, selects by its charge: plain, glowing, or full, which the gem
// display renderer draws in code.
// {"model": {"type": "minecraft:select", "property": "ruby:charge",
// "cases": [
// {"when": "charged", "model": {"type": "minecraft:model", "model": "ruby:item/gem_glowing"}},
// {"when": "full", "model": {"type": "minecraft:special", "base": "ruby:item/gem",
// "model": {"type": "ruby:gem_display"}}}],
// "fallback": {"type": "minecraft:model", "model": "ruby:item/gem"}}}
// this.charge is the PluginComponentType<int> the mod registered in ConfigureRegistry.
registry.RegisterItemSelect("ruby:charge", (stack, context) => stack.Get(this.charge) switch
{
>= 100 => "full",
> 0 => "charged",
_ => null
});
registry.RegisterItemRenderer("ruby:gem_display", new ItemRendererProperties
{
Models = ["ruby:item/gem_core"],
Renderer = new GemDisplayRenderer()
});
// The full gem's core spins about its centre with the world's time.
public sealed class GemDisplayRenderer : IItemRenderer
{
public void Render(ItemStack stack, ItemModelContext context, IItemRenderBuffer buffer)
{
var spin = Matrix4x4.CreateTranslation(-0.5f, -0.5f, -0.5f)
* Matrix4x4.CreateRotationY(context.GameTime % 360 * MathF.PI / 180)
* Matrix4x4.CreateTranslation(0.5f, 0.5f, 0.5f);
buffer.Model(new BlockModelPart("ruby:item/gem_core"), spin);
}
}
IClientRegistry.RegisterItemTooltip(string item, Action<ItemStack, IList<string>> lines) adds lines under one of the
mod's items' names in its tooltip, like NeoForge's appendHoverText. The lines take vanilla's legacy § formatting
codes (§7 for grey). They're asked for each time the tooltip is drawn, so keep them short; one that throws shows
none of its lines.
registry.RegisterItemTooltip("ruby:gem", (stack, lines) => lines.Add($"§7Charge: {stack.Get(this.charge)}"));
public sealed class RubyMod : PluginBase, IClientPlugin
{
public override void ConfigureRegistry(IPluginRegistry registry)
{
registry.RegisterBlock("ruby:mossy_ruby");
registry.RegisterEntity("ruby:golem", new EntityProperties { Width = 1.4f, Height = 2.7f });
registry.RegisterParticle("ruby:spark");
registry.RegisterMenu("ruby:pouch", rows: 1, columns: 5);
registry.MapPayload<SummonGolem>(PayloadPhase.Play, PayloadDirection.Bidirectional, SummonAsync);
}
public void ConfigureClient(IClientRegistry registry)
{
registry.HandlePayload<SummonGolem>((summon, connection) =>
{
// The server summoned a golem; this runs on the connection's packet thread.
});
var summon = registry.RegisterKeyBinding("ruby:summon_golem", "key.keyboard.r", "ruby:golems");
summon.Pressed += () => registry.Connection.SendPayload(new SummonGolem());
var held = 0;
registry.OnTick(() =>
{
// Every client tick, on the game's thread: holding the key for five seconds summons another.
held = summon.IsDown ? held + 1 : 0;
if (held == 100)
registry.Connection.SendPayload(new SummonGolem());
});
registry.RegisterBlockTint("ruby:mossy_ruby", BlockTint.Foliage);
registry.RegisterEntityRenderer("ruby:golem", new EntityRendererProperties
{
Model = "ruby:golem",
Texture = "ruby:entity/golem",
ShadowRadius = 0.7f,
IdleAnimation = "ruby:golem/idle",
WalkAnimation = "ruby:golem/walk"
});
registry.RegisterParticleProvider("ruby:spark", new ParticleProviderProperties
{
Lifetime = 20,
Gravity = 0.5f
});
registry.RegisterMenuScreen("ruby:pouch", new MenuScreenProperties
{
Texture = "ruby:gui/container/pouch",
Slots = [new(44, 20), new(62, 20), new(80, 20), new(98, 20), new(116, 20)]
});
}
}
Payloads.
HandlePayloadhandles what the server sends on a channel the mod declared withMapPayloadasClientboundorBidirectional; the handler given toMapPayloadis the server's. Handlers run on the connection's packet thread, with the connection to answer on.registry.Connectionsends from elsewhere.SendPayloadreturns false while the client isn't connected, or when the server didn't agree on the channel.Key bindings. A binding
ruby:summon_golemhas the translation keykey.ruby.summon_golemand is saved inoptions.txtlike vanilla's. Its categoryruby:golemsis translated fromkey.category.ruby.golems, and mods can share one. Players rebind them in the key binds screen. Keys use vanilla's names:key.keyboard.r,key.keyboard.left.alt,key.mouse.middle, orkey.keyboard.unknownfor none.Pressedis raised on the game's thread when the key is pressed in game with no screen open,IsDownstays true while it's held, andKeyis the key it's bound to now.Ticks.
OnTickruns a handler on the game's thread 20 times a second, in menus as in game, like NeoForge's client tick event: for pollingIsDown, say. A handler that throws isn't run again. A mod's block entities tick withBlockEntity.ClientTick(see Block entities).World queries.
registry.Connection.Worldis anIClientWorldwhile playing, and null otherwise; a client block entity usesthis.GetClientWorld()fromObsidian.API.Client. Queries never load chunks:IsChunkLoaded(chunkX, chunkZ)takes chunk coordinates (blockX >> 4).GetBlock(Vector)returns the block, vanilla or plugin, or air where nothing is loaded.GetBlockEntityData(Vector)returns a copy of the block entity's synced update data, or null.GetBlockEntity(Vector)returns the mod's live client instance, to cast to your class.GetEntity(id)andGetEntities(BoundingBox)returnIClientEntitysnapshots withId,Uuid,Type,PositionandMetadata(by protocol index; missing until received). Box queries test positions, not hitboxes.
Block and block entity data queries may run on any thread. Entity queries and live instances need the game's thread and throw elsewhere, so a payload handler hands entity work to its game-thread code. Get
Connection.Worldagain after changing servers rather than keeping it.Block tints. A tinted block's faces whose model gives them a
tintindexare multiplied by the tint, like vanilla's block colours: the biome's grass, foliage, dry foliage or water colour, blended across nearby biomes, orBlockTint.Fixed(0xRRGGBB).BlockTint.FixedByIndex(0x303030, 0x808080, 0xFFFFFF)givestintindex0, 1 and 2 their own colours. Its item is tinted too (with vanilla's item colours for the biome tints), unless its item definition givestintsof its own.Animated textures. A block, item, entity, GUI sprite or particle texture with a
.png.mcmetaanimation plays like vanilla's water, lava and fire, with no code. The format is in plugin-archives.md.Item models. Items are drawn from their item model definitions as vanilla does, for mods' items and vanilla's alike.
minecraft:model,composite,condition,select,range_dispatch,specialandemptymodels work, with the mod's own properties and vanilla's that a stack, its holder and the world's time decide (broken,damaged,has_component,custom_model_dataandusing_itemconditions;display_context,context_dimension,context_entity_type,main_hand,block_state,charge_type,custom_model_data,trim_materialandlocal_timeselects;custom_model_data,damage,count,use_durationandtimeranges). Vanilla's other properties give their defaults, andbundle/selected_itemdraws nothing. Aminecraft:specialmodel with no renderer draws itsbasemodel.Particle providers. A mod's particle type is drawn with the sprites of
assets/<ns>/particles/<name>.json({"textures": ["<ns>:spark_0", "<ns>:spark_1"]}, fromassets/<ns>/textures/particle/), one picked at random per particle or, withAnimateSprite, in turn over its life. Without a provider, its particles behave like vanilla's base particle.ParticleProviderPropertiessets theirLifetimein ticks,Gravity,Friction,Scale, andRandomizeVelocity = falseto keep the server's velocity.Menu screens. Without a screen, a mod's menu type shows like a chest.
MenuScreenPropertiesgives it a background fromassets/<ns>/textures/gui/...(Texture = "<ns>:gui/container/pouch", its top leftWidthbyHeightpixels), a position for each of the menu's slots in order (as many as the menu has), and positions for the player's inventory, the title and the "Inventory" label. A menu with more than slots (progress, buttons, lists) gets a screen in code instead, which reads the menu's open data (Machine menus) and data slots. A menu type has one screen or the other.Entity renderers. A mod's entity type is drawn with a model layer from
assets/<ns>/models/entity/<path>.json(Model = "<ns>:<path>") and a texture fromassets/<ns>/textures/entity/...(Texture = "<ns>:entity/...", orminecraft:entity/...for vanilla's), scaled byScale, with a shadow ofShadowRadiusblocks. Without a renderer or a valid model, its entities aren't drawn.- Parts named
headturn to where the entity looks, and parts whose names end inlegswing as it walks. - Keyframed animations from
assets/<ns>/animations/entity/<path>.json(format below) move parts on top of that:IdleAnimationplays from the entity's spawn,WalkAnimationfollows its walking (and replaces the leg swing), andAttackAnimationplays each time it swings its arm. - Held items are drawn in parts named
right_armandleft_arm, and vanilla armour on the parts vanilla's humanoid armour covers (head,body,right_arm,left_arm,right_leg,left_leg). - The type's
WidthandHeightare its hitbox, and its eyes are at 85% of its height. Riders sit at itsPassengerAttachments(see Entities).
- Parts named
A renderer can choose its texture from the entity's synced metadata, draw layers over its model and run code:
TextureProviderreceives the entity's metadata (asIClientEntity.Metadatahas it) and returns a texture, or null forTexture: for variants.LayersareEntityRenderLayers drawn over the model in order: a model layer (Model, or null for the entity's own), aTexture, aTint(0xRRGGBB) and aRenderType:Cutout(the default),Translucent, orEmissive(full-bright whatever the light, for glowing eyes and markings). A layer's parts are posed by name like the model's, so a saddle layer follows it. A layer'sProviderchooses its look from the metadata: anEntityLayerAppearance, or null to hide it.Rendereris code, anIEntityRenderer, whoseRender(in EntityRenderContext entity, IEntityRenderBuffer buffer)runs each frame after the model and layers. The context has the entity's id, type and metadata, the partial tick, its age, its interpolated position and rotations, andModelTransform, which its model is drawn with.buffer.Model(model, part, texture, transform, renderType, tint)draws a model layer, or one part of it: the renderer's model, a layer's, or one ofModels. ItsMatrix4x4takes model space to blocks from the entity's position;ModelTransformplaces it like the entity's model. Keep it short and free of allocations.
Providers run once per metadata change and code each frame, on the game thread; don't change the metadata table. A provider that throws falls back to its defaults, and code that throws isn't called for the entity, until its metadata changes. Layers and code aren't drawn while the entity is invisible.
registry.RegisterEntityRenderer("ruby:golem", new EntityRendererProperties
{
Model = "ruby:golem",
Texture = "ruby:entity/golem",
// The server keeps the golem's ore in metadata 16 (a VarInt): 1 for gold.
TextureProvider = data => data.GetValueOrDefault((byte)16) is 1 ? "ruby:entity/golem_gold" : null,
Layers =
[
new EntityRenderLayer
{
Texture = "ruby:entity/golem_eyes",
RenderType = EntityRenderType.Emissive
},
new EntityRenderLayer
{
Model = "ruby:golem_saddle",
Texture = "ruby:entity/golem_saddle",
Provider = data => data.GetValueOrDefault((byte)17) is true
? new EntityLayerAppearance("ruby:entity/golem_saddle")
: null
}
],
Models = ["ruby:golem_crystal"],
Renderer = new GolemCrystalRenderer()
});
// A glowing crystal over the golem's head, where its model layer puts it, spinning with the golem's age.
public sealed class GolemCrystalRenderer : IEntityRenderer
{
public void Render(in EntityRenderContext entity, IEntityRenderBuffer buffer)
{
var spin = Matrix4x4.CreateRotationY(entity.Age * 0.1f) * entity.ModelTransform;
buffer.Model("ruby:golem_crystal", null, "ruby:entity/golem_crystal", spin, EntityRenderType.Emissive);
}
}
Providers read the fields every mob has, like its custom name, health or flags, and the type's own synced data
fields (see Synced data fields) with TryGetData.
A model layer has the shape of the layers in the client's client_models.json, which are vanilla's model layers:
{
"width": 64,
"height": 32,
"root": {
"x": 0, "y": 0, "z": 0, "xRot": 0, "yRot": 0, "zRot": 0, "xScale": 1, "yScale": 1, "zScale": 1,
"cubes": [],
"children": {
"head": {
"x": 0, "y": 4, "z": 0, "xRot": 0, "yRot": 0, "zRot": 0, "xScale": 1, "yScale": 1, "zScale": 1,
"cubes": [[
[[-4, -8, -4, 0.125, 0.25], [-4, 0, -4, 0.125, 0.5], [4, 0, -4, 0.25, 0.5], [4, -8, -4, 0.25, 0.25]]
]],
"children": {}
}
}
}
}
width and height are the texture's size in pixels. Each part has its pivot (x, y, z, in pixels from its
parent's), its rotation in radians, its scale, its cubes and its child parts by name. A cube is a list of faces, and a
face four vertices [x, y, z, u, v]: a position in pixels from the part's pivot and a texture coordinate as a
fraction of the texture's size. Model space is vanilla's: 16 pixels to a block, Y pointing down, and the entity's feet
at Y 24.
An animation has the shape of the animations in client_models.json, which are vanilla's keyframed entity
animations:
{
"length": 2,
"loop": true,
"channels": [
{
"bone": "head",
"target": "ROTATION",
"keys": [
{ "time": 0, "pre": [0, 0, 0] },
{ "time": 1, "pre": [0.5, 0, 0], "cubic": true },
{ "time": 2, "pre": [0, 0, 0], "cubic": true }
]
}
]
}
length is in seconds. A looping animation (loop, false if left out) repeats after it; one that doesn't holds its
last pose. Each channel moves the part named bone by its target: POSITION in pixels (Y down), ROTATION in
radians, or SCALE, added to the part's scale of 1. Its keys, in time order, give the value reached at time
seconds (pre) and, for a jump, the value leaving it (post). The curve to a key is linear, or Catmull-Rom with
cubic. Channels add to the part's pose.
A mod's dimension draws its sky, clouds and fog from its dimension type's data (see Biomes, dimension types and damage types), so it looks the same on any client. The Obsidian client reads the same fields as vanilla's, never the dimension's name:
skyboxpicks the sky:overworld(sky disc, sun, moon, stars and sunrise),end(the End's sky box) ornone.timelinesset to#minecraft:in_overworld(or another tag holdingminecraft:day) moves the sun and tints the sky with the time of day.- The
minecraft:visual/attributes of the type, and of its biomes, setsky_color,fog_color,fog_start_distance,fog_end_distance,sky_fog_end_distance,cloud_color(clouds show only where its alpha isn't 0, which is the default) andcloud_height(192.33 by default).
For example, a dimension with End skies and low pink clouds:
{
"skybox": "end",
"has_skylight": true,
"has_ceiling": false,
"has_ender_dragon_fight": false,
"coordinate_scale": 1,
"min_y": 0,
"height": 256,
"logical_height": 256,
"infiniburn": "#minecraft:infiniburn_end",
"ambient_light": 0.1,
"monster_spawn_light_level": 0,
"monster_spawn_block_light_limit": 0,
"attributes": {
"minecraft:visual/fog_color": "#181318",
"minecraft:visual/cloud_color": "#ccff99cc",
"minecraft:visual/cloud_height": 96
}
}
IClientRegistry.RegisterDimensionEffects(string dimensionType, DimensionEffectsProperties effects) adds what that
format can't say, like NeoForge's dimension special effects:
CloudTexturedraws its clouds from the mod's texture instead of vanilla'sclouds.png, each pixel that isn't transparent a 12-block cell in its colour.Effectsis anIDimensionEffectswhose code runs each frame on the game thread.Adjustgets the frame'sDimensionAtmosphere(sky and fog colours, fog distances, cloud colour and height, the time of day and the camera) and returns it changed; water, lava and blindness still apply afterwards.RenderSkydraws quads into the sky after the skybox, plain or with one of the texturesSkyTexturesdeclares; with"skybox": "none"the whole sky is its.
If the code throws, it isn't called again until the mods reload, and the dimension is drawn from its data alone.
registry.RegisterDimensionEffects("ruby:skylands", new DimensionEffectsProperties
{
CloudTexture = "ruby:environment/skylands_clouds",
SkyTextures = ["ruby:environment/twin_sun"],
Effects = new SkylandsEffects()
});
public sealed class SkylandsEffects : IDimensionEffects
{
// Fog closes in below the islands.
public DimensionAtmosphere Adjust(DimensionAtmosphere atmosphere) => atmosphere.Camera.Y < 32
? atmosphere with { FogEnd = Math.Min(atmosphere.FogEnd, 48) }
: atmosphere;
// A second sun, fixed in the east, 100 blocks away like vanilla's.
public void RenderSky(DimensionAtmosphere atmosphere, IDimensionSkyBuffer buffer) =>
buffer.Quad(new(100, 20, -10), new(100, 0, -10), new(100, 0, 10), new(100, 20, 10), Vector4.One,
"ruby:environment/twin_sun", additive: true);
}
The title screen's Reload Mods button reloads the client's mods without restarting. It's only on the title screen, so
mods never reload while the client is connected to a server or running a world. Unloading takes back everything mods
registered in ConfigureClient, closes their screens and drops their payload channels; loading runs
ConfigureRegistry and ConfigureClient again on new instances. As on a server, content (blocks, items, entity
types, particle types, menu types) stays registered with its ids, so a reload can change what mods do and how they
draw, but new content needs a restart. Keys players bound stay in options.txt.
Screens in code
// The crusher's screen (see Machine menus): its progress, a button pausing it, and the ores it takes, searched and
// scrolled.
public sealed class CrusherScreen : ModMenuScreen
{
private static readonly Item[] ores = [ItemsRegistry.IronOre, ItemsRegistry.GoldOre, ItemsRegistry.CopperOre];
private readonly ProgressBar progress = new()
{
X = 79,
Y = 34,
Width = 24,
Height = 16,
Source = GuiImage.Sprite("ruby:crusher/progress")
};
private readonly ItemGrid list = new()
{
X = 110,
Y = 30,
Columns = 3,
Rows = 2
};
private readonly ScrollBar scroll = new()
{
X = 166,
Y = 30,
Height = 34
};
private bool paused;
public CrusherScreen(IScreenMenu menu)
: base(menu)
{
// Init runs each time the screen is shown, so the widgets kept across showings subscribe once, here.
this.scroll.Scrolled += row => this.list.FirstRow = row;
}
protected override void Init()
{
this.Background = GuiImage.Texture("ruby:gui/container/crusher");
this.Add(new SlotGrid
{
X = 26,
Y = 35,
Columns = 3
});
this.Add(this.progress);
var pause = this.Add(new Button
{
X = 8,
Y = 58,
Width = 50,
Text = this.Translate("ruby.crusher.pause")
});
pause.Pressed += () =>
{
// The menu's ClickButton pauses on 0 and runs on anything else.
this.paused = !this.paused;
this.Menu.ClickButton(this.paused ? 0 : 1);
pause.Text = this.Translate(this.paused ? "ruby.crusher.run" : "ruby.crusher.pause");
};
var search = this.Add(new TextField
{
X = 110,
Y = 18,
Width = 54,
Height = 10,
Bordered = false
});
search.Changed += this.Search;
this.scroll.WheelArea = this.list;
this.Add(this.list);
this.Add(this.scroll);
this.Search(string.Empty);
}
protected override void Tick() => this.progress.Progress = this.Menu.GetData(0) / 200f;
private void Search(string text)
{
this.list.Items = [.. ores.Where(ore => ore.UnlocalizedName.Contains(text)).Select(ore => new ItemStack(ore))];
this.scroll.MaxRow = (this.list.Items.Count + 2) / 3 - this.list.Rows;
this.list.FirstRow = this.scroll.Row;
}
}
registry.RegisterMenuScreen("ruby:crusher", menu => new CrusherScreen(menu));
A mod builds screens in C# from widgets in Obsidian.API.Client.Screens, like NeoForge's Screen and
AbstractContainerScreen, and the client draws them with its own widgets. A screen is a panel of Width by Height
GUI pixels (176 by 166 unless set), centred on the darkened game, with an optional Background, a GuiImage:
GuiImage.Sprite("ruby:crusher/progress")is a GUI sprite, fromassets/ruby/textures/gui/sprites/crusher/progress.png, stretched, tiled or nine-sliced and animated by its.mcmetalike vanilla's;GuiImage.Texture("ruby:gui/container/crusher", u, v)is a region of a whole texture, like vanilla's container textures.
Widgets are placed in the panel's pixels from its top left, and drawn in the order they were added. The client calls
Init each time the screen is shown, after removing its widgets, so add them there; Tick 20 times a second while
it's open, to update them; and Removed as it closes. Widgets are plain objects the screen changes whenever it likes,
drawn as they are each frame. It all runs on the game's thread; a screen that throws is logged and closed. A mod's
screens close when it unloads.
Label: a line of text, dark grey without a shadow like container labels unless itsColorandShadowsay otherwise, centred in itsWidthwhenCentered.Image: aGuiImageat the widget's size.ProgressBar: aGuiImagecut to itsProgress(0 to 1, rounded up to whole pixels like a furnace's arrow), filling in itsDirection(left to right, or bottom to top like a furnace's flame, ...).Button: vanilla's button with itsText, 200 by 20 unless sized;Pressedis raised on a click, or Enter or Space while it's focused, if it'sActive.TextField: vanilla's edit box, with its caret, selection and the clipboard;Changedis raised with the newTextas the player types (up toMaxLength).Hintshows while it's empty, andBordered = falsedraws only the text, like the creative inventory's search.ScrollBar: a vertical bar the player drags, or scrolls with the wheel over it or itsWheelArea, from row 0 toMaxRow;Scrolledis raised with the newRow. Its handle is vanilla's creative inventory scroller unlessHandlenames another sprite (with a_disabledone, drawn whileMaxRowis 0).SlotGrid: the menu's slots fromFirstSlot,ColumnsbyRows, 18 pixels apart from where its first item goes, likeMenuScreenProperties.Slots. The player clicks, drags, shift-clicks and swaps them with hotbar keys like any container's, and the client draws their stacks and tooltips.ItemGrid: stacks that aren't the menu's slots, like a storage terminal's contents or a list of recipes:Itemsrow by row,ColumnsbyRowsfromFirstRow, with their tooltips.Clickedis raised with the cell's index (even past the list's end), the mouse button (0 left, 1 right, 2 middle, like vanilla's) and Shift; the mod decides what it does, typically with a payload or a menu button.- Tooltips: any widget's
Tooltiptext shows while the mouse is over it, a line per\n, with vanilla's legacy§formatting codes.
A ModMenuScreen is the screen of a menu type, registered with IClientRegistry.RegisterMenuScreen(menuType, factory): the client makes one each time the server opens such a menu. It places the menu's title at Title, the
player's inventory at Inventory (null to place those slots with SlotGrids, after the menu's own from
Menu.SlotCount, or to leave them out) and its "Inventory" label at InventoryLabel. Its Menu is the client's side
of the menu:
Type,TitleandSlotCount, and copies of its slots' stacks (GetItem);- its data slots' values as last sent (
GetData, 0 until sent); - the extra data it was opened with (
ReadOpenData(), reading whatWriteOpenDatawrote); ClickButton(number), which the server'sClickButtongets.
Escape, the inventory key or Close() close the screen and the menu.
ObsidianMod's grinder is a complete machine menu and screen.
A mod's own screens, like settings, aren't tied to a menu: subclass ModScreen and open it with
registry.Screens.Open(screen), from a key binding's Pressed or a payload handler. It shows over the game, or over
the screen shown, which Escape or Close() goes back to.
Screens in Razor
@* Crusher.razor: the crusher's screen of Screens in code, built in Razor. *@
<SlotGrid X="26" Y="35" Columns="3" />
<ProgressBar X="79" Y="34" Width="24" Height="16" Source="Arrow" Progress="@(this.Menu.GetData(0) / 200f)" />
<Button X="8"
Y="58"
Width="50"
Text="@this.Screen.Translate(this.paused ? "ruby.crusher.run" : "ruby.crusher.pause")"
OnClick="this.TogglePause" />
<TextField X="110" Y="18" Width="54" Height="10" Bordered="false" Value="@this.search" ValueChanged="this.Search" />
<ItemGrid X="110" Y="30" Columns="3" Rows="2" Items="this.shown" @bind-FirstRow="this.row" />
<ScrollBar X="166" Y="30" Height="34" MaxRow="@((this.shown.Length + 2) / 3 - 2)" @bind-Row="this.row" />
@code {
private static readonly GuiImage Arrow = GuiImage.Sprite("ruby:crusher/progress");
private static readonly Item[] ores = [ItemsRegistry.IronOre, ItemsRegistry.GoldOre, ItemsRegistry.CopperOre];
private ItemStack[] shown = [];
private string search = string.Empty;
private int row;
private bool paused;
// The client's cascading value: the screen's panel and its menu.
[CascadingParameter]
public ScreenContext Screen { get; set; } = null!;
private IScreenMenu Menu => this.Screen.Menu!;
protected override void OnInitialized()
{
this.Screen.Background = GuiImage.Texture("ruby:gui/container/crusher");
this.Search(string.Empty);
}
private void TogglePause()
{
// The menu's ClickButton pauses on 0 and runs on anything else.
this.paused = !this.paused;
this.Menu.ClickButton(this.paused ? 0 : 1);
}
private void Search(string text)
{
this.search = text;
this.shown = [.. ores.Where(ore => ore.UnlocalizedName.Contains(text)).Select(ore => new ItemStack(ore))];
this.row = 0;
}
}
registry.RegisterMenuScreen<Crusher>("ruby:crusher");
A mod can build its screens in Razor rather than in code: .razor components compiled into the mod's assembly, so
the client loads and unloads them with the rest of its code. The mod's project uses the Razor SDK, and its components
inherit ModComponent (set once in _Imports.razor):
<Project Sdk="Microsoft.NET.Sdk.Razor">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<!-- A mod has no web assets: its output is what its archive holds. -->
<StaticWebAssetsEnabled>false</StaticWebAssetsEnabled>
</PropertyGroup>
<ItemGroup>
<!-- The server or client provides the API, so it isn't packed with the mod. Obsidian.API.Client brings the
ASP.NET Core framework, whose Blazor components Razor screens are built on. -->
<PackageReference Include="Obsidian.API" Version="1.0.0" ExcludeAssets="runtime" />
<PackageReference Include="Obsidian.API.Client" Version="1.0.0" ExcludeAssets="runtime" />
</ItemGroup>
</Project>
@* _Imports.razor *@
@using Microsoft.AspNetCore.Components
@using Obsidian.API
@using Obsidian.API.Client.Razor
@using Obsidian.API.Client.Screens
@using Obsidian.API.Inventory
@using Obsidian.API.Registries
@inherits ModComponent
A screen in Razor is hosted like one in code. RegisterMenuScreen<TComponent>(menuType) shows a menu type with a new
TComponent each time the server opens it, and registry.Screens.Open<TComponent>(parameters) opens a mod's own
screen, with the parameters by name. Components draw with the parts in Obsidian.API.Client.Razor, the Razor
counterparts of the widgets in Screens in code; HTML elements draw nothing.
Panel: a box holding parts, its child content, at their positions or stacked by itsFlow(ColumnorRow, withGap,PaddingandAlign), optionally filled with aColorand clipping what's outside it (Clip).Label,Image,ProgressBar: like the widgets, with aSourceGuiImageat the part's size.Button:Text,Active, andOnClick.TextField:ValueandValueChanged(@bind-Value),MaxLength,HintandBordered.ScrollBar:RowandRowChanged(@bind-Row) up toMaxRow, with itsHandlesprite; the wheel over it scrolls it.SlotGrid: the menu's slots fromFirstSlot,ColumnsbyRows. Its position is from the top left of the screen's panel wherever it is in the markup, since the container screen draws the slots.ItemGrid:Items,ColumnsbyRowsfromFirstRow, with their tooltips;OnClickwith the cell, the button and Shift, and the wheel over it raisesFirstRowChanged(@bind-FirstRow, to the same field as a scroll bar's@bind-Row).- Tooltips: any part's
Tooltiptext, like a widget's.
Each part has X, Y, Width and Height in GUI pixels from the top left of the panel it's in (or offsets in a
stacking panel), with null sizes meaning its natural size or its type's default (buttons and text fields 200 by 20,
scroll bars 12 wide), and Visible. A mod's own components, built from parts, nest like any Razor components.
The screen's components get its ScreenContext as a cascading value: the Menu (null for a mod's own screen), the
panel's Width, Height and Background, a menu screen's Inventory, Title and InventoryLabel positions,
Close(), Translate and TextWidth. Set the panel's properties as the component initializes. The client redraws
the screen every client tick, and components taking the context render with it, so markup reading the menu's data
slots stays current; other components render as Blazor's do.
ModComponent is the mod's counterpart of Blazor's ComponentBase, with its lifecycle (OnInitialized(Async),
OnParametersSet(Async), OnAfterRender(Async), ShouldRender, StateHasChanged, InvokeAsync), and
OnDispose to clean up. It all runs on the game's thread, as a screen in code does, and whatever throws is logged and
closes the screen. Two limits:
- the client only renders components that inherit
ModComponentand don't implement Blazor's component interfaces (IComponent,IHandleEvent,IHandleAfterRender,IDisposable,IAsyncDisposable) themselves; - components must not use
[Inject]or@inject; use theScreenContextcascading parameter instead.
When the mod unloads, its screens close. ObsidianMod's grinder registers
GrinderView.razor, the Razor form of its GrinderScreen.
HUD overlays
// The player's mana in the top left corner, a bar and its amount, from what the server last sent.
public sealed class ManaOverlay : ModOverlay
{
private readonly ProgressBar bar = new()
{
Y = 10,
Width = 81,
Height = 5,
Source = GuiImage.Sprite("ruby:hud/mana_bar")
};
private readonly Label amount = new()
{
Color = 0xFF55FFFF,
Shadow = true
};
public ManaOverlay()
{
this.X = 4;
this.Y = 4;
this.Width = 81;
this.Height = 15;
this.Add(new Image
{
Y = 10,
Width = 81,
Height = 5,
Source = GuiImage.Sprite("ruby:hud/mana_bar_background")
});
this.Add(this.bar);
this.Add(this.amount);
}
// Set by the payload handler, on the connection's thread; the widgets change on the game's, in Tick.
public int Mana { get; set; }
protected override void Tick()
{
var mana = this.Mana;
this.bar.Progress = mana / 20f;
this.amount.Text = $"{mana} / 20";
}
}
var mana = new ManaOverlay();
registry.RegisterOverlay(mana);
registry.HandlePayload<ManaChanged>((changed, _) => mana.Mana = changed.Mana);
A mod draws on the HUD with a ModOverlay, registered with IClientRegistry.RegisterOverlay(overlay), like a
NeoForge mod's GUI layer: widgets from Screens in code in a box of Width by Height GUI pixels.
Anchor puts the box at a corner of the screen, the middle of an edge or the centre, by the same point of the box
(TopLeft by default), then X and Y move it (negative for left and up). Overlays only show: they draw labels,
images, progress bars and item grids (without tooltips), but not buttons, text fields, scroll bars or slot grids.
Layer says where the overlay goes in vanilla's HUD: BelowChat, the default, over the hotbar, the player's bars,
boss bars, the scoreboard and titles but under the chat and the player list; AboveAll over all of them. Overlays in
a layer are drawn in the order they were registered.
Overlays are drawn while the player is in a world, under any screen, and not while the HUD is hidden (F1). Tick runs
on the game's thread every client tick while the player is in a world, to update the widgets; an overlay whose Tick
throws is removed. A mod's overlays go when it unloads.