Merge pull request #1065 from MihailRis/variant-based-hitboxes

variant-based hitboxes
This commit is contained in:
MihailRis 2026-10-31 17:41:55 +03:00 • committed by GitHub
commit 1492bb093e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
20 changed files with 202 additions and 104 deletions

View file

@ -112,6 +112,8 @@ Properties available for variance:
- model-name
- texture
- texture-faces
- hitbox
- hitboxes
- model-primitives (deprecated)
Variants are managed via `block.set_variant(x, y, z, index)`.
@ -142,6 +144,26 @@ In this example:
- Variant 1 = `stairs_left` (from variants[0])
- Variant 2 = `stairs_right` (from variants[1])
### Hitbox variants
A variant can override `hitbox` or `hitboxes`. Variants without them inherit the root hitboxes. Collisions, raycasts, block selection and `aabb` models use the hitboxes of the current variant.
```json
{
"model": "aabb",
"hitbox": [0.0, 0.0, 0.0, 1.0, 0.5, 1.0],
"rotation": "pipe",
"state-based": {
"bits": 1,
"variants": [
{ "hitbox": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] }
]
}
}
```
For extended blocks the variant is taken from the origin segment.
## Lighting
### *emission*

View file

@ -177,7 +177,12 @@ block.get_textures(id: int, [optional] variant_index: int = 0) -> string table
-- returns array of two vectors (arrays of 3 numbers):
-- 1. Minimum point of the hitbox
-- 2. Hitbox size
block.get_hitbox(id: int, rotation_index: int, [optional] hitbox_index: int = 0) -> {vec3, vec3}
block.get_hitbox(
id: int,
rotation_index: int,
[optional] hitbox_index: int = 0,
[optional] variant_index: int = 0
) -> {vec3, vec3}
```
## Data fields

View file

@ -113,6 +113,8 @@
- model-name
- texture
- texture-faces
- hitbox
- hitboxes
- model-primitives (устарело)
Управление состоянием производится через `block.set_variant(x, y, z, index)`.
@ -143,6 +145,26 @@
- Вариант 1 = `stairs_left` (из variants[0])
- Вариант 2 = `stairs_right` (из variants[1])
### Хитбоксы по вариантам
Вариант может переопределять `hitbox` или `hitboxes`. Варианты без них наследуют хитбоксы из корня. Коллизии, рейкасты, выделение блока и модели `aabb` используют хитбоксы текущего варианта.
```json
{
"model": "aabb",
"hitbox": [0.0, 0.0, 0.0, 1.0, 0.5, 1.0],
"rotation": "pipe",
"state-based": {
"bits": 1,
"variants": [
{ "hitbox": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0] }
]
}
}
```
Для расширенных блоков вариант берётся из сегмента-источника.
## Освещение
### Излучение - *emission*:

View file

@ -177,7 +177,13 @@ block.get_textures(id: int, [опционально] variant_index: int = 0) ->
-- 2. Размер хитбокса
-- rotation_index - индекс поворота блока
-- hitbox_index - индекс хитбокса
block.get_hitbox(id: int, rotation_index: int, [опционально] hitbox_index: int = 0) -> {vec3, vec3}
-- variant_index - индекс варианта
block.get_hitbox(
id: int,
rotation_index: int,
[опционально] hitbox_index: int = 0,
[опционально] variant_index: int = 0
) -> {vec3, vec3}
```
## Данные блоков

View file

@ -31,39 +31,50 @@ std::unique_ptr<Content> ContentBuilder::build() {
variant.culling == CullingMode::OPTIONAL;
};
auto prepareHitboxes = [&def](Variant& variant) {
if (def.rotatable) {
for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) {
auto& rotated = variant.rt.hitboxes[i];
rotated.clear();
rotated.reserve(variant.hitboxes.size());
for (AABB aabb : variant.hitboxes) {
def.rotations.variants[i].transform(aabb);
aabb.fix();
rotated.push_back(aabb);
}
}
} else {
variant.rt.hitboxes[0] = variant.hitboxes;
}
};
const float EPSILON = 0.01f;
auto isFullHitbox = [&def, EPSILON](const Variant& variant) {
return !variant.hitboxes.empty() &&
glm::i8vec3(variant.hitboxes[0].size() + EPSILON) == def.size;
};
bool fullHitboxes;
if (def.variants) {
fullHitboxes = true;
for (auto& variant : def.variants->variants) {
variant.rt.solid = isSolid(variant) || def.explictlySolid;
prepareHitboxes(variant);
fullHitboxes = fullHitboxes && isFullHitbox(variant);
}
def.defaults = def.variants->variants.at(0);
} else {
def.defaults.rt.solid = isSolid(def.defaults) || def.explictlySolid;
prepareHitboxes(def.defaults);
fullHitboxes = isFullHitbox(def.defaults);
}
def.rt.solid = def.defaults.rt.solid;
const float EPSILON = 0.01f;
def.rt.solid = def.rt.solid &&
def.obstacle &&
(glm::i8vec3(def.hitboxes[0].size() + EPSILON) == def.size);
def.rt.solid = def.defaults.rt.solid && def.obstacle && fullHitboxes;
def.rt.extended = def.size.x > 1 || def.size.y > 1 || def.size.z > 1;
if (def.material.empty()) {
defaults.at("block-material").get(def.material);
}
if (def.rotatable) {
for (uint i = 0; i < BlockRotProfile::MAX_COUNT; i++) {
def.rt.hitboxes[i].reserve(def.hitboxes.size());
for (AABB aabb : def.hitboxes) {
def.rotations.variants[i].transform(aabb);
aabb.fix();
def.rt.hitboxes[i].push_back(aabb);
}
}
} else {
def.rt.hitboxes[0] = def.hitboxes;
}
blockDefsIndices.push_back(&def);
groups->insert(def.defaults.drawGroup); // FIXME: variants
}

View file

@ -42,6 +42,21 @@ static void perform_user_block_fields(
layout = StructLayout::create(fields);
}
static AABB load_hitbox(const dv::value& box) {
if (box.size() < 6) {
throw std::runtime_error("hitbox requires 6 elements");
}
AABB aabb;
aabb.a = glm::vec3(
box[0].asNumber(), box[1].asNumber(), box[2].asNumber()
);
aabb.b = glm::vec3(
box[3].asNumber(), box[4].asNumber(), box[5].asNumber()
);
aabb.b += aabb.a;
return aabb;
}
static void load_variant(
Variant& variant, const dv::value& root, const std::string& name
) {
@ -86,6 +101,17 @@ static void load_variant(
logger.error() << "unknown culling mode: " << cullingModeName;
}
root.at("draw-group").get(variant.drawGroup);
if (auto found = root.at("hitboxes")) {
const auto& boxarr = *found;
variant.hitboxes.clear();
variant.hitboxes.reserve(boxarr.size());
for (uint i = 0; i < boxarr.size(); i++) {
variant.hitboxes.push_back(load_hitbox(boxarr[i]));
}
} else if (auto found = root.at("hitbox")) {
variant.hitboxes = {load_hitbox(*found)};
}
}
template<> void ContentUnitLoader<Block>::loadUnit(
@ -158,34 +184,6 @@ template<> void ContentUnitLoader<Block>::loadUnit(
def.rotatable = false;
}
// block hitbox AABB [x, y, z, width, height, depth]
if (auto found = root.at("hitboxes")) {
const auto& boxarr = *found;
def.hitboxes.resize(boxarr.size());
for (uint i = 0; i < boxarr.size(); i++) {
const auto& box = boxarr[i];
auto& hitboxesIndex = def.hitboxes[i];
hitboxesIndex.a = glm::vec3(
box[0].asNumber(), box[1].asNumber(), box[2].asNumber()
);
hitboxesIndex.b = glm::vec3(
box[3].asNumber(), box[4].asNumber(), box[5].asNumber()
);
hitboxesIndex.b += hitboxesIndex.a;
}
} else if (auto found = root.at("hitbox")) {
const auto& box = *found;
AABB aabb;
aabb.a = glm::vec3(
box[0].asNumber(), box[1].asNumber(), box[2].asNumber()
);
aabb.b = glm::vec3(
box[3].asNumber(), box[4].asNumber(), box[5].asNumber()
);
aabb.b += aabb.a;
def.hitboxes = {aabb};
}
// block light emission [r, g, b] where r,g,b in range [0..15]
if (auto found = root.at("emission")) {
const auto& emissionarr = *found;
@ -219,11 +217,19 @@ template<> void ContentUnitLoader<Block>::loadUnit(
);
}
// should variant modify hitbox?
if (def.defaults.model.type == BlockModelType::BLOCK &&
(def.size.x != 1 || def.size.y != 1 || def.size.z != 1)) {
def.defaults.model.type = BlockModelType::AABB;
def.hitboxes = {AABB(def.size)};
if (def.size.x != 1 || def.size.y != 1 || def.size.z != 1) {
auto applySize = [&def](Variant& variant) {
if (variant.model.type == BlockModelType::BLOCK) {
variant.model.type = BlockModelType::AABB;
variant.hitboxes = {AABB(def.size)};
}
};
applySize(def.defaults);
if (def.variants) {
for (auto& variant : def.variants->variants) {
applySize(variant);
}
}
}
// grounding behaviour

View file

@ -39,7 +39,7 @@ void corecontent::setup(Input* input, ContentBuilder& builder) {
for (uint i = 0; i < 6; i++) {
block.defaults.textureFaces[i] = "obstacle";
}
block.hitboxes = {AABB()};
block.defaults.hitboxes = {AABB()};
block.breakable = false;
ItemDef& item = builder.items.create(CORE_OBSTACLE+".item");
item.iconType = ItemIconType::BLOCK;
@ -55,7 +55,7 @@ void corecontent::setup(Input* input, ContentBuilder& builder) {
block.defaults.drawGroup = -1;
block.skyLightPassing = true;
block.lightPassing = true;
block.hitboxes = {AABB()};
block.defaults.hitboxes = {AABB()};
block.obstacle = false;
ItemDef& item = builder.items.create(CORE_STRUCT_AIR+".item");
item.iconType = ItemIconType::BLOCK;

View file

@ -70,9 +70,7 @@ void BlockWrapsRenderer::draw(BlockWrapper& wrapper, const Texture* texture) {
);
break;
case BlockModelType::AABB: {
const auto& aabb =
(def.rotatable ? def.rt.hitboxes[vox->state.rotation]
: def.hitboxes).at(0);
const auto& aabb = def.getHitboxes(vox->state).at(0);
const auto& size = aabb.size();
batch->cube(
glm::vec3(wrapper.position) + aabb.center(),
@ -121,9 +119,7 @@ void BlockWrapsRenderer::refreshWrapper(BlockWrapper& wrapper) {
wrapper.modelType = def.getModel(vox->state.userbits).type;
switch (wrapper.modelType) {
case BlockModelType::AABB: {
const auto& aabb =
(def.rotatable ? def.rt.hitboxes[vox->state.rotation]
: def.hitboxes).at(0);
const auto& aabb = def.getHitboxes(vox->state).at(0);
const auto& size = aabb.size();
wrapper.uvRegions[0].scale(size.z, size.y);
wrapper.uvRegions[1].scale(size.z, size.y);

View file

@ -46,7 +46,7 @@ std::unique_ptr<ImageData> BlocksPreview::draw(
case BlockModelType::AABB:
{
glm::vec3 hitbox {};
for (const auto& box : def.hitboxes) {
for (const auto& box : def.defaults.hitboxes) {
hitbox = glm::max(hitbox, box.size());
}
offset = glm::vec3(1, 1, 0.0f);

View file

@ -224,15 +224,16 @@ void BlocksRenderer::blockAABB(
const glm::ivec3& icoord,
const UVRegion(&texfaces)[6],
const Block* block,
ubyte rotation,
blockstate states,
bool lights,
bool ao
) {
if (block->hitboxes.empty()) {
const auto& hitboxes = block->getVariantByBits(states.userbits).hitboxes;
if (hitboxes.empty()) {
return;
}
AABB hitbox = block->hitboxes[0];
for (const auto& box : block->hitboxes) {
AABB hitbox = hitboxes[0];
for (const auto& box : hitboxes) {
hitbox.a = glm::min(hitbox.a, box.a);
hitbox.b = glm::max(hitbox.b, box.b);
}
@ -243,7 +244,7 @@ void BlocksRenderer::blockAABB(
glm::vec3 coord(icoord);
if (block->rotatable) {
auto& rotations = block->rotations;
auto& orient = rotations.variants[rotation];
auto& orient = rotations.variants[states.rotation];
X = orient.axes[0];
Y = orient.axes[1];
Z = orient.axes[2];
@ -537,7 +538,7 @@ void BlocksRenderer::render(
}
case BlockModelType::AABB: {
if (!denseRender)
blockAABB({x, y, z}, texfaces, &def, vox.state.rotation,
blockAABB({x, y, z}, texfaces, &def, vox.state,
!def.shadeless, def.ambientOcclusion && enableAO);
break;
}
@ -609,7 +610,7 @@ SortingMeshData BlocksRenderer::renderTranslucent(
{x, y, z},
texfaces,
&def,
vox.state.rotation,
vox.state,
!def.shadeless,
def.ambientOcclusion && enableAO
);

View file

@ -128,7 +128,7 @@ private:
const glm::ivec3& coord,
const UVRegion(&faces)[6],
const Block* block,
ubyte rotation,
blockstate states,
bool lights,
bool ambientOcclusion
);

View file

@ -213,7 +213,7 @@ model::Model ModelsGenerator::generate(
mesh.shading = !blockDef.shadeless;
switch (blockModel.type) {
case BlockModelType::AABB: {
glm::vec3 size = blockDef.hitboxes.at(0).size();
glm::vec3 size = variant.hitboxes.at(0).size();
float m = glm::max(size.x, glm::max(size.y, size.z));
m = glm::min(1.0f, m);
mesh.scale(size / m);

View file

@ -48,6 +48,7 @@
#include "voxels/Block.hpp"
#include "voxels/Chunk.hpp"
#include "voxels/Chunks.hpp"
#include "voxels/blocks_agent.hpp"
#include "voxels/Pathfinding.hpp"
#include "window/Window.hpp"
#include "world/Level.hpp"
@ -322,9 +323,9 @@ void WorldRenderer::renderBlockSelection() {
const glm::vec3 point = selection.hitPosition;
const glm::vec3 norm = selection.normal;
const std::vector<AABB>& hitboxes =
block.rotatable ? block.rt.hitboxes[selection.vox.state.rotation]
: block.hitboxes;
const auto& hitboxes = block.getHitboxes(
blocks_agent::hitbox_state(*player.chunks, pos, selection.vox.state)
);
lineBatch->lineWidth(2.0f);
for (auto& hitbox : hitboxes) {

View file

@ -459,7 +459,7 @@ void PlayerController::processRightClick(
blockid_t chosenBlock = def.rt.id;
if (def.obstacle) {
const auto& hitboxes = def.rt.hitboxes[state.rotation];
const auto& hitboxes = def.getHitboxes(state);
for (const AABB& blockAABB : hitboxes) {
if (level.entities->hasBlockingInside(blockAABB.translated(coord)
)) {

View file

@ -468,7 +468,10 @@ static int l_get_hitbox(lua::State* L) {
} else {
rotation = 0;
}
auto& hitbox = def->rt.hitboxes[rotation].at(hitboxIndex);
const auto& variant =
def->variants ? def->variants->variants[get_variant_index(L, *def, 4)]
: def->defaults;
auto& hitbox = variant.rt.hitboxes[rotation].at(hitboxIndex);
lua::createtable(L, 2, 0);
lua::pushvec3(L, hitbox.min());

View file

@ -156,7 +156,6 @@ void Block::cloneTo(Block& dst) {
dst.rotatable = rotatable;
dst.grounded = grounded;
dst.hidden = hidden;
dst.hitboxes = hitboxes;
dst.rotations = rotations;
dst.pickingItem = pickingItem;
dst.scriptName = scriptName;

View file

@ -10,6 +10,7 @@
#include "maths/UVRegion.hpp"
#include "maths/aabb.hpp"
#include "typedefs.hpp"
#include "voxel.hpp"
#include "util/EnumMetadata.hpp"
#include "util/stack_vector.hpp"
#include "interfaces/Serializable.hpp"
@ -182,10 +183,14 @@ struct Variant {
CullingMode culling = CullingMode::DEFAULT;
/// @brief Influences visible block sides for transparent blocks
uint8_t drawGroup = 0;
/// @brief Set of block physical hitboxes
std::vector<AABB> hitboxes {AABB()};
struct {
/// @brief is the block completely opaque for render
bool solid = true;
/// @brief set of hitboxes sets with all coord-systems precalculated
std::vector<AABB> hitboxes[BlockRotProfile::MAX_COUNT];
} rt;
};
@ -261,9 +266,6 @@ public:
/// @brief Grounding behaviour
GroundingBehaviour groundingBehaviour = GroundingBehaviour::PARTIAL;
/// @brief Set of block physical hitboxes
std::vector<AABB> hitboxes {AABB()};
/// @brief Set of available block rotations (coord-systems)
BlockRotProfile rotations = BlockRotProfile::NONE;
@ -312,9 +314,6 @@ public:
// @brief block size is greater than 1x1x1
bool extended = false;
/// @brief set of hitboxes sets with all coord-systems precalculated
std::vector<AABB> hitboxes[BlockRotProfile::MAX_COUNT];
/// @brief set of block callbacks flags
BlockFuncsSet funcsset {};
@ -359,6 +358,13 @@ public:
return getVariantByBits(bits).model;
}
/// @brief Get precalculated hitboxes of the variant and rotation
/// by the block state
const std::vector<AABB>& getHitboxes(blockstate state) const {
return getVariantByBits(state.userbits)
.rt.hitboxes[rotatable ? state.rotation : 0];
}
static bool isReservedBlockField(std::string_view view);
};

View file

@ -70,12 +70,14 @@ const AABB* Chunks::isObstacleAt(float x, float y, float z) const {
return nullptr;
}
glm::ivec3 offset {};
if (v->state.segment) {
blockstate state = v->state;
if (state.segment) {
glm::ivec3 point(ix, iy, iz);
offset = seekOrigin(point, def, v->state) - point;
auto origin = seekOrigin(point, def, state);
offset = origin - point;
state = blocks_agent::hitbox_state(*this, origin, state);
}
const auto& boxes =
def.rotatable ? def.rt.hitboxes[v->state.rotation] : def.hitboxes;
const auto& boxes = def.getHitboxes(state);
for (const auto& hitbox : boxes) {
if (hitbox.contains(
{x - ix - offset.x, y - iy - offset.y, z - iz - offset.z}
@ -262,18 +264,18 @@ glm::vec3 Chunks::rayCastToObstacle(
const auto& def = indices.blocks.require(voxel->id);
if (def.obstacle) {
if (!def.rt.solid) {
const std::vector<AABB>& hitboxes =
def.rt.hitboxes[voxel->state.rotation];
scalar_t distance;
glm::ivec3 norm;
Ray ray(start, dir);
glm::ivec3 offset {};
if (voxel->state.segment) {
offset = seekOrigin({ix, iy, iz}, def, voxel->state) -
glm::ivec3(ix, iy, iz);
blockstate state = voxel->state;
if (state.segment) {
auto origin = seekOrigin({ix, iy, iz}, def, state);
offset = origin - glm::ivec3(ix, iy, iz);
state = blocks_agent::hitbox_state(*this, origin, state);
}
const auto& hitboxes = def.getHitboxes(state);
for (const auto& box : hitboxes) {
// norm is dummy now, can be inefficient

View file

@ -275,19 +275,19 @@ static inline voxel* raycast_blocks(
iend = {ix, iy, iz};
if (!def.rt.solid) {
const std::vector<AABB>& hitboxes =
def.rotatable ? def.rt.hitboxes[voxel->state.rotation]
: def.hitboxes;
scalar_t distance = maxDist;
Ray ray(start, dir);
bool hit = false;
glm::vec3 offset {};
if (voxel->state.segment) {
offset = seek_origin(chunks, iend, def, voxel->state) - iend;
blockstate state = voxel->state;
if (state.segment) {
auto origin = seek_origin(chunks, iend, def, state);
offset = origin - iend;
state = hitbox_state(chunks, origin, state);
}
const auto& hitboxes = def.getHitboxes(state);
for (auto box : hitboxes) {
box.a += offset;

View file

@ -264,6 +264,22 @@ inline glm::ivec3 seek_origin(
}
}
/// @brief Get block state selecting the variant hitboxes.
/// Variant bits of an extended block are stored in its origin segment
/// @param origin extended block origin position
/// @param state state of the checked segment
template <class Storage>
inline blockstate hitbox_state(
Storage& chunks, const glm::ivec3& origin, blockstate state
) {
if (state.segment) {
if (auto* voxel = get(chunks, origin.x, origin.y, origin.z)) {
state.userbits = voxel->state.userbits;
}
}
return state;
}
/// @brief Check blocks replaceability with specified block
/// @tparam Storage chunks storage class
/// @param chunks chunks storage
@ -490,12 +506,14 @@ inline std::optional<AABB> is_obstacle_at(
return std::nullopt;
}
glm::ivec3 offset {};
if (v->state.segment) {
blockstate state = v->state;
if (state.segment) {
glm::ivec3 point(ix, iy, iz);
offset = seek_origin(chunks, point, def, v->state) - point;
auto origin = seek_origin(chunks, point, def, state);
offset = origin - point;
state = hitbox_state(chunks, origin, state);
}
const auto& boxes =
def.rotatable ? def.rt.hitboxes[v->state.rotation] : def.hitboxes;
const auto& boxes = def.getHitboxes(state);
for (const auto& hitbox : boxes) {
if (hitbox.intersects(aabb - glm::ivec3(ix, iy, iz))) {