diff --git a/client/client.ts b/client/client.ts index 2c69aa1..48d721b 100644 --- a/client/client.ts +++ b/client/client.ts @@ -318,7 +318,7 @@ export class Client { player.entity_interaction_range, (entity) => entity instanceof RemotePlayer || - (entity instanceof RemoteEntity && !entity.dead && is_hittable(entity)), + (entity instanceof RemoteEntity && !entity.dead && is_pickable(entity)), ); // a block in front of the entity hides it this.hit_result = this.level.pick( @@ -377,6 +377,8 @@ export class Client { if (!attacking && using) { this.game_mode.use_item_on(hit); } + } else if (use_pressed && this.entity_hit) { + this.game_mode.interact(this.entity_hit); } else if (use_pressed) { this.game_mode.use_item(); } else if (!this.entity_hit && InputManager.is_mouse_pressed(0)) { @@ -413,7 +415,8 @@ export class Client { } } -// mobs can be hit, scripted entities like the fishing hook can't. kinds the client doesn't know are left to the server -function is_hittable(entity: RemoteEntity) { +// what the crosshair can be on: mobs and objects, not scripted entities like the fishing hook. kinds the client doesn't +// know are left to the server +function is_pickable(entity: RemoteEntity) { return EverythingRegistry.get("entities", entity.type)?.behavior !== "scripted"; } diff --git a/client/game_mode.ts b/client/game_mode.ts index 8b1daae..4ad3d6a 100644 --- a/client/game_mode.ts +++ b/client/game_mode.ts @@ -196,20 +196,28 @@ export class MultiPlayerGameMode { this.client.player.last_attack = performance.now(); } + // right click on an entity or another player, for mods' entity_interact. the server uses the held item when none + // of them stops it + interact(entity: Entity) { + this.client.player.send_position_now(); + this.client.connection.send({ type: "interact_entity", id: entity.id }); + } + // right click on nothing use_item() { this.client.connection.send({ type: "use_item" }); } // whether a mob's or player's collision box overlaps the block, the server doesn't let solid blocks go there. mobs - // are the mod entities that aren't scripted, players are this one and the others + // are the mod entities that aren't scripted or objects, players are this one and the others #occupied(x: number, y: number, z: number, block: BlockRegistry, value: number) { const shape = collision_shape_at(block, value); for (const entity of this.client.level.entities.values()) { const json = entity instanceof RemoteEntity ? EverythingRegistry.get("entities", entity.type) : undefined; - const blocks = entity instanceof Player || (json !== undefined && json.behavior !== "scripted"); + const blocks = entity instanceof Player || + (json !== undefined && json.behavior !== "scripted" && json.behavior !== "object"); if (blocks && box_overlaps_block(entity, x, y, z, shape)) return true; } return false; diff --git a/client/rendering/entity_renderer.ts b/client/rendering/entity_renderer.ts index abf20bf..08ac7c3 100644 --- a/client/rendering/entity_renderer.ts +++ b/client/rendering/entity_renderer.ts @@ -5,7 +5,7 @@ // turns to the entity's yaw, and its bones are posed by its type's animator from a mod (see entity_animators.ts). without // one, a bone named "head" turns to where it looks, and bones named like minecraft's humanoid ones (right_arm, left_arm, // right_leg, left_leg) swing as it walks, the right arm when it attacks too. entities without a model are their texture -// facing the camera, like minecraft's fishing hook +// facing the camera, like minecraft's fishing hook, and objects without one are the item they hold import { AssetManager } from "@/client/assets.ts"; import type { Camera } from "@/client/camera.ts"; import type { RemoteEntity } from "@/client/entity/remote_entity.ts"; @@ -18,6 +18,8 @@ import { HURT_TINT } from "./player_renderer.ts"; import { bone_matrices, IDENTITY, model_pivot, multiply, rotation_around, type Vec3 } from "./model_math.ts"; import { push_model } from "./model_renderer.ts"; import { entity_tint } from "./entity_light.ts"; +import { push_item, synced_stack } from "./item_renderer.ts"; +import type { ItemData } from "@/common/inventory.ts"; // models are in texture pixels, 16 to a block const PIXEL = 1 / 16; @@ -27,29 +29,42 @@ export function render_mod_entity(entity: RemoteEntity, camera: Camera, partial_ const json = EverythingRegistry.get("entities", entity.type); if (!json) return; const atlas = AssetManager.instance.get("cubi:textures"); - const region = get_sprite_region(json.texture); const hurt = entity.hurt_time > 0 || entity.dead ? HURT_TINT : undefined; const tint = entity_tint(entity, partial_tick, hurt, entity.data.on_fire === true); + const scale = json.scale ?? 1; if (json.model === undefined) { - render_sprite(entity, camera, atlas, region, partial_tick, tint); + // an object is the item it holds, the size the item's model is made + const item = entity.data.item as ItemData | undefined; + if (json.behavior === "object") { + if (item) push_item(atlas, synced_stack(item), turned_with(entity, partial_tick, scale), tint); + } else if (json.texture !== undefined) { + render_sprite(entity, camera, atlas, get_sprite_region(json.texture), scale, partial_tick, tint); + } return; } const model = EverythingRegistry.get("entity_models", json.model); - if (!model) return; - - const { x, y, z } = entity.render_position(partial_tick); - const yaw_sin = Math.sin(entity.yaw); - const yaw_cos = Math.cos(entity.yaw); - const to_world = (px: number, py: number, pz: number): Vec3 => { - const [mx, my, mz] = [px * PIXEL, py * PIXEL, pz * PIXEL]; - return [x + mx * yaw_cos + mz * yaw_sin, y + my, z - mx * yaw_sin + mz * yaw_cos]; - }; + if (!model || json.texture === undefined) return; + const placed = turned_with(entity, partial_tick, scale); + const to_world = (px: number, py: number, pz: number) => placed(px * PIXEL, py * PIXEL, pz * PIXEL); const offsets = entity.animation?.pose(entity.age + partial_tick); const pose = offsets ? () => IDENTITY : default_pose(entity, partial_tick); + const region = get_sprite_region(json.texture); push_model(model, bone_matrices(model, pose, offsets), atlas, region, to_world, tint); } +// from blocks around the entity's feet, its own way round, to the world: sized by scale and turned to its yaw +function turned_with(entity: RemoteEntity, partial_tick: number, scale: number) { + const { x, y, z } = entity.render_position(partial_tick); + const yaw_sin = Math.sin(entity.yaw) * scale; + const yaw_cos = Math.cos(entity.yaw) * scale; + return (bx: number, by: number, bz: number): Vec3 => [ + x + bx * yaw_cos + bz * yaw_sin, + y + by * scale, + z - bx * yaw_sin + bz * yaw_cos, + ]; +} + // the head looking and the humanoid swing, for an entity without an animator function default_pose(entity: RemoteEntity, partial_tick: number) { const limbs = limb_angles(entity, partial_tick); @@ -86,14 +101,15 @@ function render_sprite( camera: Camera, atlas: Texture, region: SpriteRegion, + scale: number, partial_tick: number, [r, g, b]: Vec3, ) { const { x, y, z } = entity.render_position(partial_tick); const cy = y + entity.height / 2; // the camera's right and up, halved to the sprite's size - const half_width = region.width * PIXEL / 2; - const half_height = region.height * PIXEL / 2; + const half_width = region.width * PIXEL * scale / 2; + const half_height = region.height * PIXEL * scale / 2; const [yaw_sin, yaw_cos] = [Math.sin(camera.yaw), Math.cos(camera.yaw)]; const [pitch_sin, pitch_cos] = [Math.sin(camera.pitch), Math.cos(camera.pitch)]; const right: Vec3 = [yaw_cos * half_width, 0, -yaw_sin * half_width]; diff --git a/client/rendering/item_renderer.ts b/client/rendering/item_renderer.ts index e67a682..53e3b1b 100644 --- a/client/rendering/item_renderer.ts +++ b/client/rendering/item_renderer.ts @@ -127,8 +127,17 @@ export function render_item_entity(entity: ItemEntity, partial_tick: number) { } } -// the stacks shown items are drawn as, by their "item" client data, which is replaced whenever it changes -const shown_stacks = new WeakMap(); +// the stack an item synced to clients is drawn as, like a shown item's "item" client data or an object's. made once +// for each, since the data is replaced whenever it changes +export function synced_stack(data: ItemData): ItemStack { + let stack = synced_stacks.get(data); + if (!stack) { + stack = ItemStack.from_data(data); + synced_stacks.set(data, stack); + } + return stack; +} +const synced_stacks = new WeakMap(); // every item blocks with item_display show on top of them, their "item" client data, see BlockRegistry.item_display. // the atlas has to be the current texture @@ -143,11 +152,7 @@ export function render_block_items(level: ClientLevel) { const value = level.get_block_value(x, y, z); const block = blocks[value & ID_MASK]; if (!block?.item_display) continue; - let item = shown_stacks.get(shown); - if (!item) { - item = ItemStack.from_data(shown); - shown_stacks.set(shown, item); - } + const item = synced_stack(shown); // the block's own light, or the one above for blocks light doesn't get into, since the items sit on top const here = level.get_light(x, y, z); const above = level.get_light(x, y + 1, z); diff --git a/common/everything_registry.ts b/common/everything_registry.ts index a485fe9..dd79696 100644 --- a/common/everything_registry.ts +++ b/common/everything_registry.ts @@ -287,6 +287,9 @@ export interface ItemRegistry { // 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; + // the entity it lies in the world as instead of a cubi:item, holding the stack, like neoforge's hasCustomEntity. + // an "object" (see EntityJson.behavior) + entity?: string; // what players see, like "Iron Ingot". made from the id when not set, see display_name in common/utils.ts name?: string; block_id?: string; diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index 22f0e1f..b415b4c 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -381,6 +381,13 @@ export interface BlockInteractEvent { readonly item: ItemStack | undefined; } +// a right click on an entity, like neoforge's PlayerInteractEvent.EntityInteract +export interface EntityInteractEvent { + readonly player: Player; + readonly entity: EntityRef; + readonly item: ItemStack | undefined; +} + // a player or a mob being hurt, like neoforge's LivingIncomingDamageEvent export interface EntityDamageEvent { readonly entity: LivingRef; @@ -408,6 +415,8 @@ export interface ServerBeforeEvents { block_break: EventSignal; block_place: EventSignal; block_interact: EventSignal; + // handlers do what the click does, and cancel it so the held item isn't used too + entity_interact: EventSignal; chat_send: EventSignal; entity_damage: EventSignal; } @@ -584,10 +593,10 @@ export interface EntityRef { // like neoforge's Entity.kill: a player or a mob dies, even when invulnerable, and anything else is removed. cause // is for events and the death message, like LivingRef.damage's. mods' entity_damage can still cancel it kill(cause?: string): void; - // what an item lying around is, a copy. undefined for every other kind of entity + // what an item lying around is, or what an object holds, a copy. undefined for every other kind of entity get_item(): ItemStack | undefined; - // changes what an item lying around is, like ItemEntity.setItem. undefined or a count of 0 removes it. throws for - // every other kind of entity + // changes what an item lying around is, like ItemEntity.setItem, undefined or a count of 0 removing it. or what an + // object holds, undefined or a count of 0 leaving it holding nothing. throws for every other kind of entity set_item(item: ItemStack | undefined): void; // a sound following it, once, for every player who sees it and is within its range play_sound(sound: Id, options?: PlayOptions): void; diff --git a/common/mod_check.ts b/common/mod_check.ts index f93d767..d698184 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -363,6 +363,14 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable; // see ItemRegistry.model model?: string; + // see ItemRegistry.entity + entity?: string; // tier and speed default to 0 and 2 tool?: Omit & Partial; places?: string; @@ -390,6 +392,7 @@ const item_schema: z.ZodType = z.object({ texture: id.optional(), data_textures: z.record(z.string(), id).optional(), model: id.optional(), + entity: id.optional(), tool: z.object({ type: z.string(), durability: z.int().min(1), @@ -429,19 +432,24 @@ const item_schema: z.ZodType = z.object({ components: json_object.optional(), }); -// a kind of entity, drawn with an entity model and one texture, or without a model as its texture facing the camera +const ENTITY_BEHAVIORS = ["animal", "monster", "scripted", "object"]; + +// a kind of entity, drawn with an entity model and one texture, or without a model as its texture facing the camera. +// an object without a model is drawn as the item it holds const entity_schema = z.object({ id, // an entity model, see EntityModelJson model: id.optional(), - texture: id, + // only an object can go without one + texture: id.optional(), // "animal" (the default) wanders around, panics when hurt and looks at players. "monster" goes after players it // sees and whoever hurts it, and despawns far from players, like minecraft's zombies. "scripted" stays where - // scripts put it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook. any other id - // is a behavior a mod's script registers + // scripts put it: no gravity, ai or health, and it isn't saved with the world, like the fishing hook. "object" lies + // around like a dropped item, holding one, without ai or health (see ItemRegistry.entity). any other id is a + // behavior a mod's script registers behavior: z.custom( - (value) => ["animal", "monster", "scripted"].includes(value as string) || id.safeParse(value).success, - 'must be "animal", "monster", "scripted" or a behavior id like "my_mod:thing"', + (value) => ENTITY_BEHAVIORS.includes(value as string) || id.safeParse(value).success, + 'must be "animal", "monster", "scripted", "object" or a behavior id like "my_mod:thing"', ).optional(), // what natural spawning counts it as, see entity_category category: z.enum(["monster", "creature"]).optional(), @@ -465,6 +473,11 @@ const entity_schema = z.object({ loot_table: loot_table_id.optional(), // what it sounds like: /hurt, /death, /step and /ambient, see ENTITY_SOUNDS sounds: sound_prefix.optional(), + // how much bigger it's drawn than its model (or its texture, or its item), 1 when not set. its box stays the same + scale: z.number().positive().optional(), +}).refine((entity) => entity.texture !== undefined || entity.behavior === "object", { + path: ["texture"], + message: "is needed unless it's an object", }); export type EntityJson = z.infer; @@ -899,6 +912,7 @@ export function item_to_json(id: string, item: ItemRegistry): ItemJson { const json: ItemJson = { id, texture: item.texture_id }; if (item.data_textures !== undefined) json.data_textures = item.data_textures; if (item.model !== undefined) json.model = item.model; + if (item.entity !== undefined) json.entity = item.entity; if (item.tool !== undefined) json.tool = item.tool; if (item.block_id !== undefined) json.places = item.block_id; if (item.max_stack !== undefined) json.max_stack = item.max_stack; @@ -929,6 +943,7 @@ function item_fields(json: ItemJson): Partial { const item: Partial = {}; if (json.data_textures !== undefined) item.data_textures = json.data_textures; if (json.model !== undefined) item.model = json.model; + if (json.entity !== undefined) item.entity = json.entity; if (json.tool !== undefined) item.tool = { tier: 0, speed: 2, ...json.tool }; if (json.places !== undefined) item.block_id = json.places; if (json.max_stack !== undefined) item.max_stack = json.max_stack; diff --git a/common/protocol.ts b/common/protocol.ts index 1458a70..3cd0519 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -12,7 +12,7 @@ export const AIR_ID = "cubi:air"; // bump when a client and server of different versions can't play together. // the server rejects a different version before the client downloads anything -export const PROTOCOL_VERSION = 30; +export const PROTOCOL_VERSION = 31; export interface PlayerInfo { id: string; @@ -132,6 +132,8 @@ export type ClientMessage = | { type: "hit_block"; x: number; y: number; z: number } // left click on an entity, by id | { type: "attack_entity"; id: string } + // right click on an entity, by id, for mods' entity_interact. it uses the held item when they don't stop it + | { type: "interact_entity"; id: string } // left click at nothing, a swing at the air. it starts the attack cooldown over, like an attack | { type: "swing" } // right click without looking at a block, for items' on_use diff --git a/docs/modding/concepts/events.md b/docs/modding/concepts/events.md index 54efe71..23bb7e2 100644 --- a/docs/modding/concepts/events.md +++ b/docs/modding/concepts/events.md @@ -42,19 +42,20 @@ showed. These events fire for **every** player's actions, since they all go thro ## The Events -| Event | Before | After | Fields | -| ---------------- | ------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------- | -| `block_break` | ✓ | ✓ | `player`, `block` (with its tile `data`), `item` held | -| `block_place` | ✓ | ✓ | `player`, `block` (`{ id, x, y, z }`), `face` clicked, `hit` where on it (0-1 each axis), `item` held | -| `block_interact` | ✓ | ✓ | `player`, `block`, `item` held. Before fires for every right click on a block, after only when a component's `on_interact` handled it | -| `chat_send` | ✓ | ✓ | `player`, `message`. Before handlers can change `message` | -| `entity_damage` | ✓ | ✓ | `entity`, `player`, `amount`, `cause`, `bypasses_invulnerability`. See below | -| `player_death` | | ✓ | `player`, `cause`. They've dropped what they carried and respawn right after | -| `player_join` | | ✓ | `player` | -| `player_leave` | | ✓ | `player` | -| `server_start` | | ✓ | none. Every mod's server phase has run | -| `tick` | | ✓ | `dt`, in seconds. 20 times a second | -| `new_day` | | ✓ | `day`. At 06:00, after every block's `on_new_day` | +| Event | Before | After | Fields | +| ----------------- | ------ | ----- | ------------------------------------------------------------------------------------------------------------------------------------------------ | +| `block_break` | ✓ | ✓ | `player`, `block` (with its tile `data`), `item` held | +| `block_place` | ✓ | ✓ | `player`, `block` (`{ id, x, y, z }`), `face` clicked, `hit` where on it (0-1 each axis), `item` held | +| `block_interact` | ✓ | ✓ | `player`, `block`, `item` held. Before fires for every right click on a block, after only when a component's `on_interact` handled it | +| `entity_interact` | ✓ | | `player`, `entity` right clicked, `item` held. Cancelling it stops the held item being used, see [Interacting](../entities/index.md#interacting) | +| `chat_send` | ✓ | ✓ | `player`, `message`. Before handlers can change `message` | +| `entity_damage` | ✓ | ✓ | `entity`, `player`, `amount`, `cause`, `bypasses_invulnerability`. See below | +| `player_death` | | ✓ | `player`, `cause`. They've dropped what they carried and respawn right after | +| `player_join` | | ✓ | `player` | +| `player_leave` | | ✓ | `player` | +| `server_start` | | ✓ | none. Every mod's server phase has run | +| `tick` | | ✓ | `dt`, in seconds. 20 times a second | +| `new_day` | | ✓ | `day`. At 06:00, after every block's `on_new_day` | `cause` is `"fall"`, `"void"`, `"starve"`, `"mob_attack"`, or whatever a mod passed to `damage(amount, cause)`. diff --git a/docs/modding/entities/index.md b/docs/modding/entities/index.md index 0d4e489..239d3d9 100644 --- a/docs/modding/entities/index.md +++ b/docs/modding/entities/index.md @@ -25,9 +25,10 @@ and players. Mods define new kinds in their `entities/` folder, and draw them wi | Field | Default | Meaning | | -------------------- | ---------- | ------------------------------------------------------------------------------------------------------ | | `id` | required | The entity's id. | -| `texture` | required | Any texture, stretched over the model's `texture_width` and `texture_height`. | +| `texture` | required | Any texture, stretched over the model's `texture_width` and `texture_height`. An object needs none. | | `model` | none | An [entity model](#entity-models). Without one it's drawn as its texture, facing the camera. | -| `behavior` | `"animal"` | `"animal"`, `"monster"`, `"scripted"`, or a [custom behavior](#custom-behaviors)'s id. | +| `behavior` | `"animal"` | `"animal"`, `"monster"`, `"scripted"`, `"object"`, or a [custom behavior](#custom-behaviors)'s id. | +| `scale` | `1` | How much bigger it's drawn than its model, texture or item. Its box stays `width` and `height`. | | `category` | see below | `"monster"` or `"creature"`, see [Natural Spawning](#natural-spawning). | | `width`, `height` | required | Its collision box in blocks, up to 16. `width` is for both x and z. Its eyes are at 85% of the height. | | `max_health` | `10` | In half hearts. | @@ -92,6 +93,49 @@ the world, so a script never finds one it doesn't know about after a restart. Th } ``` +**Objects** lie around like a dropped item, holding one: they fall, slide and float in water the same way, but nobody +picks them up by walking into them, and they never despawn or merge. They can't be hurt, don't think, don't stop blocks +being placed where they are, and are saved with the world with what they hold. Without a `model`, an object is drawn as +its item: the item's [model](../resources/models.md#entity-models-as-items) at the size it's made, times `scale`, turned +the way the object faces. + +An item lies around as an object instead of a dropped item when it names one as its +[`entity`](../items/index.md#properties), like NeoForge's `hasCustomEntity`. Every way an item ends up in the world +spawns the object holding it: thrown, dropped when its holder dies or when it doesn't fit, popped out of a broken block, +or a script's `spawn_item` or `drop_item`. Dangerous Business's scrap is one, picked up by right clicking it (see +[Interacting](#interacting)): + +```json +{ + "format_version": 1, + "entity": { + "id": "dangerous_business:scrap", + "behavior": "object", + "width": 0.7, + "height": 0.7, + "scale": 0.7 + } +} +``` + +## Interacting + +Right clicking an entity from up to 3 blocks away fires [`before.entity_interact`](../concepts/events.md#the-events), +like NeoForge's `PlayerInteractEvent.EntityInteract`. Its handlers do whatever the click does and cancel it, otherwise +the held item is used as if clicking nothing. A handler can also leave the entity be, like scrap with nowhere to go: + +```ts +ctx.events.before.entity_interact.subscribe((event) => { + if (event.entity.type !== "dangerous_business:scrap") return; + event.cancel = true; + const item = event.entity.get_item(); + const slot = [0, 1, 2, 3].find((slot) => event.player.inventory.get(slot) === undefined); + if (!item || slot === undefined) return; + event.player.inventory.set(slot, item); + event.entity.remove(); +}); +``` + ## Custom Behaviors A mob can get its goals from a script instead, like NeoForge's `registerGoals`. Its json names a behavior id, and the @@ -288,8 +332,8 @@ interface EntityRef { push(x: number, y: number, z: number): void; // adds to its velocity remove(): void; kill(cause?: string): void; // players and mobs die, anything else is removed - get_item(): ItemStack | undefined; // for an item lying around, a copy - set_item(item: ItemStack | undefined): void; // for an item lying around, undefined takes it away + get_item(): ItemStack | undefined; // for an item lying around or what an object holds, a copy + set_item(item: ItemStack | undefined): void; // undefined takes an item lying around away, an object holds nothing } ``` diff --git a/docs/modding/items/index.md b/docs/modding/items/index.md index 290ef5e..02c1fc8 100644 --- a/docs/modding/items/index.md +++ b/docs/modding/items/index.md @@ -56,6 +56,7 @@ down to 0 is gone. | `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). | +| `entity` | none | An [object](../entities/index.md#behaviors) it lies in the world as instead of a dropped item, holding the stack. | | `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). | diff --git a/mods/dangerous_business/items/air_horn.json b/mods/dangerous_business/items/air_horn.json index c1cf290..0d2d2fd 100644 --- a/mods/dangerous_business/items/air_horn.json +++ b/mods/dangerous_business/items/air_horn.json @@ -3,6 +3,8 @@ "item": { "id": "dangerous_business:air_horn", "texture": "dangerous_business:air_horn", - "model": "dangerous_business:air_horn" + "model": "dangerous_business:air_horn", + "entity": "dangerous_business:scrap", + "max_stack": 1 } } diff --git a/mods/dangerous_business/scripts/main.ts b/mods/dangerous_business/scripts/main.ts index 9cc68e1..11bab6c 100644 --- a/mods/dangerous_business/scripts/main.ts +++ b/mods/dangerous_business/scripts/main.ts @@ -4,6 +4,7 @@ import { DOOR, FACILITY_DOOR } from "./shared.ts"; import { Alea } from "@paulaboks/rng"; import { register_coilhead, register_coilhead_animator } from "./coilhead.ts"; import { register_jester, register_jester_animator } from "./jester.ts"; +import { register_scrap } from "./scrap.ts"; import { DOORWAY, MAIN_TILE, @@ -26,6 +27,7 @@ export function server(ctx: ServerContext) { register_commands(ctx); register_coilhead(ctx); register_jester(ctx); + register_scrap(ctx); } export function client(ctx: ClientContext) { diff --git a/mods/dangerous_business/scripts/scrap.ts b/mods/dangerous_business/scripts/scrap.ts new file mode 100644 index 0000000..08d8cb8 --- /dev/null +++ b/mods/dangerous_business/scripts/scrap.ts @@ -0,0 +1,22 @@ +import type { ServerContext } from "cubi/server"; + +// scrap lies around as this entity (see its items' "entity"), holding the item, and is picked up by right clicking it +export const SCRAP = "dangerous_business:scrap"; + +// the inventory slots scrap can be picked up into, the hotbar for now +const LOOT_SLOTS = [0, 1, 2, 3, 4, 5, 6, 7, 8]; + +export function register_scrap(ctx: ServerContext) { + ctx.events.before.entity_interact.subscribe((event) => { + if (event.entity.type !== SCRAP) return; + // clicking scrap never uses what's held, picked up or not + event.cancel = true; + const item = event.entity.get_item(); + const inventory = event.player.inventory; + const slot = LOOT_SLOTS.find((slot) => inventory.get(slot) === undefined); + // with no free loot slot it stays where it is + if (!item || slot === undefined) return; + inventory.set(slot, item); + event.entity.remove(); + }); +} diff --git a/server/game/entity/entity_manager.ts b/server/game/entity/entity_manager.ts index aeb0099..af65b42 100644 --- a/server/game/entity/entity_manager.ts +++ b/server/game/entity/entity_manager.ts @@ -16,7 +16,9 @@ import { sound_range, sound_to_play } from "@/common/mod_data.ts"; import type { ServerPlayer } from "../player.ts"; import type { ServerWorld } from "../world.ts"; import type { DamageSource, Entity, EntityLevel, SavedEntity } from "./entity.ts"; -import { load_entity } from "./entity_types.ts"; +import { create_entity, load_entity } from "./entity_types.ts"; +import { ObjectEntity } from "./mod_entity.ts"; +import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import { ItemEntity } from "./item_entity.ts"; import { MOBS_PATH_THROUGH } from "./pathfinding.ts"; import type { LivingEntity } from "./living_entity.ts"; @@ -180,7 +182,16 @@ export class EntityManager implements EntityLevel { this.#host.after_hurt(entity, amount, source); } - spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity { + // a cubi:item, or the entity the item lies around as instead, holding it (see ItemRegistry.entity) + spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): Entity { + const type = EverythingRegistry.get("items", stack.type_id)?.entity; + const object = type === undefined ? undefined : create_entity(this, type); + if (object instanceof ObjectEntity) { + object.item = stack; + object.set_position(x, y, z); + this.add_entity(object); + return object; + } const entity = new ItemEntity(this, stack, x, y, z, pickup_delay); this.add_entity(entity); return entity; diff --git a/server/game/entity/item_entity.ts b/server/game/entity/item_entity.ts index 8c03cda..d331b51 100644 --- a/server/game/entity/item_entity.ts +++ b/server/game/entity/item_entity.ts @@ -43,6 +43,36 @@ export interface SavedItemEntity extends SavedEntity { health?: number; } +// one tick of falling, sliding and floating like an item lying around, for an entity whose own gravity is 0 (see +// ItemEntity.gravity) +export function move_like_item(entity: Entity) { + // covered by a block placed on it, float out the top instead of being stuck inside. only inside what it bumps + // into, like minecraft's noCollision, so it can lie in a block with a hollow, like a basin + const level = entity.level; + if (!physics.box_is_free(entity, 0, 0, 0, (x, y, z) => level.collision_shape(x, y, z))) { + entity.vy = UNSTICK_SPEED; + } + + // like minecraft's ItemEntity.tick, gravity goes on its speed before it moves, not along the way like + // move_body's. the floating numbers are made for that: an item bobbing up out of the water drops straight back + // in, instead of hanging above it a tick longer and falling twice as fast + if (physics.fluid_depth(entity, (x, y, z) => level.fluid_at(x, y, z)) > FLOAT_DEPTH) { + entity.vx *= WATER_DRAG; + entity.vz *= WATER_DRAG; + if (entity.vy < FLOAT_SPEED) entity.vy += FLOAT_ACCELERATION; + } else if (!entity.no_gravity) { + entity.vy += GRAVITY * TICK_DELTA; + } + + entity.move(); + const friction = entity.on_ground ? GROUND_FRICTION : AIR_DRAG; + entity.vx *= friction; + entity.vy *= AIR_DRAG; + entity.vz *= friction; + if (Math.abs(entity.vx) < MIN_SPEED) entity.vx = 0; + if (Math.abs(entity.vz) < MIN_SPEED) entity.vz = 0; +} + // a stack of items lying in the world, like minecraft's ItemEntity. only the server simulates it, // clients draw where they're told it is export class ItemEntity extends Entity { @@ -51,7 +81,7 @@ export class ItemEntity extends Entity { override width = ITEM_SIZE; override height = ITEM_SIZE; override eye_height = ITEM_SIZE / 2; - // it falls in tick() instead, see there + // it falls in move_like_item instead, see there override gravity = 0; // ticks until a player can pick it up @@ -79,32 +109,7 @@ export class ItemEntity extends Entity { if (this.pickup_delay > 0) { this.pickup_delay -= 1; } - - // covered by a block placed on it, float out the top instead of being stuck inside. only inside what it bumps - // into, like minecraft's noCollision, so it can lie in a block with a hollow, like a basin - const level = this.level; - if (!physics.box_is_free(this, 0, 0, 0, (x, y, z) => level.collision_shape(x, y, z))) { - this.vy = UNSTICK_SPEED; - } - - // like minecraft's ItemEntity.tick, gravity goes on its speed before it moves, not along the way like - // move_body's. the floating numbers are made for that: an item bobbing up out of the water drops straight back - // in, instead of hanging above it a tick longer and falling twice as fast - if (physics.fluid_depth(this, (x, y, z) => level.fluid_at(x, y, z)) > FLOAT_DEPTH) { - this.vx *= WATER_DRAG; - this.vz *= WATER_DRAG; - if (this.vy < FLOAT_SPEED) this.vy += FLOAT_ACCELERATION; - } else if (!this.no_gravity) { - this.vy += GRAVITY * TICK_DELTA; - } - - this.move(); - const friction = this.on_ground ? GROUND_FRICTION : AIR_DRAG; - this.vx *= friction; - this.vy *= AIR_DRAG; - this.vz *= friction; - if (Math.abs(this.vx) < MIN_SPEED) this.vx = 0; - if (Math.abs(this.vz) < MIN_SPEED) this.vz = 0; + move_like_item(this); if (this.age >= DESPAWN_TICKS) { this.remove(); diff --git a/server/game/entity/mod_entity.ts b/server/game/entity/mod_entity.ts index 8210e2a..26264cf 100644 --- a/server/game/entity/mod_entity.ts +++ b/server/game/entity/mod_entity.ts @@ -2,11 +2,14 @@ // SPDX-License-Identifier: AGPL-3.0-or-later // the kinds of entity mods define in entities/.json (see EntityJson): animals that wander around, panic when hurt -// and look at players now and then, like minecraft's simpler animals, monsters that go after players, and scripted -// ones that stay where scripts put them +// and look at players now and then, like minecraft's simpler animals, monsters that go after players, scripted ones +// that stay where scripts put them, and objects that lie around holding an item +import { type ItemData, ItemStack } from "@/common/inventory.ts"; import { entity_category, type EntityJson } from "@/common/mod_data.ts"; +import type { EntityData } from "@/common/protocol.ts"; import { ATTRIBUTES, type AttributeType } from "./attributes.ts"; -import { Entity } from "./entity.ts"; +import { Entity, type SavedEntity } from "./entity.ts"; +import { move_like_item } from "./item_entity.ts"; import type { EntityFactory } from "./entity_types.ts"; import { FloatGoal, @@ -30,6 +33,9 @@ export function mod_entity_factory( if (json.behavior === "scripted") { return (level) => new ScriptedEntity(level, json); } + if (json.behavior === "object") { + return (level) => new ObjectEntity(level, json); + } const monster = json.behavior === "monster"; const behavior = json.behavior?.includes(":") ? json.behavior : undefined; @@ -110,3 +116,50 @@ class ScriptedEntity extends Entity { return false; } } + +// a thing lying around, holding an item, like neoforge's custom item entities (see ItemRegistry.entity): it falls, +// slides and floats like a dropped item, but nobody picks it up by walking into it, it never despawns or merges, and it +// can't be hurt. what happens when it's clicked is up to mods +export class ObjectEntity extends Entity { + readonly type: string; + // it falls in move_like_item instead + override gravity = 0; + item: ItemStack | undefined; + + constructor(level: Entity["level"], json: EntityJson) { + super(level); + this.type = json.id; + this.width = json.width; + this.height = json.height; + this.eye_height = json.height * 0.85; + } + + override tick() { + this.base_tick(); + if (this.removed || this.vehicle) return; + move_like_item(this); + } + + // it isn't hurt by falling either + override update_fall_distance() {} + + override synced_data(): EntityData { + const data = super.synced_data(); + if (this.item) data.item = this.item.to_synced_data(); + return data; + } + + override save_additional(saved: SavedObjectEntity) { + super.save_additional(saved); + if (this.item) saved.item = this.item.to_data(); + } + + override load_additional(saved: SavedObjectEntity) { + super.load_additional(saved); + this.item = saved.item ? ItemStack.from_data(saved.item) : undefined; + } +} + +interface SavedObjectEntity extends SavedEntity { + item?: ItemData; +} diff --git a/server/game/game_server.ts b/server/game/game_server.ts index d9228aa..aff0784 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -549,7 +549,8 @@ export class GameServer { } } - spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): ItemEntity { + // a cubi:item, or the entity the item lies around as, see EntityManager.spawn_item + spawn_item(x: number, y: number, z: number, stack: ItemStack, pickup_delay = 0): Entity { const entity = this.entities.spawn_item(x, y, z, stack, pickup_delay); this.world.dirty = true; return entity; @@ -588,6 +589,8 @@ export class GameServer { entity.vx = -Math.sin(player.yaw) * cos_pitch * speed + Math.cos(spread_angle) * spread; entity.vy = Math.sin(player.pitch) * speed + (0.1 + (Math.random() - Math.random()) * 0.1) * TICKS_PER_SECOND; entity.vz = -Math.cos(player.yaw) * cos_pitch * speed + Math.sin(spread_angle) * spread; + // one drawn with a model lands facing the way they threw it + entity.yaw = player.yaw; return entity; } @@ -1224,6 +1227,10 @@ export class GameServer { this.#attack_entity(player, message.id); } break; + case "interact_entity": + // a client that hadn't heard it's using an item yet, still clicking + if (typeof message.id === "string" && !player.using) this.#interact_entity(player, message.id); + break; case "swing": player.attack_strength_ticker = 0; break; @@ -1380,6 +1387,19 @@ export class GameServer { } // right click at nothing: eating, or the item's on_use + // a right click on an entity, like minecraft's ServerboundInteractPacket: mods' entity_interact, then the held item + // is used like on nothing, unless one of them stopped it. out of reach, or gone already, it's only that use + #interact_entity(player: ServerPlayer, id: string) { + const entity = this.entities.get_entity(id); + if (entity && !entity.removed && player.alive && this.#entity_in_reach(player, entity)) { + const player_api = this.mods.player(player); + const event = { player: player_api, entity: entity_ref(entity), item: player_api.held_item, cancel: false }; + this.mods.before.entity_interact.emit(event); + if (event.cancel) return; + } + this.#use_item(player); + } + #use_item(player: ServerPlayer): boolean { return this.#eat(player) || this.#use_item_components(player, undefined); } @@ -2639,7 +2659,7 @@ export class GameServer { } // from the eyes to the closest point of its box - #entity_in_reach(player: ServerPlayer, entity: LivingEntity) { + #entity_in_reach(player: ServerPlayer, entity: Entity) { const eye_y = player.y + player.eye_height; const half = entity.width / 2; const dx = Math.max(entity.x - half - player.x, 0, player.x - entity.x - half); diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index 3ac204c..169eebd 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -92,6 +92,7 @@ import { Mob } from "./entity/mob.ts"; import { BUILTIN_GOALS, mob_goals } from "./mob_behaviors.ts"; import { create_entity } from "./entity/entity_types.ts"; import { BLOCK_DROP_PICKUP_DELAY, ItemEntity } from "./entity/item_entity.ts"; +import { ObjectEntity } from "./entity/mod_entity.ts"; import { attribute_type, type AttributeType, MODIFIER_OPERATIONS } from "./entity/attributes.ts"; import { effect_type, EffectInstance, type EffectType } from "./entity/effects.ts"; import { biome_season } from "@/common/worldgen/biomes.ts"; @@ -192,6 +193,7 @@ export class ModRuntime { block_break: new Signal(), block_place: new Signal(), block_interact: new Signal(), + entity_interact: new Signal(), chat_send: new Signal(), entity_damage: new Signal(), }; @@ -1853,8 +1855,15 @@ export function entity_ref(entity: Entity): EntityRef { kill(cause = "script") { entity.kill(String(cause)); }, - get_item: () => entity instanceof ItemEntity ? item_copy(entity.item) : undefined, + get_item() { + const item = entity instanceof ItemEntity || entity instanceof ObjectEntity ? entity.item : undefined; + return item ? item_copy(item) : undefined; + }, set_item(item) { + if (entity instanceof ObjectEntity) { + if (!entity.removed) entity.item = item && item.count > 0 ? new_stack(item) : undefined; + return; + } if (!(entity instanceof ItemEntity)) throw new Error(`${entity.type} isn't an item lying around`); if (entity.removed) return; if (!item || item.count <= 0) entity.remove(); diff --git a/tests/dangerous_business_test.ts b/tests/dangerous_business_test.ts index aea9bf2..8dd2966 100644 --- a/tests/dangerous_business_test.ts +++ b/tests/dangerous_business_test.ts @@ -472,3 +472,21 @@ Deno.test("a jester's music box and scream play from as far as it's got, for a p set_mods_client(undefined as unknown as Client); Deno.removeSync(dir, { recursive: true }); }); + +Deno.test("dropped scrap lies around as scrap, picked up by right clicking it into a free hotbar slot", async () => { + const { t } = await setup(); + const alice = t.game.players()[0]; + const inventory = alice.inventory; + const scrap = t.game.spawn_item(0.5, 100, 2.5, new ItemStack("dangerous_business:air_horn")); + assertEquals(scrap.type, "dangerous_business:scrap"); + + // with every hotbar slot taken it stays where it is + for (let slot = 0; slot < 9; slot++) inventory.set_item(slot, new ItemStack(FLOOR)); + t.send(1, { type: "interact_entity", id: scrap.id }); + assert(!scrap.removed); + + inventory.set_item(5, undefined); + t.send(1, { type: "interact_entity", id: scrap.id }); + assert(scrap.removed); + assertEquals(inventory.get_item(5)?.type_id, "dangerous_business:air_horn"); +}); diff --git a/tests/mod_entity_test.ts b/tests/mod_entity_test.ts index 226d40e..b8e9c4b 100644 --- a/tests/mod_entity_test.ts +++ b/tests/mod_entity_test.ts @@ -150,11 +150,16 @@ Deno.test("an entity needs a texture and a size", () => { Deno.test("an entity without a model is drawn as its texture, and a scripted one has no ai", () => { assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "scripted", width: 0.25, height: 0.25 }), []); assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "flying", width: 0.25, height: 0.25 }), [ - 'behavior must be "animal", "monster", "scripted" or a behavior id like "my_mod:thing"', + 'behavior must be "animal", "monster", "scripted", "object" or a behavior id like "my_mod:thing"', ]); assertEquals(validate_entity({ id: "a:b", texture: "a:b", behavior: "a:flying", width: 0.25, height: 0.25 }), []); }); +Deno.test("only an object can go without a texture, it's drawn as the item it holds", () => { + assertEquals(validate_entity({ id: "a:b", behavior: "object", width: 0.5, height: 0.5 }), []); + assertEquals(validate_entity({ id: "a:b", width: 0.5, height: 0.5 }).length, 1); +}); + Deno.test("an entity can say it doesn't jump and how far it drops, in whole blocks", () => { const entity = { id: "a:b", texture: "a:b", width: 1, height: 1 }; assertEquals(validate_entity({ ...entity, jumps: false, max_fall: 0 }), []); diff --git a/tests/object_entity_test.ts b/tests/object_entity_test.ts new file mode 100644 index 0000000..9a135db --- /dev/null +++ b/tests/object_entity_test.ts @@ -0,0 +1,141 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// items that lie around as an entity of their own instead of a cubi:item, holding the stack, and right clicking +// entities, which mods' entity_interact handles +import { assert, assertEquals } from "@std/assert"; +import { ItemStack } from "@/common/inventory.ts"; +import { ObjectEntity } from "@/server/game/entity/mod_entity.ts"; +import { load_and_check } from "@/tools/check_mods.ts"; +import { copy_dir, stone_floor, test_game } from "./helpers.ts"; + +// logs every entity_interact, cancelling it while the player sneaks, and every use of the wrench +const SERVER_SCRIPT = ` +import type { ServerContext } from "cubi/server"; +export function server(ctx: ServerContext) { + const log = (key: string, value: unknown) => { + const all = ctx.storage.get>("log") ?? {}; + (all[key] ??= []).push(value); + ctx.storage.set("log", all); + }; + ctx.events.before.entity_interact.subscribe((event) => { + log("interact", [event.entity.type, event.entity.get_item()?.data, event.item?.id]); + if (event.player.is_sneaking()) event.cancel = true; + }); + ctx.components.register_item("testmod:wrench", { + on_use() { log("wrench", true); }, + }); +} +`; + +function test_mods(crate_entity = "testmod:crate", crate_behavior = "object") { + const dir = Deno.makeTempDirSync({ prefix: "bworld_objects_" }); + copy_dir("mods/bworld", `${dir}/bworld`); + const mod = `${dir}/testmod`; + for (const folder of ["entities", "items", "scripts"]) Deno.mkdirSync(`${mod}/${folder}`, { recursive: true }); + const write = (path: string, json: unknown) => Deno.writeTextFileSync(`${mod}/${path}`, JSON.stringify(json)); + write("manifest.json", { + format_version: 1, + id: "testmod", + name: "Test", + version: "1.0.0", + dependencies: [{ id: "bworld", version: "*" }], + main: "scripts/main.ts", + }); + write("entities/crate.json", { + format_version: 1, + entity: { id: "testmod:crate", behavior: crate_behavior, texture: "bworld:stone", width: 0.5, height: 0.5 }, + }); + write("items/crate.json", { + format_version: 1, + item: { id: "testmod:crate", texture: "bworld:stone", entity: crate_entity, max_stack: 1 }, + }); + write("items/wrench.json", { + format_version: 1, + item: { id: "testmod:wrench", texture: "bworld:stone", components: { "testmod:wrench": {} } }, + }); + Deno.writeTextFileSync(`${mod}/scripts/main.ts`, SERVER_SCRIPT); + return dir; +} + +// alice on a stone floor at y 100, looking north at a crate a block in front of her holding data +async function setup() { + const dir = test_mods(); + const t = await test_game(dir); + t.join(1, "alice"); + stone_floor(t.game); + t.send(1, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch: 0 }); + const alice = t.game.players()[0]; + const log = () => (t.game.mods.storage.testmod?.log ?? {}) as Record; + return { ...t, dir, alice, log }; +} + +const crates = (game: Awaited>["game"]) => + game.entities.all().filter((entity) => entity instanceof ObjectEntity); + +Deno.test("an item with an entity drops as that entity holding the stack, which lands and is saved with it", async () => { + const { game, send, take, alice, dir } = await setup(); + send(1, { type: "chat", text: "/give testmod:crate" }); + alice.inventory.get_item(0)!.data = { value: 42 }; + take(1); + + send(1, { type: "drop_item", menu: 0, slot: 0, all: false }); + assertEquals(game.item_entities(), [], "it isn't a cubi:item"); + const [crate] = crates(game); + assertEquals(crate.type, "testmod:crate"); + assertEquals(crate.item?.data, { value: 42 }); + const added = take(1).find((m) => m.type === "add_entity"); + assertEquals(added?.entity.data.item, { id: "testmod:crate", count: 1, data: { value: 42 } }); + + for (let i = 0; i < 60; i++) game.tick(); + assert(crate.on_ground, "it fell onto the floor"); + assertEquals(crate.y, 100); + assertEquals(crate.yaw, alice.yaw, "it lies the way it was thrown"); + + // walking into it doesn't pick it up + send(1, { type: "move", x: crate.x, y: 100, z: crate.z, yaw: 0, pitch: 0 }); + for (let i = 0; i < 5; i++) game.tick(); + assert(!crate.removed); + assertEquals(alice.inventory.get_item(0), undefined); + + const reloaded = await test_game(dir, game.save()); + const [loaded] = crates(reloaded.game); + assertEquals(loaded.item?.to_data(), { id: "testmod:crate", count: 1, data: { value: 42 } }); + Deno.removeSync(dir, { recursive: true }); +}); + +Deno.test("right clicking an entity in reach fires entity_interact, then uses the held item unless it's cancelled", async () => { + const { game, send, log, dir } = await setup(); + const crate = game.spawn_item(0.5, 100, 1.5, new ItemStack("testmod:crate")); + send(1, { type: "chat", text: "/give testmod:wrench" }); + + send(1, { type: "interact_entity", id: crate.id }); + assertEquals(log()["interact"], [["testmod:crate", undefined, "testmod:wrench"]]); + assertEquals(log()["wrench"], [true], "nothing cancelled it"); + + send(1, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch: 0, sneaking: true }); + send(1, { type: "interact_entity", id: crate.id }); + assertEquals(log()["interact"].length, 2); + assertEquals(log()["wrench"], [true], "cancelling it stops the wrench being used"); + + // out of reach only the wrench is used, like a click on nothing + send(1, { type: "move", x: 0.5, y: 100, z: 2.5, yaw: 0, pitch: 0 }); + crate.set_position(0.5, 100, -20); + send(1, { type: "interact_entity", id: crate.id }); + assertEquals(log()["interact"].length, 2); + assertEquals(log()["wrench"], [true, true]); + Deno.removeSync(dir, { recursive: true }); +}); + +Deno.test("check-mods reports an item's entity that doesn't exist or isn't an object", async () => { + const errors = async (dir: string) => { + const report = (await load_and_check(dir)).find((mod) => mod.id === "testmod")!.report; + Deno.removeSync(dir, { recursive: true }); + return report.errors.join("\n"); + }; + const missing = await errors(test_mods("testmod:nothing")); + assert(missing.includes("entity testmod:nothing doesn't exist"), missing); + const animal = await errors(test_mods("testmod:crate", "animal")); + assert(animal.includes(`entity testmod:crate has to be an "object"`), animal); + assertEquals(await errors(test_mods()), ""); +});