Render geo models in items
This commit is contained in:
@@ -9,13 +9,14 @@ import { get_sprite_region } from "@/client/sprites.ts";
|
||||
import type { ItemEntity } from "@/client/entity/item_entity.ts";
|
||||
import { contained_fluid, type ItemData, ItemStack } from "@/common/inventory.ts";
|
||||
import type { FluidVariant } from "@/common/mod_api/shared.ts";
|
||||
import type { FluidJson } from "@/common/mod_data.ts";
|
||||
import type { EntityModelJson, FluidJson } from "@/common/mod_data.ts";
|
||||
import { light_color, push_vertex, Texture } from "@/client/renderer/mod.ts";
|
||||
import {
|
||||
bake_model,
|
||||
type BakedQuad,
|
||||
block_item_texture,
|
||||
block_variant,
|
||||
classify_quad,
|
||||
cube_face_texture,
|
||||
cube_face_tint,
|
||||
type DisplayTransform,
|
||||
@@ -30,6 +31,8 @@ import { get_state_value, item_texture } from "@/common/utils.ts";
|
||||
import { ID_MASK, TEXTURE_SIZE } from "@/common/constants.ts";
|
||||
import type { ClientLevel } from "@/client/level/client_level.ts";
|
||||
import { entity_tint } from "./entity_light.ts";
|
||||
import { bone_matrices, IDENTITY } from "./model_math.ts";
|
||||
import { push_model } from "./model_renderer.ts";
|
||||
import type { Vec3 } from "./player_renderer.ts";
|
||||
import { fluid_rules } from "@/client/fluid_rules.ts";
|
||||
import { color_rgb, tint_without_biome, type TintColor } from "@/common/worldgen/biome_colors.ts";
|
||||
@@ -249,11 +252,15 @@ export interface ItemModel {
|
||||
block?: BlockRegistry;
|
||||
}
|
||||
|
||||
// an item's own model, or its block's item_model with the block's textures, baked the first time it's drawn. undefined
|
||||
// for items drawn as a cube or as their sprite
|
||||
// an item's own model, or its block's item_model with the block's textures, baked the first time it's drawn. an item's
|
||||
// own can be an entity model, drawn in the item's texture. undefined for items drawn as a cube or as their sprite
|
||||
export function item_model_of(item: ItemStack): ItemModel | undefined {
|
||||
const info = EverythingRegistry.get<ItemRegistry>("items", item.type_id);
|
||||
if (info?.model !== undefined) return baked_item_model(info, info.model);
|
||||
if (info?.model !== undefined) {
|
||||
const entity_model = EverythingRegistry.get<EntityModelJson>("entity_models", info.model);
|
||||
if (entity_model) return baked_entity_item_model(entity_model, item_texture(item, info));
|
||||
return baked_item_model(info, info.model);
|
||||
}
|
||||
const block = placed_block(item);
|
||||
if (block?.item_model !== undefined) return baked_item_model(block, block.item_model, block);
|
||||
return undefined;
|
||||
@@ -270,6 +277,54 @@ function baked_item_model(key: ItemRegistry | BlockRegistry, id: string, block?:
|
||||
}
|
||||
const baked_items = new WeakMap<ItemRegistry | BlockRegistry, ItemModel>();
|
||||
|
||||
// by texture, since an item's texture can change with its data
|
||||
function baked_entity_item_model(model: EntityModelJson, texture: string): ItemModel {
|
||||
let by_texture = baked_entity_items.get(model);
|
||||
if (!by_texture) {
|
||||
by_texture = new Map();
|
||||
baked_entity_items.set(model, by_texture);
|
||||
}
|
||||
let baked = by_texture.get(texture);
|
||||
if (!baked) {
|
||||
baked = { quads: entity_model_quads(model, texture), display: model.display ?? {} };
|
||||
by_texture.set(texture, baked);
|
||||
}
|
||||
return baked;
|
||||
}
|
||||
const baked_entity_items = new WeakMap<EntityModelJson, Map<string, ItemModel>>();
|
||||
|
||||
// an entity model as a block model's quads, standing on the block's bottom in its middle like it stands on the ground,
|
||||
// 16 of its pixels across the block. its uvs are pixels of the texture, 0 to 16 like a block model's
|
||||
export function entity_model_quads(model: EntityModelJson, texture: string): BakedQuad[] {
|
||||
const vertices: number[][] = [];
|
||||
const pixels = { width: 1, height: 1 } as Texture;
|
||||
const whole_texture = { x: 0, y: 0, width: TEXTURE_SIZE, height: TEXTURE_SIZE };
|
||||
const to_block = (x: number, y: number, z: number): Vec3 => [x / 16 + 0.5, y / 16, z / 16 + 0.5];
|
||||
push_model(model, bone_matrices(model, () => IDENTITY), pixels, whole_texture, to_block, undefined, undefined, (
|
||||
x,
|
||||
y,
|
||||
z,
|
||||
u,
|
||||
v,
|
||||
) => vertices.push([x, y, z, u, v]));
|
||||
const quads: BakedQuad[] = [];
|
||||
// two triangles a box face, its corners 0 1 2 and 0 2 3
|
||||
for (let i = 0; i < vertices.length; i += 6) {
|
||||
const corners = [vertices[i], vertices[i + 1], vertices[i + 2], vertices[i + 5]];
|
||||
const positions = corners.flatMap(([x, y, z]) => [x, y, z]);
|
||||
quads.push({
|
||||
positions,
|
||||
uvs: corners.flatMap(([, , , u, v]) => [u, v]),
|
||||
texture,
|
||||
variables: [],
|
||||
...classify_quad(positions),
|
||||
cull: -1,
|
||||
shade: true,
|
||||
});
|
||||
}
|
||||
return quads;
|
||||
}
|
||||
|
||||
// whether an item is drawn as a block or a model rather than its sprite, which decides how big it's drawn and how it's
|
||||
// held when its model has no display transform for that
|
||||
export function drawn_as_model(item: ItemStack) {
|
||||
|
||||
@@ -500,7 +500,7 @@ export function bake_model(
|
||||
let cull = face_json.cullface ? FACE_INDEX[face_json.cullface] : -1;
|
||||
for (let t = 0; t < x_turns && cull >= 0; t++) cull = TURN_X[cull];
|
||||
for (let t = 0; t < turns && cull >= 0; t++) cull = TURN_Y[cull];
|
||||
const { face: facing, flush, aligned } = classify(positions);
|
||||
const { face: facing, flush, aligned } = classify_quad(positions);
|
||||
quads.push({
|
||||
positions,
|
||||
uvs,
|
||||
@@ -560,7 +560,7 @@ export function element_rotation(element: ModelElementJson): (point: number[]) =
|
||||
}
|
||||
|
||||
// which way a quad faces most, whether it's flat against the block's edge, and whether it faces straight along an axis
|
||||
function classify(p: number[]): { face: number; flush: boolean; aligned: boolean } {
|
||||
export function classify_quad(p: number[]): { face: number; flush: boolean; aligned: boolean } {
|
||||
const e1 = [p[3] - p[0], p[4] - p[1], p[5] - p[2]];
|
||||
const e2 = [p[9] - p[0], p[10] - p[1], p[11] - p[2]];
|
||||
const normal = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]];
|
||||
|
||||
@@ -284,7 +284,8 @@ export interface ItemRegistry<T = unknown | undefined> {
|
||||
texture_id: string | ((item: ItemStack<T>) => string);
|
||||
// shown in place of texture_id while the stack's data has that key set, like a cast fishing rod. the first wins
|
||||
data_textures?: Record<string, string>;
|
||||
// a model it's drawn with instead of its texture, with the model's own textures, like a 3d wrench
|
||||
// a model it's drawn with instead of its texture, with the model's own textures, like a 3d wrench. or an entity
|
||||
// model (see EntityModelJson), drawn in its texture
|
||||
model?: string;
|
||||
// what players see, like "Iron Ingot". made from the id when not set, see display_name in common/utils.ts
|
||||
name?: string;
|
||||
|
||||
+2
-1
@@ -361,7 +361,8 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
|
||||
errors.push(`${file}: item ${json.id} has no texture, and no block of this mod gives it an item`);
|
||||
}
|
||||
for (const texture of Object.values(json.data_textures ?? {})) uses(file, texture, "texture");
|
||||
if (json.model) uses(file, json.model, "model");
|
||||
// an entity model is drawn in the item's texture
|
||||
if (json.model && !entity_model_owners.has(json.model)) uses(file, json.model, "model");
|
||||
if (json.places) uses(file, json.places, "block");
|
||||
if (json.food?.returns) uses(file, json.food.returns, "item");
|
||||
for (const layer of json.layers ?? []) uses(file, layer.texture, "texture");
|
||||
|
||||
+23
-1
@@ -23,7 +23,7 @@ import {
|
||||
WATERLOGGED,
|
||||
type WornProperties,
|
||||
} from "./everything_registry.ts";
|
||||
import type { BlockPart, BlockVariant, ModelFileJson } from "./block_models.ts";
|
||||
import type { BlockPart, BlockVariant, ModelDisplay, ModelFileJson } from "./block_models.ts";
|
||||
import { expand_items, list_matches } from "./tags.ts";
|
||||
import { GAME_VERSION } from "./constants.ts";
|
||||
import type { PlayOptions } from "./mod_api/shared.ts";
|
||||
@@ -567,6 +567,8 @@ const entity_model_schema = z.object({
|
||||
// the size its uvs are laid out for, the texture is stretched to it
|
||||
texture_width: z.int().min(1),
|
||||
texture_height: z.int().min(1),
|
||||
// how it's placed where it's shown as an item, from the geometry's item_display_transforms
|
||||
display: z.partialRecord(z.enum(DISPLAY_CONTEXTS), display_transform).optional(),
|
||||
// parents come before their children
|
||||
bones: z.array(entity_bone).superRefine((bones, ctx) => {
|
||||
const names = new Set<string>();
|
||||
@@ -1063,10 +1065,12 @@ export function entity_model_from_geo(json: unknown, id: string): { model?: Enti
|
||||
};
|
||||
}
|
||||
const bones = Array.isArray(geometry.bones) ? geometry.bones : [];
|
||||
const display = geo_display(geometry.item_display_transforms);
|
||||
const model = {
|
||||
id,
|
||||
texture_width: geometry.description.texture_width,
|
||||
texture_height: geometry.description.texture_height,
|
||||
...(display === undefined ? {} : { display }),
|
||||
bones: bones.map((bone) => {
|
||||
if (!is_object(bone)) return bone;
|
||||
const { name, parent, pivot, rotation } = bone;
|
||||
@@ -1094,6 +1098,24 @@ export function entity_model_from_geo(json: unknown, id: string): { model?: Enti
|
||||
return problems.length === 0 ? { model: model as EntityModelJson, problems } : { problems };
|
||||
}
|
||||
|
||||
// the places a geometry's item_display_transforms has that items are shown in, with what of each the engine uses. their
|
||||
// rotation_pivot, scale_pivot and fit_to_frame are left out
|
||||
function geo_display(transforms: unknown): ModelDisplay | undefined {
|
||||
if (!is_object(transforms)) return undefined;
|
||||
const display: Record<string, unknown> = {};
|
||||
for (const context of DISPLAY_CONTEXTS) {
|
||||
const transform = transforms[context];
|
||||
if (!is_object(transform)) continue;
|
||||
const { rotation, translation, scale } = transform;
|
||||
display[context] = {
|
||||
...(rotation === undefined ? {} : { rotation }),
|
||||
...(translation === undefined ? {} : { translation }),
|
||||
...(scale === undefined ? {} : { scale }),
|
||||
};
|
||||
}
|
||||
return Object.keys(display).length > 0 ? display as ModelDisplay : undefined;
|
||||
}
|
||||
|
||||
export function validate_clip(json: unknown): Problems {
|
||||
return find_problems(clip_schema, json);
|
||||
}
|
||||
|
||||
@@ -330,7 +330,8 @@ get the id `<mod id>:<name>`. From the file's first geometry, bworld uses:
|
||||
|
||||
- the description's `texture_width` and `texture_height`,
|
||||
- each bone's `name`, `parent`, `pivot` and `rotation`,
|
||||
- each cube's `origin`, `size`, `uv`, `inflate`, `pivot` and `rotation`.
|
||||
- each cube's `origin`, `size`, `uv`, `inflate`, `pivot` and `rotation`,
|
||||
- `item_display_transforms`, for an [item drawn with it](../resources/models.md#entity-models-as-items).
|
||||
|
||||
Cubes can use box UV (`"uv": [u, v]`) or per face UV (`"uv": { "north": { "uv": [u, v], "uv_size": [w, h] }, ... }`),
|
||||
where a face that's left out isn't drawn and a negative size flips it. Faces are drawn from both sides, like Bedrock's
|
||||
|
||||
+18
-18
@@ -42,24 +42,24 @@ down to 0 is gone.
|
||||
|
||||
## Properties
|
||||
|
||||
| Field | Default | Meaning |
|
||||
| ----------------- | ------------------- | -------------------------------------------------------------------------------------- |
|
||||
| `id` | required | The item's id. |
|
||||
| `texture` | required | The texture it's drawn with. Leave it out to [fill in a block's item](#block-items). |
|
||||
| `name` | from the id | What players see. `copper_tools:copper_ingot` is "Copper Ingot" when not set. |
|
||||
| `lore` | none | Tooltip text under the name. `\n` starts a new line. |
|
||||
| `max_stack` | `64`, `1` for tools | How many fit in one slot. |
|
||||
| `base_sell_value` | none | What one is worth when sold, a whole number of 0 or more. |
|
||||
| `places` | none | A block it places when used on a block, like seeds. |
|
||||
| `tool` | none | Makes it a [tool](tools.md). |
|
||||
| `food` | none | Makes it [edible](food.md). |
|
||||
| `data_textures` | none | Other textures, picked by the stack's `data`, see below. |
|
||||
| `model` | none | A [model](../resources/models.md#item-models) it's drawn with instead of its texture. |
|
||||
| `worn` | none | How it looks worn on a player, see [below](#worn-models). |
|
||||
| `targets_fluids` | `false` | Players holding it aim at fluids, like buckets and fishing rods. Others aim through. |
|
||||
| `fluid_container` | none | Makes it hold a fluid, like a bucket, see [Fluids](../resources/fluids.md#containers). |
|
||||
| `layers` | none | Textures drawn over its own, each in a color, see [below](#layers). |
|
||||
| `components` | none | [Item components](#item-components) and their parameters. |
|
||||
| Field | Default | Meaning |
|
||||
| ----------------- | ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `id` | required | The item's id. |
|
||||
| `texture` | required | The texture it's drawn with. Leave it out to [fill in a block's item](#block-items). |
|
||||
| `name` | from the id | What players see. `copper_tools:copper_ingot` is "Copper Ingot" when not set. |
|
||||
| `lore` | none | Tooltip text under the name. `\n` starts a new line. |
|
||||
| `max_stack` | `64`, `1` for tools | How many fit in one slot. |
|
||||
| `base_sell_value` | none | What one is worth when sold, a whole number of 0 or more. |
|
||||
| `places` | none | A block it places when used on a block, like seeds. |
|
||||
| `tool` | none | Makes it a [tool](tools.md). |
|
||||
| `food` | none | Makes it [edible](food.md). |
|
||||
| `data_textures` | none | Other textures, picked by the stack's `data`, see below. |
|
||||
| `model` | none | A [model](../resources/models.md#item-models) it's drawn with instead of its texture, or an [entity model](../resources/models.md#entity-models-as-items). |
|
||||
| `worn` | none | How it looks worn on a player, see [below](#worn-models). |
|
||||
| `targets_fluids` | `false` | Players holding it aim at fluids, like buckets and fishing rods. Others aim through. |
|
||||
| `fluid_container` | none | Makes it hold a fluid, like a bucket, see [Fluids](../resources/fluids.md#containers). |
|
||||
| `layers` | none | Textures drawn over its own, each in a color, see [below](#layers). |
|
||||
| `components` | none | [Item components](#item-components) and their parameters. |
|
||||
|
||||
### Textures From Data
|
||||
|
||||
|
||||
@@ -236,6 +236,17 @@ the same places Minecraft's do, so a transform made for Minecraft, like in Block
|
||||
here. A model gets its parent's transform for each place it doesn't set its own. Minecraft's other places, like third
|
||||
person, aren't used.
|
||||
|
||||
### Entity Models as Items
|
||||
|
||||
An item's `model` can also be an [entity model](../entities/index.md#entity-models), a `models/<name>.geo.json` made in
|
||||
Blockbench, drawn in the item's own `texture` laid out for the model's `texture_width` and `texture_height`. It stands
|
||||
in the middle of the block the way Blockbench shows it, 16 pixels to a block with its bottom at 0, and its faces are
|
||||
shaded like a block model's. Its pose is the one in the file, bones aren't animated.
|
||||
|
||||
Its display transforms are the geometry's `item_display_transforms`, which Blockbench's Display tab writes for the
|
||||
"Bedrock Block" format. Only `rotation`, `translation` and `scale` of the places above are used: `rotation_pivot`,
|
||||
`scale_pivot` and `fit_to_frame` aren't.
|
||||
|
||||
## Lighting
|
||||
|
||||
Faces flat against the block's edge get smooth lighting and ambient occlusion like a full block's. Anything inside the
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"format_version": 1,
|
||||
"item": {
|
||||
"id": "dangerous_business:air_horn",
|
||||
"texture": "dangerous_business:air_horn",
|
||||
"model": "dangerous_business:air_horn"
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,7 @@
|
||||
import { assert, assertAlmostEquals, assertEquals } from "@std/assert";
|
||||
import { mat4 } from "gl-matrix";
|
||||
import { display_transform, drawn_as_model, item_model_of } from "@/client/rendering/item_renderer.ts";
|
||||
import type { DisplayTransform } from "@/common/block_models.ts";
|
||||
import { type DisplayTransform, FACE_INDEX } from "@/common/block_models.ts";
|
||||
import { ItemStack } from "@/common/inventory.ts";
|
||||
import { load_and_check } from "@/tools/check_mods.ts";
|
||||
import { create_mod } from "@/tools/new_mod.ts";
|
||||
@@ -57,6 +57,49 @@ Deno.test("check-mods reports an item's model that doesn't exist", async () => {
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("an item can be drawn with an entity model, in its own texture, placed by the model's display transforms", async () => {
|
||||
const dir = mods_with({ textures: { "0": "bworld:oak_planks" }, elements: [HANDLE] });
|
||||
// the same handle as a bedrock model, as blockbench exports it
|
||||
Deno.removeSync(`${dir}/copper_tools/models/wrench.json`);
|
||||
Deno.writeTextFileSync(
|
||||
`${dir}/copper_tools/models/wrench.geo.json`,
|
||||
JSON.stringify({
|
||||
format_version: "1.21.0",
|
||||
"minecraft:geometry": [{
|
||||
description: { identifier: "geometry.wrench", texture_width: 16, texture_height: 16 },
|
||||
item_display_transforms: {
|
||||
gui: { ...GUI, translation: [0, 0, 0], rotation_pivot: [0, 0, 0], fit_to_frame: true },
|
||||
thirdperson_righthand: { rotation: [70, 45, 0] },
|
||||
},
|
||||
bones: [{
|
||||
name: "handle",
|
||||
pivot: [0, 0, 0],
|
||||
cubes: [{ origin: [-1, 0, -1], size: [2, 14, 2], uv: [0, 0] }],
|
||||
}],
|
||||
}],
|
||||
}),
|
||||
);
|
||||
const report = (await load_and_check(dir)).find((mod) => mod.id === "copper_tools")!.report;
|
||||
assertEquals(report.errors, []);
|
||||
await test_game(dir);
|
||||
const wrench = new ItemStack("copper_tools:wrench", 1);
|
||||
const model = item_model_of(wrench)!;
|
||||
assert(drawn_as_model(wrench));
|
||||
assertEquals(model.quads.length, 6);
|
||||
assert(model.quads.every((quad) => quad.texture === "bworld:stick"));
|
||||
// only what the engine places items with, in the places it shows them
|
||||
assertEquals(model.display, { gui: { ...GUI, translation: [0, 0, 0] } });
|
||||
// standing in the middle of the block, 16 pixels to it
|
||||
const xs = model.quads.flatMap((quad) => quad.positions.filter((_, i) => i % 3 === 0));
|
||||
const ys = model.quads.flatMap((quad) => quad.positions.filter((_, i) => i % 3 === 1));
|
||||
assertEquals([Math.min(...xs), Math.max(...xs)], [7 / 16, 9 / 16]);
|
||||
assertEquals([Math.min(...ys), Math.max(...ys)], [0, 14 / 16]);
|
||||
// faces know which way they face, for their shading
|
||||
const top = model.quads.find((quad) => quad.face === FACE_INDEX.top)!;
|
||||
assert(top.positions.filter((_, i) => i % 3 === 1).every((y) => y === 14 / 16));
|
||||
Deno.removeSync(dir, { recursive: true });
|
||||
});
|
||||
|
||||
Deno.test("a display transform moves, turns around z then y then x, and scales, around the model's middle", () => {
|
||||
// an item's points are centered on x and z, from 0 to 1 high
|
||||
const near = (actual: number[], expected: number[]) =>
|
||||
|
||||
Reference in New Issue
Block a user