Add bounding boxes to models

This commit is contained in:
codemob-dev 2025-07-28 09:55:20 -04:00
parent 288ab2ebfb
commit d44ac5a833
2 changed files with 27 additions and 9 deletions

View File

@ -73,6 +73,10 @@ pub const collision = struct {
}
return true;
}
pub fn join(self: AABB, other: AABB) AABB {
return .{.min = @min(self.min, other.min), .max = @max(self.max, other.max)};
}
};
const Direction = enum(u2) {x = 0, y = 1, z = 2};
@ -81,19 +85,27 @@ pub const collision = struct {
var resultBox: ?AABB = null;
var minDistance: f64 = std.math.floatMax(f64);
if(block.collide()) {
//const model = block.mode().model(block).model();
const model = block.mode().model(block).model();
const pos = Vec3d{@floatFromInt(x), @floatFromInt(y), @floatFromInt(z)};
const blockAABB = AABB {.min = pos, .max = pos + @as(Vec3d, @splat(1.0))};
const entityAABB = AABB {.min = entityPosition - entityBoundingBoxExtent, .max = entityPosition + entityBoundingBoxExtent};
if(blockAABB.intersects(entityAABB)) {
resultBox = blockAABB;
const dotMin = vec.dot(directionVector, blockAABB.min);
const dotMax = vec.dot(directionVector, blockAABB.max);
minDistance = @min(dotMin, dotMax);
for(model.collision) |relativeBlockAABB| {
const blockAABB = AABB {.min = relativeBlockAABB.min + pos, .max = relativeBlockAABB.max + pos};
if(blockAABB.intersects(entityAABB)) {
const dotMin = vec.dot(directionVector, blockAABB.min);
const dotMax = vec.dot(directionVector, blockAABB.max);
const distance = @min(dotMin, dotMax);
if(distance < minDistance) {
resultBox = blockAABB;
minDistance = distance;
} else if(distance == minDistance) {
resultBox = resultBox.?.join(blockAABB);
}
}
}
}
return .{.box = resultBox orelse return null, .dist = minDistance};

View File

@ -11,6 +11,7 @@ const Vec2f = vec.Vec2f;
const Mat4f = vec.Mat4f;
const FaceData = main.renderer.chunk_meshing.FaceData;
const NeverFailingAllocator = main.heap.NeverFailingAllocator;
const AABB = main.game.collision.AABB;
var quadSSBO: graphics.SSBO = undefined;
@ -92,6 +93,7 @@ pub const Model = struct {
allNeighborsOccluded: bool,
noNeighborsOccluded: bool,
hasNeighborFacingQuads: bool,
collision: []AABB,
fn getFaceNeighbor(quad: *const QuadInfo) ?chunk.Neighbor {
var allZero: @Vector(3, bool) = .{true, true, true};
@ -195,6 +197,9 @@ pub const Model = struct {
self.allNeighborsOccluded = self.allNeighborsOccluded and self.isNeighborOccluded[neighbor];
self.noNeighborsOccluded = self.noNeighborsOccluded and !self.isNeighborOccluded[neighbor];
}
self.collision = main.globalAllocator.alloc(AABB, 1);
self.collision[0] = AABB {.min = @floatCast(self.min), .max = @floatCast(self.max)};
return modelIndex;
}
@ -386,6 +391,7 @@ pub const Model = struct {
main.globalAllocator.free(self.neighborFacingQuads[i]);
}
main.globalAllocator.free(self.internalQuads);
main.globalAllocator.free(self.collision);
}
pub fn getRawFaces(model: Model, quadList: *main.List(QuadInfo)) void {