Add some more shitcoding to MapGen

This commit is contained in:
2025-10-12 17:40:06 +07:00
parent ca56b703e3
commit cf88ccf67f
3 changed files with 476 additions and 426 deletions

View File

@@ -10,20 +10,6 @@ local mathRound, mathHuge
= math.round, math.huge = math.round, math.huge
-- --- MapGen default noises --- -- --- MapGen default noises ---
---@type ValueNoise
local oceanNoise
---@type NoiseParams
local oceanNoiseParams = {
offset = -30,
scale = 10,
spread = vector.new(100, 100, 100),
seed = 47,
octaves = 8,
persistence = 0.4,
lacunarity = 2,
}
---@type ValueNoise ---@type ValueNoise
local rocksNoise local rocksNoise
@@ -37,58 +23,27 @@ local rocksNoiseParams ={
persistence = 0.5, persistence = 0.5,
lacunarity = 4, lacunarity = 4,
} }
---DEBUG NOISES
--- TODO удалить, после реализации климата от регионов
---@type ValueNoise
local humidityNoise
---@type NoiseParams
humidityNoiseParams = {
offset = 50,
scale = 25,
spread = {x = 10, y = 10, z = 10},
seed = 47,
octaves = 2,
persistence = 0.6,
lacunarity = 2,
}
---@type ValueNoise
local tempNoise
---@type NoiseParams
tempNoiseParams = {
offset = 50,
scale = 25,
spread = {x = 10, y = 10, z = 10},
seed = 12,
octaves = 2,
persistence = 0.6,
lacunarity = 2,
}
-- --- End of default noises --- -- --- End of default noises ---
---@class MapGen ---@class MapGen
---@field layersByName table ---@field layersByName table
---@field layersList table ---@field layersList table
---@field biomesList table ---@field biomesList table
---@field biomesDiagram table ---@field biomesDiagram table
---@field multinoiseInitialized boolean Is the fractal noise of the regions initialized? This is necessary for a one-time noise initialization. ---@field isMultinoiseInitialized boolean Is the fractal noise of the regions initialized? This is necessary for a one-time noise initialization.
---@field isRunning boolean A static field that guarantees that only one instance of the `MapGen` class will work. ---@field isRunning boolean A static field that guarantees that only one instance of the `MapGen` class will work.
---@field nodeIDs table<string, string> ---@field nodeIDs table<string, number>
local MapGen = { local MapGen = {
layersByName = {}, layersByName = {},
layersList = {}, layersList = {},
biomesList = {}, biomesList = {},
biomesDiagram = {}, biomesDiagram = {},
multinoiseInitialized = false, isMultinoiseInitialized = false,
isRunning = false, isRunning = false,
} }
---@param nodeIDs table<string, string> ---@param nodeIDs table<string, number>
---@return MapGen ---@return MapGen
function MapGen:new(nodeIDs) function MapGen:new(nodeIDs)
---@type MapGen ---@type MapGen
@@ -99,23 +54,13 @@ function MapGen:new(nodeIDs)
return instance return instance
end end
---Determines which layer a node belongs to based on its height coordinate.
---@param yPos number
---@return MapGen.Layer?
function MapGen:getLayerByHeight(yPos) function MapGen:getLayerByHeight(yPos)
--- TODO: возможно здесь получится сделать более оптимизированный алгоритм for _, layer in ipairs(self.layersList) do
--- учитывая тот факт, что эта функция вызывается для каждой ноды в on_generated
--- и может быть даже не один раз
--- Можно подумать над тем, чтобы использовать сортированный список
---@param layer MapGen.Layer
for _, layer in ipairs(self.layersList) do
if yPos >= layer.minY and yPos <= layer.maxY then if yPos >= layer.minY and yPos <= layer.maxY then
return layer return layer
end end
end end
return nil
end end
---Mark the world area between two heights as a `MapGen.Layer`. ---Mark the world area between two heights as a `MapGen.Layer`.
@@ -126,7 +71,7 @@ end
---@param maxY number ---@param maxY number
function MapGen:RegisterLayer(name, minY, maxY) function MapGen:RegisterLayer(name, minY, maxY)
---Checking if layers overlap ---Checking if layers overlap
if self:getLayerByHeight(minY) ~= nil and self:getLayerByHeight(maxY) ~= nil then if self:getLayerByHeight(minY) ~= nil or self:getLayerByHeight(maxY) ~= nil then
error('Registered layers must not overlap!') error('Registered layers must not overlap!')
end end
@@ -168,17 +113,33 @@ end
---Initialize region noise. This should be called after the map object is loaded. ---Initialize region noise. This should be called after the map object is loaded.
function MapGen:initRegionsMultinoise() function MapGen:initRegionsMultinoise()
---@param layer MapGen.Layer -- Generate rocks noise once
for _, layer in ipairs(self.layersList) do rocksNoise = core.get_value_noise(rocksNoiseParams)
for _, layer in ipairs(self.layersList) do
print("INIT DEFAULT NOISES")
layer.defaultRegion:initMultinoise()
---@param region MapGen.Region
for _, region in ipairs(layer.regionsList) do for _, region in ipairs(layer.regionsList) do
region:initMultinoise() region:initMultinoise()
end end
end end
self.isMultinoiseInitialized = true
end
self.multinoiseInitialized = true -- Precompute noise for entire chunk
local function precomputeNoiseForChunk(noise, minPos, maxPos)
local noiseMap = {}
local index = 1
for z = minPos.z, maxPos.z do
for y = minPos.y, maxPos.y do
for x = minPos.x, maxPos.x do
noiseMap[index] = mathRound(noise:get_3d(vector.new(x, y, z)))
index = index + 1
end
end
end
return noiseMap
end end
---@param name string ---@param name string
@@ -192,6 +153,13 @@ function MapGen:RegisterBiome(name, tempPoint, humidityPoint, groundNodes, soilH
table.insert(self.biomesList, biome) table.insert(self.biomesList, biome)
end end
function MapGen:precomputeNodeIDs()
for _, biome in ipairs(self.biomesList) do
biome.groundNodes.turf = self.nodeIDs[biome.groundNodes.turf] or biome.groundNodes.turf
biome.groundNodes.soil = self.nodeIDs[biome.groundNodes.soil] or biome.groundNodes.soil
end
end
function MapGen:initBiomesDiagram() function MapGen:initBiomesDiagram()
local diagram = self.biomesDiagram local diagram = self.biomesDiagram
@@ -217,17 +185,17 @@ function MapGen:initBiomesDiagram()
end end
end end
local function generateSoil(biome, data, index, x, y, z) local function generateSoil(biome, data, index, pos)
data[index] = core.get_content_id(biome.groundNodes.turf) -- TODO: убрать тут get_content_id(), переместить его куда-то "выше" data[index] = biome.groundNodes.turf
end end
local function generateRock(ids, data, index, x, y, z) local function generateRock(ids, data, index, pos)
if rocksNoise == nil then if rocksNoise == nil then
rocksNoise = core.get_value_noise(rocksNoiseParams) rocksNoise = core.get_value_noise(rocksNoiseParams)
end end
local noiseRocksValue = mathRound(rocksNoise:get_3d({x = x, y = y, z = z})) local noiseRocksValue = mathRound(rocksNoise:get_3d(pos))
if noiseRocksValue == 1 then if noiseRocksValue == 1 then
data[index] = ids.malachite data[index] = ids.malachite
elseif noiseRocksValue == 2 then elseif noiseRocksValue == 2 then
@@ -247,108 +215,160 @@ local function generateRock(ids, data, index, x, y, z)
end end
end end
local function generateNode(mapGenerator, hight, temp, humidity, data, index, x, y, z) function MapGen:generateNode(self, hight, temp, humidity, data, index, pos)
local ids = mapGenerator.nodeIDs local ids = self.nodeIDs
local biome = mapGenerator.biomesDiagram[temp][humidity] local biome = self.biomesDiagram[temp][humidity]
if y > hight and y > 0 then if pos.y > hight and pos.y > 0 then
data[index] = ids.air data[index] = ids.air
elseif y == hight and y > 0 then elseif pos.y == hight and pos.y > 0 then
generateSoil(biome, data, index, x, y, z) generateSoil(biome, data, index, pos)
elseif y < hight then elseif pos.y < hight then
generateRock(ids, data, index, x, y, z) generateRock(ids, data, index, pos)
else else
data[index] = ids.water data[index] = ids.water
end end
end end
---@param mapGenerator MapGen
local function generatorHandler3D(mapGenerator, data, index, x, y, z)
local layer = mapGenerator:getLayerByHeight(y)
if layer == nil then
data[index] = mapGenerator.nodeIDs.air
return
end
-- Initialize base noises if needed -- КАРОЧИ. Надо оптимизировать вот это говно. Оно срабатывает для каждого блока и поэтому все так лагаетю
if oceanNoise == nil then oceanNoise = core.get_value_noise(oceanNoiseParams) end function MapGen:generateVoxelOptimized(data, index, pos, layer, rocksNoiseMap, area, minPos, maxPos)
if tempNoise == nil then tempNoise = core.get_value_noise(tempNoiseParams) end -- Fast region lookup with spatial partitioning
if humidityNoise == nil then humidityNoise = core.get_value_noise(humidityNoiseParams) end local region = layer:getRegionByPos(pos)
-- Base values (outside any region) -- Get base values from default region
local baseHeight = oceanNoise:get_3d({x = x, y = y, z = z}) local defaultRegion = layer:getDefaultRegion()
local baseTemp = tempNoise:get_3d({x = x, y = y, z = z}) local defaultNoises = defaultRegion:getMultinoise()
local baseHumidity = humidityNoise:get_3d({x = x, y = y, z = z})
local baseHeight = defaultNoises.landscapeNoise:get_3d(pos)
local baseTemp = defaultNoises.tempNoise:get_3d(pos)
local baseHumidity = defaultNoises.humidityNoise:get_3d(pos)
local finalHeight = baseHeight local finalHeight = baseHeight
local finalTemp = baseTemp local finalTemp = baseTemp
local finalHumidity = baseHumidity local finalHumidity = baseHumidity
local region = layer:getRegionByPos(x, y, z) -- Apply region-specific noises if needed
local polyhedron = region:getPolyhedron() if region ~= defaultRegion then
local distance = polyhedron:distanceToSurface(vector.new(x, y, z)) local polyhedron = region:getPolyhedron()
local bufferZone = region:getBufferZone() local distance = polyhedron:distanceToSurface(pos)
local bufferZone = region:getBufferZone()
if distance <= bufferZone.thickness then if distance <= bufferZone.thickness then
local regionNoises = region:getMultinoise() local regionNoises = region:getMultinoise()
local blendFactor = InterpolationPresets[region:getInterpolationPreset()](distance, bufferZone.thickness) local blendFactor = InterpolationPresets[region:getInterpolationPreset()](distance, bufferZone.thickness)
-- 3D noise interpolation if regionNoises.landscapeNoise then
if regionNoises.landscapeNoise then local regionHeight = regionNoises.landscapeNoise:get_3d(pos)
local regionHeight = regionNoises.landscapeNoise:get_3d({x = x, y = y, z = z}) finalHeight = baseHeight + (regionHeight - baseHeight) * blendFactor
finalHeight = baseHeight + (regionHeight - baseHeight) * blendFactor end
end
if regionNoises.tempNoise then if regionNoises.tempNoise then
local regionTemp = regionNoises.tempNoise:get_3d({x = x, y = y, z = z}) local regionTemp = regionNoises.tempNoise:get_3d(pos)
finalTemp = baseTemp + (regionTemp - baseTemp) * blendFactor finalTemp = baseTemp + (regionTemp - baseTemp) * blendFactor
end end
if regionNoises.humidityNoise then if regionNoises.humidityNoise then
local regionHumidity = regionNoises.humidityNoise:get_3d({x = x, y = y, z = z}) local regionHumidity = regionNoises.humidityNoise:get_3d(pos)
finalHumidity = baseHumidity + (regionHumidity - baseHumidity) * blendFactor finalHumidity = baseHumidity + (regionHumidity - baseHumidity) * blendFactor
end
end end
end end
generateNode(mapGenerator, mathRound(finalHeight), mathRound(finalTemp), -- Generate the actual node
mathRound(finalHumidity), data, index, x, y, z) self:generateNodeOptimized(mathRound(finalHeight), mathRound(finalTemp),
mathRound(finalHumidity), data, index, pos, rocksNoiseMap, minPos, maxPos)
end
function MapGen:generateNodeOptimized(height, temp, humidity, data, index, pos, rocksNoiseMap, minPos, maxPos)
local ids = self.nodeIDs
local biome = self.biomesDiagram[temp][humidity]
if pos.y > height and pos.y > 0 then
data[index] = ids.air
elseif pos.y == height and pos.y > 0 then
data[index] = biome.groundNodes.turf
elseif pos.y < height then
-- Calculate index without creating vectors
local noiseIndex = ((pos.z - minPos.z) * (maxPos.y - minPos.y + 1) * (maxPos.x - minPos.x + 1) +
(pos.y - minPos.y) * (maxPos.x - minPos.x + 1) +
(pos.x - minPos.x)) + 1
local noiseValue = rocksNoiseMap[noiseIndex]
-- Use lookup table for rock types
local rockTypes = {
[1] = ids.malachite, [2] = ids.hapcoryte, [3] = ids.iyellite,
[4] = ids.sylite, [5] = ids.tauitite, [6] = ids.falmyte,
[7] = ids.burcite, [8] = ids.felhor
}
data[index] = rockTypes[noiseValue] or ids.stone
else
data[index] = ids.water
end
end end
---@param minPos table ---@param minPos table
---@param maxPos table ---@param maxPos table
---@param blockseed number ---@param blockseed number
function MapGen:onMapGenerated(minPos, maxPos, blockseed) function MapGen:onMapGenerated(minPos, maxPos, blockseed)
-- We obtain a generation area for further manipulations print("Stage 1: entering loop")
local voxelManip, eMin, eMax = core.get_mapgen_object("voxelmanip") local voxelManip, eMin, eMax = core.get_mapgen_object("voxelmanip")
if not self.multinoiseInitialized then
self:initRegionsMultinoise()
end
local data = voxelManip:get_data() local data = voxelManip:get_data()
-- local param2_data = voxelManip:get_param2_data() -- local param2_data = voxelManip:get_param2_data()
local area = VoxelArea:new({MinEdge = eMin, MaxEdge = eMax}) local area = VoxelArea:new({MinEdge = eMin, MaxEdge = eMax})
-- Initial generation: landscape
for z = minPos.z, maxPos.z do
for y = minPos.y, maxPos.y do
local index = area:index(minPos.x, y, z)
for x = minPos.x, maxPos.x do print("Stage 2: generating initial landscape")
generatorHandler3D(self, data, index, x, y, z)
index = index + 1 -- Cache frequently accessed values
local nodeIDs = self.nodeIDs
local biomesDiagram = self.biomesDiagram
-- Precompute rocks noise for entire chunk
local rocksNoiseMap = precomputeNoiseForChunk(rocksNoise, minPos, maxPos)
local vec = vector.zero()
local areaIndex = area.index
-- Process by layers to minimize context switching
local a, b, c, d = 0, 0, 0, 0
for _, layer in ipairs(self.layersList) do
a = a+1
b, c, d = 0, 0, 0
local layerMinY = math.max(minPos.y, layer.minY)
local layerMaxY = math.min(maxPos.y, layer.maxY)
if layerMinY <= layerMaxY then
for z = minPos.z, maxPos.z do
b = b+1
c, d = 0, 0
vec.z = z
for y = layerMinY, layerMaxY do
c = c+1
d = 0
vec.y = y
local index = areaIndex(area, minPos.x, y, z)
for x = minPos.x, maxPos.x do
d = d+1
vec.x = x
self:generateVoxelOptimized(data, index, vec, layer, rocksNoiseMap, area, minPos, maxPos)
index = index + 1
print(a..":"..b..":"..c..":"..d)
end
end
end
end end
end end
end
-- We make changes back to LVM and recalculate light & liquids print("Stage 3: applying changes")
voxelManip:set_data(data) voxelManip:set_data(data)
-- voxelManip:set_param2_data(param2_data) -- voxelManip:set_param2_data(param2_data)
voxelManip:update_liquids() voxelManip:update_liquids()
voxelManip:calc_lighting() voxelManip:calc_lighting()
voxelManip:write_to_map() voxelManip:write_to_map()
end end
@@ -360,12 +380,18 @@ function MapGen:run()
error('Only one instance of a `MapGen` class can be running.') error('Only one instance of a `MapGen` class can be running.')
end end
-- Initialize default systems
self:precomputeNodeIDs()
self:initBiomesDiagram()
core.register_on_generated(function(...) core.register_on_generated(function(...)
if not self.isMultinoiseInitialized then
self:initRegionsMultinoise()
end
self:onMapGenerated(...) self:onMapGenerated(...)
end) end)
self:initBiomesDiagram()
MapGen.isRunning = true MapGen.isRunning = true
end end

View File

@@ -24,25 +24,28 @@ end
---@param bufferZone MapGen.Region.BufferZone ---@param bufferZone MapGen.Region.BufferZone
---@return MapGen.Region ---@return MapGen.Region
function Region:new(polyhedron, multinoiseParams, bufferZone) function Region:new(polyhedron, multinoiseParams, bufferZone)
local _polyhedron = polyhedron local _polyhedron = polyhedron
local _multinoiseParams = multinoiseParams local _multinoiseParams = multinoiseParams
local _bufferZone = bufferZone local _bufferZone = bufferZone
local _interpolationPreset = bufferZone.preset or "linear" local _interpolationPreset = bufferZone.preset or "linear"
local _multinoise = {} local _multinoise = {}
local instance = setmetatable({}, {__index = self}) local instance = setmetatable({}, {__index = self})
function instance:getPolyhedron() return _polyhedron end function instance:getPolyhedron() return _polyhedron end
function instance:getMultinoiseParams() return _multinoiseParams end function instance:getMultinoiseParams() return _multinoiseParams end
function instance:getMultinoise() return _multinoise end function instance:getMultinoise() return _multinoise end
function instance:getBufferZone() return _bufferZone end function instance:getBufferZone() return _bufferZone end
function instance:getInterpolationPreset() return _interpolationPreset end function instance:getInterpolationPreset() return _interpolationPreset end
function instance:initMultinoise() function instance:initMultinoise()
_multinoise = multinoiseParamsToMultinoise(_multinoiseParams) print("WTF:::")
end print(type(_multinoise))
print(dump(_multinoise))
_multinoise = multinoiseParamsToMultinoise(_multinoiseParams)
end
return instance return instance
end end
return Region return Region

View File

@@ -4,73 +4,100 @@
---@field boundingBox {min: vector, max: vector} ---@field boundingBox {min: vector, max: vector}
local Polyhedron = {} local Polyhedron = {}
local mathMin, mathMax, mathHuge, mathSqrt, mathAbs local mathMin, mathMax, mathHuge, mathAbs
= math.min, math.max, math.huge, math.sqrt, math.abs = math.min, math.max, math.huge, math.abs
---Creates a new Polyhedron instance ---Creates a new Polyhedron instance
---@param vertices vector[] Array of 3D vertices that define the polyhedron ---@param vertices vector[] Array of 3D vertices that define the polyhedron
---@param faces integer[][] Array of faces, where each face is an array of vertex indices ---@param faces integer[][] Array of faces, where each face is an array of vertex indices
---@return Polyhedron ---@return Polyhedron
function Polyhedron:new(vertices, faces) function Polyhedron:new(vertices, faces)
local instance = setmetatable({ local instance = setmetatable({
vertices = vertices, vertices = vertices,
faces = faces, faces = faces,
boundingBox = self:calculateBoundingBox(vertices) boundingBox = self:calculateBoundingBox(vertices)
}, {__index = self}) }, {__index = self})
return instance
-- Precompute face data
instance.faceData = {}
for i, face in ipairs(faces) do
instance.faceData[i] = {
plane = instance:computePlane(face),
normal = instance:computeFaceNormal(face),
edges = instance:computeFaceEdges(face)
}
end
return instance
end
function Polyhedron:computeFaceEdges(face)
local edges = {}
for i = 1, #face do
local j = (i % #face) + 1
edges[i] = {face[i], face[j]}
end
return edges
end end
---Calculates the axis-aligned bounding box for the polyhedron ---Calculates the axis-aligned bounding box for the polyhedron
---@param vertices vector[] Array of vertices to compute bounds for ---@param vertices vector[] Array of vertices to compute bounds for
---@return {min: vector, max: vector} Bounding box with min and max corners ---@return {min: vector, max: vector} Bounding box with min and max corners
function Polyhedron:calculateBoundingBox(vertices) function Polyhedron:calculateBoundingBox(vertices)
local min = vector.new(mathHuge, mathHuge, mathHuge) local min = vector.new(mathHuge, mathHuge, mathHuge)
local max = vector.new(-mathHuge, -mathHuge, -mathHuge) local max = vector.new(-mathHuge, -mathHuge, -mathHuge)
for _, vertex in ipairs(vertices) do for _, vertex in ipairs(vertices) do
min.x = mathMin(min.x, vertex.x) min.x = mathMin(min.x, vertex.x)
min.y = mathMin(min.y, vertex.y) min.y = mathMin(min.y, vertex.y)
min.z = mathMin(min.z, vertex.z) min.z = mathMin(min.z, vertex.z)
max.x = mathMax(max.x, vertex.x) max.x = mathMax(max.x, vertex.x)
max.y = mathMax(max.y, vertex.y) max.y = mathMax(max.y, vertex.y)
max.z = mathMax(max.z, vertex.z) max.z = mathMax(max.z, vertex.z)
end end
return {min = min, max = max} return {min = min, max = max}
end end
---Computes the normal vector for a face using Newell's method ---Computes the normal vector for a face using Newell's method
---@param face integer[] Array of vertex indices forming the face ---@param face integer[] Array of vertex indices forming the face
---@return vector Normalized normal vector for the face ---@return vector Normalized normal vector for the face
function Polyhedron:computeFaceNormal(face) function Polyhedron:computeFaceNormal(face)
if #face < 3 then if #face < 3 then
error("Face must have at least 3 vertices") error("Face must have at least 3 vertices")
end end
-- Use Newell's method for more robust normal calculation with non-convex polygons local normal = vector.zero()
local normal = vector.new(0, 0, 0)
for i = 1, #face do for i = 1, #face do
local j = (i % #face) + 1 local j = (i % #face) + 1
local current = self.vertices[face[i]] local current = self.vertices[face[i]]
local next = self.vertices[face[j]] local next_vert = self.vertices[face[j]]
normal.x = normal.x + (current.y - next.y) * (current.z + next.z) -- Newell's method components
normal.y = normal.y + (current.z - next.z) * (current.x + next.x) normal.x = normal.x + (current.y - next_vert.y) * (current.z + next_vert.z)
normal.z = normal.z + (current.x - next.x) * (current.y + next.y) normal.y = normal.y + (current.z - next_vert.z) * (current.x + next_vert.x)
end normal.z = normal.z + (current.x - next_vert.x) * (current.y + next_vert.y)
end
return normal:normalize() -- Check for zero normal (degenerate face)
local magnitude = vector.length(normal)
if magnitude == 0 then
return vector.zero() -- Or handle degenerate case appropriately
end
-- Normalize the normal vector
return vector.normalize(normal)
end end
---Computes the plane equation for a face ---Computes the plane equation for a face
---@param face integer[] Array of vertex indices forming the face ---@param face integer[] Array of vertex indices forming the face
---@return {normal: vector, point: vector, d: number} Plane equation in form: normal·x + d = 0 ---@return {normal: vector, point: vector, d: number} Plane equation in form: normal·x + d = 0
function Polyhedron:computePlane(face) function Polyhedron:computePlane(face)
local normal = self:computeFaceNormal(face) local normal = self:computeFaceNormal(face)
local point = self.vertices[face[1]] local point = self.vertices[face[1]]
local d = -normal:dot(point) local d = -normal:dot(point)
return {normal = normal, point = point, d = d} return {normal = normal, point = point, d = d}
end end
---Finds the intersection point between a ray and a plane ---Finds the intersection point between a ray and a plane
@@ -79,21 +106,21 @@ end
---@param plane {normal: vector, point: vector, d: number} Plane equation ---@param plane {normal: vector, point: vector, d: number} Plane equation
---@return vector|nil Intersection point, or nil if no intersection ---@return vector|nil Intersection point, or nil if no intersection
function Polyhedron:rayPlaneIntersection(rayOrigin, rayDir, plane) function Polyhedron:rayPlaneIntersection(rayOrigin, rayDir, plane)
local denom = plane.normal:dot(rayDir) local denom = plane.normal:dot(rayDir)
-- Ray is parallel to plane -- Ray is parallel to plane
if mathAbs(denom) < 1e-6 then if mathAbs(denom) < 1e-6 then
return nil return nil
end end
local t = (-plane.normal:dot(rayOrigin) - plane.d) / denom local t = (-plane.normal:dot(rayOrigin) - plane.d) / denom
-- Intersection is behind ray origin -- Intersection is behind ray origin
if t < 0 then if t < 0 then
return nil return nil
end end
return rayOrigin + rayDir * t return rayOrigin + rayDir * t
end end
---Checks if a 3D point lies within a face (convex or non-convex) ---Checks if a 3D point lies within a face (convex or non-convex)
@@ -101,34 +128,34 @@ end
---@param face integer[] Array of vertex indices forming the face ---@param face integer[] Array of vertex indices forming the face
---@return boolean True if point is inside the face, false otherwise ---@return boolean True if point is inside the face, false otherwise
function Polyhedron:pointInFace(point, face) function Polyhedron:pointInFace(point, face)
if #face < 3 then if #face < 3 then
return false return false
end end
-- Project the face and point to 2D using the face's plane -- Project the face and point to 2D using the face's plane
local plane = self:computePlane(face) local plane = self:computePlane(face)
-- Create a 2D coordinate system on the plane -- Create a 2D coordinate system on the plane
local uAxis, vAxis = self:createPlaneBasis(plane.normal) local uAxis, vAxis = self:createPlaneBasis(plane.normal)
-- Project all vertices to 2D -- Project all vertices to 2D
local vertices2D = {} local vertices2D = {}
for _, vertexIndex in ipairs(face) do for _, vertexIndex in ipairs(face) do
local vertex = self.vertices[vertexIndex] local vertex = self.vertices[vertexIndex]
local vecToVertex = vertex - plane.point local vecToVertex = vertex - plane.point
local u = vecToVertex:dot(uAxis) local u = vecToVertex:dot(uAxis)
local v = vecToVertex:dot(vAxis) local v = vecToVertex:dot(vAxis)
table.insert(vertices2D, {u, v}) table.insert(vertices2D, {u, v})
end end
-- Project the point to 2D -- Project the point to 2D
local vecToPoint = point - plane.point local vecToPoint = point - plane.point
local pointU = vecToPoint:dot(uAxis) local pointU = vecToPoint:dot(uAxis)
local pointV = vecToPoint:dot(vAxis) local pointV = vecToPoint:dot(vAxis)
local point2D = {pointU, pointV} local point2D = {pointU, pointV}
-- Use winding number algorithm for point-in-polygon test (works with non-convex polygons) -- Use winding number algorithm for point-in-polygon test (works with non-convex polygons)
return self:pointInPolygon2D(point2D, vertices2D) return self:pointInPolygon2D(point2D, vertices2D)
end end
---Creates an orthonormal basis for a plane defined by its normal ---Creates an orthonormal basis for a plane defined by its normal
@@ -136,18 +163,18 @@ end
---@return vector uAxis First basis vector ---@return vector uAxis First basis vector
---@return vector vAxis Second basis vector ---@return vector vAxis Second basis vector
function Polyhedron:createPlaneBasis(normal) function Polyhedron:createPlaneBasis(normal)
-- Choose an arbitrary vector not parallel to normal -- Choose an arbitrary vector not parallel to normal
local temp local temp
if mathAbs(normal.x) > mathAbs(normal.y) then if mathAbs(normal.x) > mathAbs(normal.y) then
temp = vector.new(0, 1, 0) temp = vector.new(0, 1, 0)
else else
temp = vector.new(1, 0, 0) temp = vector.new(1, 0, 0)
end end
local uAxis = normal:cross(temp):normalize() local uAxis = normal:cross(temp):normalize()
local vAxis = normal:cross(uAxis):normalize() local vAxis = normal:cross(uAxis):normalize()
return uAxis, vAxis return uAxis, vAxis
end end
---Winding number algorithm for 2D point-in-polygon test ---Winding number algorithm for 2D point-in-polygon test
@@ -155,31 +182,31 @@ end
---@param polygon number[][] Array of 2D polygon vertices as {{u,v}, ...} ---@param polygon number[][] Array of 2D polygon vertices as {{u,v}, ...}
---@return boolean True if point is inside polygon, false otherwise ---@return boolean True if point is inside polygon, false otherwise
function Polyhedron:pointInPolygon2D(point, polygon) function Polyhedron:pointInPolygon2D(point, polygon)
local wn = 0 -- Winding number counter local wn = 0 -- Winding number counter
for i = 1, #polygon do for i = 1, #polygon do
local j = (i % #polygon) + 1 local j = (i % #polygon) + 1
local vi = polygon[i] local vi = polygon[i]
local vj = polygon[j] local vj = polygon[j]
if vi[2] <= point[2] then if vi[2] <= point[2] then
if vj[2] > point[2] then if vj[2] > point[2] then
-- Upward crossing -- Upward crossing
if self:isLeft(vi, vj, point) > 0 then if self:isLeft(vi, vj, point) > 0 then
wn = wn + 1 wn = wn + 1
end end
end end
else else
if vj[2] <= point[2] then if vj[2] <= point[2] then
-- Downward crossing -- Downward crossing
if self:isLeft(vi, vj, point) < 0 then if self:isLeft(vi, vj, point) < 0 then
wn = wn - 1 wn = wn - 1
end end
end end
end end
end end
return wn ~= 0 -- Non-zero means inside return wn ~= 0 -- Non-zero means inside
end end
---Helper function for winding number algorithm - determines if point is left of edge ---Helper function for winding number algorithm - determines if point is left of edge
@@ -188,7 +215,7 @@ end
---@param p number[] Point to test {u, v} ---@param p number[] Point to test {u, v}
---@return number Positive if left, negative if right, zero if collinear ---@return number Positive if left, negative if right, zero if collinear
function Polyhedron:isLeft(a, b, p) function Polyhedron:isLeft(a, b, p)
return (b[1] - a[1]) * (p[2] - a[2]) - (p[1] - a[1]) * (b[2] - a[2]) return (b[1] - a[1]) * (p[2] - a[2]) - (p[1] - a[1]) * (b[2] - a[2])
end end
---Checks if a ray intersects with a face ---Checks if a ray intersects with a face
@@ -197,14 +224,14 @@ end
---@param face integer[] Array of vertex indices forming the face ---@param face integer[] Array of vertex indices forming the face
---@return boolean True if ray intersects the face, false otherwise ---@return boolean True if ray intersects the face, false otherwise
function Polyhedron:rayIntersectsFace(rayOrigin, rayDir, face) function Polyhedron:rayIntersectsFace(rayOrigin, rayDir, face)
local plane = self:computePlane(face) local plane = self:computePlane(face)
local intersection = self:rayPlaneIntersection(rayOrigin, rayDir, plane) local intersection = self:rayPlaneIntersection(rayOrigin, rayDir, plane)
if not intersection then if not intersection then
return false return false
end end
return self:pointInFace(intersection, face) return self:pointInFace(intersection, face)
end end
---Calculates the minimum distance from a point to a face ---Calculates the minimum distance from a point to a face
@@ -212,37 +239,37 @@ end
---@param face integer[] Array of vertex indices forming the face ---@param face integer[] Array of vertex indices forming the face
---@return number Minimum distance to the face (0 if point is on the face) ---@return number Minimum distance to the face (0 if point is on the face)
function Polyhedron:distanceToFace(point, face) function Polyhedron:distanceToFace(point, face)
local plane = self:computePlane(face) local plane = self:computePlane(face)
-- First check if projection is inside the face -- First check if projection is inside the face
local projection = point - plane.normal * (plane.normal:dot(point) + plane.d) local projection = point - plane.normal * (plane.normal:dot(point) + plane.d)
if self:pointInFace(projection, face) then if self:pointInFace(projection, face) then
-- Point projects inside face, return distance to plane -- Point projects inside face, return distance to plane
return mathAbs(plane.normal:dot(point) + plane.d) return mathAbs(plane.normal:dot(point) + plane.d)
end end
-- Point projects outside face, find minimum distance to edges or vertices -- Point projects outside face, find minimum distance to edges or vertices
local minDistance = mathHuge local minDistance = mathHuge
-- Check distance to each edge -- Check distance to each edge
for i = 1, #face do for i = 1, #face do
local j = (i % #face) + 1 local j = (i % #face) + 1
local v1 = self.vertices[face[i]] local v1 = self.vertices[face[i]]
local v2 = self.vertices[face[j]] local v2 = self.vertices[face[j]]
local edgeDistance = self:pointToLineSegmentDistance(point, v1, v2) local edgeDistance = self:pointToLineSegmentDistance(point, v1, v2)
minDistance = mathMin(minDistance, edgeDistance) minDistance = mathMin(minDistance, edgeDistance)
end end
-- Also check distance to vertices (in case the closest point is a vertex) -- Also check distance to vertices (in case the closest point is a vertex)
for _, vertexIndex in ipairs(face) do for _, vertexIndex in ipairs(face) do
local vertex = self.vertices[vertexIndex] local vertex = self.vertices[vertexIndex]
local vertexDistance = (point - vertex):length() local vertexDistance = (point - vertex):length()
minDistance = mathMin(minDistance, vertexDistance) minDistance = mathMin(minDistance, vertexDistance)
end end
return minDistance return minDistance
end end
---Calculates the distance from a point to a line segment ---Calculates the distance from a point to a line segment
@@ -251,63 +278,49 @@ end
---@param lineEnd vector End point of the line segment ---@param lineEnd vector End point of the line segment
---@return number Minimum distance from point to the line segment ---@return number Minimum distance from point to the line segment
function Polyhedron:pointToLineSegmentDistance(point, lineStart, lineEnd) function Polyhedron:pointToLineSegmentDistance(point, lineStart, lineEnd)
local lineVec = lineEnd - lineStart local lineVec = lineEnd - lineStart
local lineLengthSq = lineVec:dot(lineVec) local lineLengthSq = lineVec:dot(lineVec)
if lineLengthSq == 0 then if lineLengthSq == 0 then
return (point - lineStart):length() return (point - lineStart):length()
end end
local t = (point - lineStart):dot(lineVec) / lineLengthSq local t = (point - lineStart):dot(lineVec) / lineLengthSq
t = mathMax(0, mathMin(1, t)) t = mathMax(0, mathMin(1, t))
local projection = lineStart + lineVec * t local projection = lineStart + lineVec * t
return (point - projection):length() return (point - projection):length()
end end
---Checks if this polyhedron's bounding box intersects with another's ---Checks if this polyhedron's bounding box intersects with another's
---@param otherPolyhedron Polyhedron The other polyhedron to test against ---@param otherPolyhedron Polyhedron The other polyhedron to test against
---@return boolean True if bounding boxes intersect, false otherwise ---@return boolean True if bounding boxes intersect, false otherwise
function Polyhedron:boundingBoxIntersects(otherPolyhedron) function Polyhedron:boundingBoxIntersects(otherPolyhedron)
local box1 = self.boundingBox local box1 = self.boundingBox
local box2 = otherPolyhedron.boundingBox local box2 = otherPolyhedron.boundingBox
return box1.min.x <= box2.max.x and box1.max.x >= box2.min.x and return box1.min.x <= box2.max.x and box1.max.x >= box2.min.x and
box1.min.y <= box2.max.y and box1.max.y >= box2.min.y and box1.min.y <= box2.max.y and box1.max.y >= box2.min.y and
box1.min.z <= box2.max.z and box1.max.z >= box2.min.z box1.min.z <= box2.max.z and box1.max.z >= box2.min.z
end end
---Checks if any edge of this polyhedron intersects with any face of another polyhedron ---Checks if any edge of this polyhedron intersects with any face of another polyhedron
---@param otherPolyhedron Polyhedron The other polyhedron to test against ---@param otherPolyhedron Polyhedron The other polyhedron to test against
---@return boolean True if any edge intersects any face, false otherwise ---@return boolean True if any edge intersects any face, false otherwise
function Polyhedron:edgesIntersect(otherPolyhedron) function Polyhedron:edgesIntersect(otherPolyhedron)
-- Check each edge of this polyhedron against each face of the other -- Check each edge of this polyhedron against each face of the other
for _, face in ipairs(self.faces) do for _, face in ipairs(self.faces) do
for i = 1, #face do for i = 1, #face do
local j = (i % #face) + 1 local j = (i % #face) + 1
local edgeStart = self.vertices[face[i]] local edgeStart = self.vertices[face[i]]
local edgeEnd = self.vertices[face[j]] local edgeEnd = self.vertices[face[j]]
if self:edgeIntersectsPolyhedron(edgeStart, edgeEnd, otherPolyhedron) then if self:edgeIntersectsPolyhedron(edgeStart, edgeEnd, otherPolyhedron) then
return true return true
end end
end end
end end
return false
-- Check each edge of the other polyhedron against each face of this
for _, face in ipairs(otherPolyhedron.faces) do
for i = 1, #face do
local j = (i % #face) + 1
local edgeStart = otherPolyhedron.vertices[face[i]]
local edgeEnd = otherPolyhedron.vertices[face[j]]
if self:edgeIntersectsPolyhedron(edgeStart, edgeEnd, otherPolyhedron) then
return true
end
end
end
return false
end end
---Checks if an edge intersects with any face of a polyhedron ---Checks if an edge intersects with any face of a polyhedron
@@ -316,77 +329,85 @@ end
---@param polyhedron Polyhedron The polyhedron to test against ---@param polyhedron Polyhedron The polyhedron to test against
---@return boolean True if edge intersects the polyhedron, false otherwise ---@return boolean True if edge intersects the polyhedron, false otherwise
function Polyhedron:edgeIntersectsPolyhedron(edgeStart, edgeEnd, polyhedron) function Polyhedron:edgeIntersectsPolyhedron(edgeStart, edgeEnd, polyhedron)
local edgeDir = (edgeEnd - edgeStart):normalize() local edgeDir = (edgeEnd - edgeStart):normalize()
local edgeLength = (edgeEnd - edgeStart):length() local edgeLength = (edgeEnd - edgeStart):length()
for _, face in ipairs(polyhedron.faces) do for _, face in ipairs(polyhedron.faces) do
local plane = polyhedron:computePlane(face) local plane = polyhedron:computePlane(face)
local intersection = self:rayPlaneIntersection(edgeStart, edgeDir, plane) local intersection = self:rayPlaneIntersection(edgeStart, edgeDir, plane)
if intersection then if intersection then
local t = (intersection - edgeStart):length() local t = (intersection - edgeStart):length()
-- Check if intersection is within edge bounds and inside face -- Check if intersection is within edge bounds and inside face
if t >= 0 and t <= edgeLength and polyhedron:pointInFace(intersection, face) then if t >= 0 and t <= edgeLength and polyhedron:pointInFace(intersection, face) then
return true return true
end end
end end
end end
return false return false
end end
---Determines if a point is inside the polyhedron using ray-casting ---Determines if a point is inside the polyhedron using ray-casting
---@param point vector The point to test ---@param point vector The point to test
---@return boolean True if point is inside the polyhedron, false otherwise ---@return boolean True if point is inside the polyhedron, false otherwise
function Polyhedron:containsPoint(point) function Polyhedron:containsPoint(point)
-- Ray-casting algorithm for point-in-polyhedron test -- Fast AABB rejection first
local rayDir = vector.new(1, 0, 0) -- Simple X-direction ray local bb = self.boundingBox
local intersections = 0 if point.x < bb.min.x or point.x > bb.max.x or
point.y < bb.min.y or point.y > bb.max.y or
point.z < bb.min.z or point.z > bb.max.z then
return false
end
for _, face in ipairs(self.faces) do -- Then do ray casting
if self:rayIntersectsFace(point, rayDir, face) then local rayDir = vector.new(1, 0, 0)
intersections = intersections + 1 local intersections = 0
end
end
return intersections % 2 == 1 -- Odd number of intersections = inside for i, face in ipairs(self.faces) do
if self:rayIntersectsFace(point, rayDir, face) then
intersections = intersections + 1
end
end
return intersections % 2 == 1
end end
---Calculates the minimum distance from a point to the surface of the polyhedron ---Calculates the minimum distance from a point to the surface of the polyhedron
---@param point vector The point to measure distance from ---@param point vector The point to measure distance from
---@return number Minimum distance to the polyhedron surface ---@return number Minimum distance to the polyhedron surface
function Polyhedron:distanceToSurface(point) function Polyhedron:distanceToSurface(point)
local minDistance = mathHuge local minDistance = mathHuge
for _, face in ipairs(self.faces) do for _, face in ipairs(self.faces) do
local distance = self:distanceToFace(point, face) local distance = self:distanceToFace(point, face)
minDistance = mathMin(minDistance, distance) minDistance = mathMin(minDistance, distance)
end end
return minDistance return minDistance
end end
---Checks if this polyhedron intersects with another polyhedron ---Checks if this polyhedron intersects with another polyhedron
---@param otherPolyhedron Polyhedron The other polyhedron to test against ---@param otherPolyhedron Polyhedron The other polyhedron to test against
---@return boolean True if polyhedrons intersect, false otherwise ---@return boolean True if polyhedrons intersect, false otherwise
function Polyhedron:intersects(otherPolyhedron) function Polyhedron:intersects(otherPolyhedron)
-- Check if bounding boxes intersect first (optimization) -- Check if bounding boxes intersect first (optimization)
if not self:boundingBoxIntersects(otherPolyhedron) then if not self:boundingBoxIntersects(otherPolyhedron) then
return false return false
end end
-- Check if any vertex of one is inside the other -- Check if any vertex of one is inside the other
for _, vertex in ipairs(self.vertices) do for _, vertex in ipairs(self.vertices) do
if otherPolyhedron:containsPoint(vertex) then return true end if otherPolyhedron:containsPoint(vertex) then return true end
end end
for _, vertex in ipairs(otherPolyhedron.vertices) do for _, vertex in ipairs(otherPolyhedron.vertices) do
if self:containsPoint(vertex) then return true end if self:containsPoint(vertex) then return true end
end end
-- Check for edge-face intersections -- Check for edge-face intersections
return self:edgesIntersect(otherPolyhedron) return self:edgesIntersect(otherPolyhedron)
end end
return Polyhedron return Polyhedron