Ported .Net Core commits:
hondacrx: - Initial commit: Switch to .Net Core 2.0 - Fix build and removed not needed files Fabi: - Updated solution platforms. - Changed folder structure. - Change library target framework to netstandard2.0. - Updated solution platforms again... - Removed windows specific kernel32 function usage (Ctrl-C handler).
This commit is contained in:
@@ -0,0 +1,636 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public class BIH
|
||||
{
|
||||
public BIH()
|
||||
{
|
||||
init_empty();
|
||||
}
|
||||
|
||||
void init_empty()
|
||||
{
|
||||
tree.Clear();
|
||||
objects.Clear();
|
||||
// create space for the first node
|
||||
tree.Add(3u << 30); // dummy leaf
|
||||
tree.Add(0);
|
||||
tree.Add(0);
|
||||
}
|
||||
|
||||
public void build<T>(List<T> primitives, uint leafSize = 3, bool printStats = false) where T : IModel
|
||||
{
|
||||
if (primitives.Count == 0)
|
||||
{
|
||||
init_empty();
|
||||
return;
|
||||
}
|
||||
|
||||
buildData dat;
|
||||
dat.maxPrims = (int)leafSize;
|
||||
dat.numPrims = (uint)primitives.Count;
|
||||
dat.indices = new uint[dat.numPrims];
|
||||
dat.primBound = new AxisAlignedBox[dat.numPrims];
|
||||
bounds = primitives[0].getBounds();
|
||||
for (int i = 0; i < dat.numPrims; ++i)
|
||||
{
|
||||
dat.indices[i] = (uint)i;
|
||||
dat.primBound[i] = primitives[i].getBounds();
|
||||
bounds.merge(dat.primBound[i]);
|
||||
}
|
||||
List<uint> tempTree = new List<uint>();
|
||||
BuildStats stats = new BuildStats();
|
||||
buildHierarchy(tempTree, dat, stats);
|
||||
if (printStats)
|
||||
stats.printStats();
|
||||
|
||||
for (int i = 0; i < dat.numPrims; ++i)
|
||||
objects.Add(dat.indices[i]);
|
||||
tree = tempTree;
|
||||
}
|
||||
public uint primCount() { return (uint)objects.Count; }
|
||||
|
||||
public bool readFromFile(BinaryReader reader)
|
||||
{
|
||||
var lo = reader.ReadStruct<Vector3>();
|
||||
var hi = reader.ReadStruct<Vector3>();
|
||||
bounds = new AxisAlignedBox(lo, hi);
|
||||
|
||||
uint treeSize = reader.ReadUInt32();
|
||||
tree.Clear();
|
||||
for (var i = 0; i < treeSize; i++)
|
||||
tree.Add(reader.ReadUInt32());
|
||||
|
||||
var count = reader.ReadUInt32();
|
||||
objects.Clear();
|
||||
for (var i = 0; i < count; i++)
|
||||
objects.Add(reader.ReadUInt32());
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void intersectRay(Ray r, WorkerCallback intersectCallback, ref float maxDist, bool stopAtFirst = false)
|
||||
{
|
||||
float intervalMin = -1.0f;
|
||||
float intervalMax = -1.0f;
|
||||
Vector3 org = r.Origin;
|
||||
Vector3 dir = r.Direction;
|
||||
Vector3 invDir = new Vector3();
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
invDir[i] = 1.0f / dir[i];
|
||||
if (MathFunctions.fuzzyNe(dir[i], 0.0f))
|
||||
{
|
||||
float t1 = (bounds.Lo[i] - org[i]) * invDir[i];
|
||||
float t2 = (bounds.Hi[i] - org[i]) * invDir[i];
|
||||
if (t1 > t2)
|
||||
MathFunctions.Swap<float>(ref t1, ref t2);
|
||||
if (t1 > intervalMin)
|
||||
intervalMin = t1;
|
||||
if (t2 < intervalMax || intervalMax < 0.0f)
|
||||
intervalMax = t2;
|
||||
// intervalMax can only become smaller for other axis,
|
||||
// and intervalMin only larger respectively, so stop early
|
||||
if (intervalMax <= 0 || intervalMin >= maxDist)
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (intervalMin > intervalMax)
|
||||
return;
|
||||
intervalMin = Math.Max(intervalMin, 0.0f);
|
||||
intervalMax = Math.Min(intervalMax, maxDist);
|
||||
|
||||
uint[] offsetFront = new uint[3];
|
||||
uint[] offsetBack = new uint[3];
|
||||
uint[] offsetFront3 = new uint[3];
|
||||
uint[] offsetBack3 = new uint[3];
|
||||
// compute custom offsets from direction sign bit
|
||||
|
||||
for (int i = 0; i < 3; ++i)
|
||||
{
|
||||
offsetFront[i] = floatToRawIntBits(dir[i]) >> 31;
|
||||
offsetBack[i] = offsetFront[i] ^ 1;
|
||||
offsetFront3[i] = offsetFront[i] * 3;
|
||||
offsetBack3[i] = offsetBack[i] * 3;
|
||||
|
||||
// avoid always adding 1 during the inner loop
|
||||
++offsetFront[i];
|
||||
++offsetBack[i];
|
||||
}
|
||||
|
||||
StackNode[] stack = new StackNode[64];
|
||||
int stackPos = 0;
|
||||
int node = 0;
|
||||
|
||||
while (true)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
uint tn = tree[node];
|
||||
uint axis = (uint)(tn & (3 << 30)) >> 30;
|
||||
bool BVH2 = Convert.ToBoolean(tn & (1 << 29));
|
||||
int offset = (int)(tn & ~(7 << 29));
|
||||
if (!BVH2)
|
||||
{
|
||||
if (axis < 3)
|
||||
{
|
||||
// "normal" interior node
|
||||
float tf = (intBitsToFloat(tree[(int)(node + offsetFront[axis])]) - org[axis]) * invDir[axis];
|
||||
float tb = (intBitsToFloat(tree[(int)(node + offsetBack[axis])]) - org[axis]) * invDir[axis];
|
||||
// ray passes between clip zones
|
||||
if (tf < intervalMin && tb > intervalMax)
|
||||
break;
|
||||
int back = (int)(offset + offsetBack3[axis]);
|
||||
node = back;
|
||||
// ray passes through far node only
|
||||
if (tf < intervalMin)
|
||||
{
|
||||
intervalMin = (tb >= intervalMin) ? tb : intervalMin;
|
||||
continue;
|
||||
}
|
||||
node = offset + (int)offsetFront3[axis]; // front
|
||||
// ray passes through near node only
|
||||
if (tb > intervalMax)
|
||||
{
|
||||
intervalMax = (tf <= intervalMax) ? tf : intervalMax;
|
||||
continue;
|
||||
}
|
||||
// ray passes through both nodes
|
||||
// push back node
|
||||
stack[stackPos].node = (uint)back;
|
||||
stack[stackPos].tnear = (tb >= intervalMin) ? tb : intervalMin;
|
||||
stack[stackPos].tfar = intervalMax;
|
||||
stackPos++;
|
||||
// update ray interval for front node
|
||||
intervalMax = (tf <= intervalMax) ? tf : intervalMax;
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
// leaf - test some objects
|
||||
int n = (int)tree[node + 1];
|
||||
while (n > 0)
|
||||
{
|
||||
bool hit = intersectCallback.Invoke(r, objects[offset], ref maxDist, stopAtFirst);
|
||||
if (stopAtFirst && hit)
|
||||
return;
|
||||
--n;
|
||||
++offset;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (axis > 2)
|
||||
return; // should not happen
|
||||
float tf = (intBitsToFloat(tree[(int)(node + offsetFront[axis])]) - org[axis]) * invDir[axis];
|
||||
float tb = (intBitsToFloat(tree[(int)(node + offsetBack[axis])]) - org[axis]) * invDir[axis];
|
||||
node = offset;
|
||||
intervalMin = (tf >= intervalMin) ? tf : intervalMin;
|
||||
intervalMax = (tb <= intervalMax) ? tb : intervalMax;
|
||||
if (intervalMin > intervalMax)
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
} // traversal loop
|
||||
do
|
||||
{
|
||||
// stack is empty?
|
||||
if (stackPos == 0)
|
||||
return;
|
||||
// move back up the stack
|
||||
stackPos--;
|
||||
intervalMin = stack[stackPos].tnear;
|
||||
if (maxDist < intervalMin)
|
||||
continue;
|
||||
node = (int)stack[stackPos].node;
|
||||
intervalMax = stack[stackPos].tfar;
|
||||
break;
|
||||
} while (true);
|
||||
}
|
||||
}
|
||||
|
||||
public void intersectPoint(Vector3 p, WorkerCallback intersectCallback)
|
||||
{
|
||||
if (!bounds.contains(p))
|
||||
return;
|
||||
|
||||
StackNode[] stack = new StackNode[64];
|
||||
int stackPos = 0;
|
||||
int node = 0;
|
||||
|
||||
while (true)
|
||||
{
|
||||
while (true)
|
||||
{
|
||||
uint tn = tree[node];
|
||||
uint axis = (uint)(tn & (3 << 30)) >> 30;
|
||||
bool BVH2 = Convert.ToBoolean(tn & (1 << 29));
|
||||
int offset = (int)(tn & ~(7 << 29));
|
||||
if (!BVH2)
|
||||
{
|
||||
if (axis < 3)
|
||||
{
|
||||
// "normal" interior node
|
||||
float tl = intBitsToFloat(tree[node + 1]);
|
||||
float tr = intBitsToFloat(tree[node + 2]);
|
||||
// point is between clip zones
|
||||
if (tl < p[(int)axis] && tr > p[axis])
|
||||
break;
|
||||
int right = offset + 3;
|
||||
node = right;
|
||||
// point is in right node only
|
||||
if (tl < p[(int)axis])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
node = offset; // left
|
||||
// point is in left node only
|
||||
if (tr > p[axis])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
// point is in both nodes
|
||||
// push back right node
|
||||
stack[stackPos].node = (uint)right;
|
||||
stackPos++;
|
||||
continue;
|
||||
}
|
||||
else
|
||||
{
|
||||
// leaf - test some objects
|
||||
uint n = tree[node + 1];
|
||||
while (n > 0)
|
||||
{
|
||||
intersectCallback.Invoke(p, objects[offset]); // !!!
|
||||
--n;
|
||||
++offset;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
else // BVH2 node (empty space cut off left and right)
|
||||
{
|
||||
if (axis > 2)
|
||||
return; // should not happen
|
||||
float tl = intBitsToFloat(tree[node + 1]);
|
||||
float tr = intBitsToFloat(tree[node + 2]);
|
||||
node = offset;
|
||||
if (tl > p[axis] || tr < p[axis])
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
} // traversal loop
|
||||
|
||||
// stack is empty?
|
||||
if (stackPos == 0)
|
||||
return;
|
||||
// move back up the stack
|
||||
stackPos--;
|
||||
node = (int)stack[stackPos].node;
|
||||
}
|
||||
}
|
||||
|
||||
void buildHierarchy(List<uint> tempTree, buildData dat, BuildStats stats)
|
||||
{
|
||||
// create space for the first node
|
||||
tempTree.Add(3u << 30); // dummy leaf
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
|
||||
// seed bbox
|
||||
AABound gridBox = new AABound();
|
||||
gridBox.lo = bounds.Lo;
|
||||
gridBox.hi = bounds.Hi;
|
||||
AABound nodeBox = gridBox;
|
||||
// seed subdivide function
|
||||
subdivide(0, (int)(dat.numPrims - 1), tempTree, dat, gridBox, nodeBox, 0, 1, stats);
|
||||
}
|
||||
|
||||
void subdivide(int left, int right, List<uint> tempTree, buildData dat, AABound gridBox, AABound nodeBox, int nodeIndex, int depth, BuildStats stats)
|
||||
{
|
||||
if ((right - left + 1) <= dat.maxPrims || depth >= 64)
|
||||
{
|
||||
// write leaf node
|
||||
stats.updateLeaf(depth, right - left + 1);
|
||||
createNode(tempTree, nodeIndex, left, right);
|
||||
return;
|
||||
}
|
||||
// calculate extents
|
||||
int axis = -1, prevAxis, rightOrig;
|
||||
float clipL = float.NaN, clipR = float.NaN, prevClip = float.NaN;
|
||||
float split = float.NaN, prevSplit;
|
||||
bool wasLeft = true;
|
||||
while (true)
|
||||
{
|
||||
prevAxis = axis;
|
||||
prevSplit = split;
|
||||
// perform quick consistency checks
|
||||
Vector3 d = gridBox.hi - gridBox.lo;
|
||||
for (int i = 0; i < 3; i++)
|
||||
{
|
||||
if (nodeBox.hi[i] < gridBox.lo[i] || nodeBox.lo[i] > gridBox.hi[i])
|
||||
Log.outError(LogFilter.Server, "Reached tree area in error - discarding node with: {0} objects", right - left + 1);
|
||||
}
|
||||
// find longest axis
|
||||
axis = (int)d.primaryAxis();
|
||||
split = 0.5f * (gridBox.lo[axis] + gridBox.hi[axis]);
|
||||
// partition L/R subsets
|
||||
clipL = float.NegativeInfinity;
|
||||
clipR = float.PositiveInfinity;
|
||||
rightOrig = right; // save this for later
|
||||
float nodeL = float.PositiveInfinity;
|
||||
float nodeR = float.NegativeInfinity;
|
||||
for (int i = left; i <= right; )
|
||||
{
|
||||
int obj = (int)dat.indices[i];
|
||||
float minb = dat.primBound[obj].Lo[axis];
|
||||
float maxb = dat.primBound[obj].Hi[axis];
|
||||
float center = (minb + maxb) * 0.5f;
|
||||
if (center <= split)
|
||||
{
|
||||
// stay left
|
||||
i++;
|
||||
if (clipL < maxb)
|
||||
clipL = maxb;
|
||||
}
|
||||
else
|
||||
{
|
||||
// move to the right most
|
||||
int t = (int)dat.indices[i];
|
||||
dat.indices[i] = dat.indices[right];
|
||||
dat.indices[right] = (uint)t;
|
||||
right--;
|
||||
if (clipR > minb)
|
||||
clipR = minb;
|
||||
}
|
||||
nodeL = Math.Min(nodeL, minb);
|
||||
nodeR = Math.Max(nodeR, maxb);
|
||||
}
|
||||
// check for empty space
|
||||
if (nodeL > nodeBox.lo[axis] && nodeR < nodeBox.hi[axis])
|
||||
{
|
||||
float nodeBoxW = nodeBox.hi[axis] - nodeBox.lo[axis];
|
||||
float nodeNewW = nodeR - nodeL;
|
||||
// node box is too big compare to space occupied by primitives?
|
||||
if (1.3f * nodeNewW < nodeBoxW)
|
||||
{
|
||||
stats.updateBVH2();
|
||||
int nextIndex1 = tempTree.Count();
|
||||
// allocate child
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
// write bvh2 clip node
|
||||
stats.updateInner();
|
||||
tempTree[nodeIndex + 0] = (uint)((axis << 30) | (1 << 29) | nextIndex1);
|
||||
tempTree[nodeIndex + 1] = floatToRawIntBits(nodeL);
|
||||
tempTree[nodeIndex + 2] = floatToRawIntBits(nodeR);
|
||||
// update nodebox and recurse
|
||||
nodeBox.lo[axis] = nodeL;
|
||||
nodeBox.hi[axis] = nodeR;
|
||||
subdivide(left, rightOrig, tempTree, dat, gridBox, nodeBox, nextIndex1, depth + 1, stats);
|
||||
return;
|
||||
}
|
||||
}
|
||||
// ensure we are making progress in the subdivision
|
||||
if (right == rightOrig)
|
||||
{
|
||||
// all left
|
||||
if (prevAxis == axis && MathFunctions.fuzzyEq(prevSplit, split))
|
||||
{
|
||||
// we are stuck here - create a leaf
|
||||
stats.updateLeaf(depth, right - left + 1);
|
||||
createNode(tempTree, nodeIndex, left, right);
|
||||
return;
|
||||
}
|
||||
if (clipL <= split)
|
||||
{
|
||||
// keep looping on left half
|
||||
gridBox.hi[axis] = split;
|
||||
prevClip = clipL;
|
||||
wasLeft = true;
|
||||
continue;
|
||||
}
|
||||
gridBox.hi[axis] = split;
|
||||
prevClip = float.NaN;
|
||||
}
|
||||
else if (left > right)
|
||||
{
|
||||
// all right
|
||||
right = rightOrig;
|
||||
if (prevAxis == axis && MathFunctions.fuzzyEq(prevSplit, split))
|
||||
{
|
||||
// we are stuck here - create a leaf
|
||||
stats.updateLeaf(depth, right - left + 1);
|
||||
createNode(tempTree, nodeIndex, left, right);
|
||||
return;
|
||||
}
|
||||
|
||||
if (clipR >= split)
|
||||
{
|
||||
// keep looping on right half
|
||||
gridBox.lo[axis] = split;
|
||||
prevClip = clipR;
|
||||
wasLeft = false;
|
||||
continue;
|
||||
}
|
||||
gridBox.lo[axis] = split;
|
||||
prevClip = float.NaN;
|
||||
}
|
||||
else
|
||||
{
|
||||
// we are actually splitting stuff
|
||||
if (prevAxis != -1 && !float.IsNaN(prevClip))
|
||||
{
|
||||
// second time through - lets create the previous split
|
||||
// since it produced empty space
|
||||
int nextIndex0 = tempTree.Count;
|
||||
// allocate child node
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
if (wasLeft)
|
||||
{
|
||||
// create a node with a left child
|
||||
// write leaf node
|
||||
stats.updateInner();
|
||||
tempTree[nodeIndex + 0] = (uint)((prevAxis << 30) | nextIndex0);
|
||||
tempTree[nodeIndex + 1] = floatToRawIntBits(prevClip);
|
||||
tempTree[nodeIndex + 2] = floatToRawIntBits(float.PositiveInfinity);
|
||||
}
|
||||
else
|
||||
{
|
||||
// create a node with a right child
|
||||
// write leaf node
|
||||
stats.updateInner();
|
||||
tempTree[nodeIndex + 0] = (uint)((prevAxis << 30) | (nextIndex0 - 3));
|
||||
tempTree[nodeIndex + 1] = floatToRawIntBits(float.NegativeInfinity);
|
||||
tempTree[nodeIndex + 2] = floatToRawIntBits(prevClip);
|
||||
}
|
||||
// count stats for the unused leaf
|
||||
depth++;
|
||||
stats.updateLeaf(depth, 0);
|
||||
// now we keep going as we are, with a new nodeIndex:
|
||||
nodeIndex = nextIndex0;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
// compute index of child nodes
|
||||
int nextIndex = tempTree.Count;
|
||||
// allocate left node
|
||||
int nl = right - left + 1;
|
||||
int nr = rightOrig - (right + 1) + 1;
|
||||
if (nl > 0)
|
||||
{
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
}
|
||||
else
|
||||
nextIndex -= 3;
|
||||
// allocate right node
|
||||
if (nr > 0)
|
||||
{
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
tempTree.Add(0);
|
||||
}
|
||||
// write leaf node
|
||||
stats.updateInner();
|
||||
tempTree[nodeIndex + 0] = (uint)((axis << 30) | nextIndex);
|
||||
tempTree[nodeIndex + 1] = floatToRawIntBits(clipL);
|
||||
tempTree[nodeIndex + 2] = floatToRawIntBits(clipR);
|
||||
// prepare L/R child boxes
|
||||
AABound gridBoxL = gridBox;
|
||||
AABound gridBoxR = gridBox;
|
||||
AABound nodeBoxL = nodeBox;
|
||||
AABound nodeBoxR = nodeBox;
|
||||
gridBoxL.hi[axis] = gridBoxR.lo[axis] = split;
|
||||
nodeBoxL.hi[axis] = clipL;
|
||||
nodeBoxR.lo[axis] = clipR;
|
||||
// recurse
|
||||
if (nl > 0)
|
||||
subdivide(left, right, tempTree, dat, gridBoxL, nodeBoxL, nextIndex, depth + 1, stats);
|
||||
else
|
||||
stats.updateLeaf(depth + 1, 0);
|
||||
if (nr > 0)
|
||||
subdivide(right + 1, rightOrig, tempTree, dat, gridBoxR, nodeBoxR, nextIndex + 3, depth + 1, stats);
|
||||
else
|
||||
stats.updateLeaf(depth + 1, 0);
|
||||
}
|
||||
|
||||
void createNode(List<uint> tempTree, int nodeIndex, int left, int right)
|
||||
{
|
||||
// write leaf node
|
||||
tempTree[nodeIndex + 0] = (uint)((3 << 30) | left);
|
||||
tempTree[nodeIndex + 1] = (uint)(right - left + 1);
|
||||
}
|
||||
|
||||
struct buildData
|
||||
{
|
||||
public uint[] indices;
|
||||
public AxisAlignedBox[] primBound;
|
||||
public uint numPrims;
|
||||
public int maxPrims;
|
||||
}
|
||||
struct StackNode
|
||||
{
|
||||
public uint node;
|
||||
public float tnear;
|
||||
public float tfar;
|
||||
}
|
||||
public class BuildStats
|
||||
{
|
||||
public int numNodes;
|
||||
public int numLeaves;
|
||||
public int sumObjects;
|
||||
public int minObjects;
|
||||
public int maxObjects;
|
||||
public int sumDepth;
|
||||
public int minDepth;
|
||||
public int maxDepth;
|
||||
int[] numLeavesN = new int[6];
|
||||
int numBVH2;
|
||||
|
||||
public BuildStats()
|
||||
{
|
||||
numNodes = 0;
|
||||
numLeaves = 0;
|
||||
sumObjects = 0;
|
||||
minObjects = 0x0FFFFFFF;
|
||||
maxObjects = -1;
|
||||
sumDepth = 0;
|
||||
minDepth = 0x0FFFFFFF;
|
||||
maxDepth = -1;
|
||||
numBVH2 = 0;
|
||||
|
||||
for (int i = 0; i < 6; ++i)
|
||||
numLeavesN[i] = 0;
|
||||
}
|
||||
|
||||
public void updateInner() { numNodes++; }
|
||||
public void updateBVH2() { numBVH2++; }
|
||||
public void updateLeaf(int depth, int n) { }
|
||||
public void printStats() { }
|
||||
}
|
||||
|
||||
|
||||
AxisAlignedBox bounds;
|
||||
List<uint> tree = new List<uint>();
|
||||
List<uint> objects = new List<uint>();
|
||||
|
||||
[StructLayout(LayoutKind.Explicit)]
|
||||
public struct FloatToIntConverter
|
||||
{
|
||||
[FieldOffset(0)]
|
||||
public uint IntValue;
|
||||
[FieldOffset(0)]
|
||||
public float FloatValue;
|
||||
}
|
||||
|
||||
uint floatToRawIntBits(float f)
|
||||
{
|
||||
FloatToIntConverter converter = new FloatToIntConverter();
|
||||
converter.FloatValue = f;
|
||||
return converter.IntValue;
|
||||
}
|
||||
float intBitsToFloat(uint i)
|
||||
{
|
||||
FloatToIntConverter converter = new FloatToIntConverter();
|
||||
converter.IntValue = i;
|
||||
return converter.FloatValue;
|
||||
}
|
||||
|
||||
}
|
||||
public struct AABound
|
||||
{
|
||||
public Vector3 lo, hi;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public class BIHWrap<T> where T : IModel
|
||||
{
|
||||
public void insert(T obj)
|
||||
{
|
||||
++unbalanced_times;
|
||||
m_objects_to_push.Add(obj);
|
||||
}
|
||||
public void remove(T obj)
|
||||
{
|
||||
++unbalanced_times;
|
||||
uint Idx = 0;
|
||||
if (m_obj2Idx.TryGetValue(obj, out Idx))
|
||||
m_objects[(int)Idx] = null;
|
||||
else
|
||||
m_objects_to_push.Remove(obj);
|
||||
}
|
||||
|
||||
public void balance()
|
||||
{
|
||||
if (unbalanced_times == 0)
|
||||
return;
|
||||
|
||||
unbalanced_times = 0;
|
||||
m_objects.Clear();
|
||||
m_objects.AddRange(m_obj2Idx.Keys);
|
||||
m_objects.AddRange(m_objects_to_push);
|
||||
|
||||
m_tree.build(m_objects);
|
||||
}
|
||||
|
||||
public void intersectRay(Ray ray, WorkerCallback intersectCallback, ref float maxDist)
|
||||
{
|
||||
balance();
|
||||
MDLCallback temp_cb = new MDLCallback(intersectCallback, m_objects.ToArray(), (uint)m_objects.Count);
|
||||
m_tree.intersectRay(ray, temp_cb, ref maxDist, true);
|
||||
}
|
||||
|
||||
public void intersectPoint(Vector3 point, WorkerCallback intersectCallback)
|
||||
{
|
||||
balance();
|
||||
MDLCallback callback = new MDLCallback(intersectCallback, m_objects.ToArray(), (uint)m_objects.Count);
|
||||
m_tree.intersectPoint(point, callback);
|
||||
}
|
||||
|
||||
BIH m_tree = new BIH();
|
||||
List<T> m_objects = new List<T>();
|
||||
Dictionary<T, uint> m_obj2Idx = new Dictionary<T, uint>();
|
||||
HashSet<T> m_objects_to_push = new HashSet<T>();
|
||||
int unbalanced_times;
|
||||
|
||||
public class MDLCallback : WorkerCallback
|
||||
{
|
||||
T[] objects;
|
||||
WorkerCallback _callback;
|
||||
uint objects_size;
|
||||
|
||||
public MDLCallback(WorkerCallback callback, T[] objects_array, uint size)
|
||||
{
|
||||
objects = objects_array;
|
||||
_callback = callback;
|
||||
objects_size = size;
|
||||
}
|
||||
|
||||
/// Intersect ray
|
||||
public override bool Invoke(Ray ray, uint idx, ref float maxDist)
|
||||
{
|
||||
if (idx >= objects_size)
|
||||
return false;
|
||||
|
||||
T obj = objects[idx];
|
||||
if (obj != null)
|
||||
return _callback.Invoke(ray, obj, ref maxDist);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Intersect point
|
||||
public override void Invoke(Vector3 p, uint idx)
|
||||
{
|
||||
if (idx >= objects_size)
|
||||
return;
|
||||
|
||||
T obj = objects[idx];
|
||||
if (obj != null)
|
||||
_callback.Invoke(p, Convert.ToUInt32(obj));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public class WorkerCallback
|
||||
{
|
||||
public virtual void Invoke(Vector3 point, uint entry) { }
|
||||
public virtual bool Invoke(Ray ray, uint entry, ref float distance, bool pStopAtFirstHit) { return false; }
|
||||
public virtual bool Invoke(Ray r, GameObjectModel obj, ref float distance) { return false; }
|
||||
public virtual bool Invoke(Ray r, IModel obj, ref float distance) { return false; }
|
||||
public virtual bool Invoke(Ray ray, uint idx, ref float maxDist) { return false; }
|
||||
}
|
||||
|
||||
public class TriBoundFunc
|
||||
{
|
||||
public TriBoundFunc(List<Vector3> vert)
|
||||
{
|
||||
vertices = vert;
|
||||
}
|
||||
|
||||
public void Invoke(MeshTriangle tri, out AxisAlignedBox value)
|
||||
{
|
||||
Vector3 lo = vertices[(int)tri.idx0];
|
||||
Vector3 hi = lo;
|
||||
|
||||
lo = (lo.Min(vertices[(int)tri.idx1])).Min(vertices[(int)tri.idx2]);
|
||||
hi = (hi.Max(vertices[(int)tri.idx1])).Max(vertices[(int)tri.idx2]);
|
||||
|
||||
value = new AxisAlignedBox(lo, hi);
|
||||
}
|
||||
|
||||
List<Vector3> vertices;
|
||||
}
|
||||
|
||||
public class WModelAreaCallback : WorkerCallback
|
||||
{
|
||||
public WModelAreaCallback(List<GroupModel> vals, Vector3 down)
|
||||
{
|
||||
prims = vals;
|
||||
hit = null;
|
||||
zDist = float.PositiveInfinity;
|
||||
zVec = down;
|
||||
}
|
||||
|
||||
List<GroupModel> prims;
|
||||
public GroupModel hit;
|
||||
public float zDist;
|
||||
Vector3 zVec;
|
||||
public override void Invoke(Vector3 point, uint entry)
|
||||
{
|
||||
float group_Z;
|
||||
if (prims[(int)entry].IsInsideObject(point, zVec, out group_Z))
|
||||
{
|
||||
if (group_Z < zDist)
|
||||
{
|
||||
zDist = group_Z;
|
||||
hit = prims[(int)entry];
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public class WModelRayCallBack : WorkerCallback
|
||||
{
|
||||
public WModelRayCallBack(List<GroupModel> mod)
|
||||
{
|
||||
models = mod;
|
||||
hit = false;
|
||||
}
|
||||
public override bool Invoke(Ray ray, uint entry, ref float distance, bool pStopAtFirstHit)
|
||||
{
|
||||
bool result = models[(int)entry].IntersectRay(ray, ref distance, pStopAtFirstHit);
|
||||
if (result) hit = true;
|
||||
return hit;
|
||||
}
|
||||
List<GroupModel> models;
|
||||
public bool hit;
|
||||
}
|
||||
|
||||
public class GModelRayCallback : WorkerCallback
|
||||
{
|
||||
public GModelRayCallback(List<MeshTriangle> tris, List<Vector3> vert)
|
||||
{
|
||||
vertices = vert;
|
||||
triangles = tris;
|
||||
hit = false;
|
||||
}
|
||||
public override bool Invoke(Ray ray, uint entry, ref float distance, bool pStopAtFirstHit)
|
||||
{
|
||||
bool result = IntersectTriangle(triangles[(int)entry], vertices, ray, ref distance);
|
||||
if (result)
|
||||
hit = true;
|
||||
|
||||
return hit;
|
||||
}
|
||||
|
||||
bool IntersectTriangle(MeshTriangle tri, List<Vector3> points, Ray ray, ref float distance)
|
||||
{
|
||||
const float EPS = 1e-5f;
|
||||
|
||||
// See RTR2 ch. 13.7 for the algorithm.
|
||||
|
||||
Vector3 e1 = points[(int)tri.idx1] - points[(int)tri.idx0];
|
||||
Vector3 e2 = points[(int)tri.idx2] - points[(int)tri.idx0];
|
||||
Vector3 p = new Vector3(ray.Direction.cross(e2));
|
||||
float a = e1.dot(p);
|
||||
|
||||
if (Math.Abs(a) < EPS)
|
||||
{
|
||||
// Determinant is ill-conditioned; abort early
|
||||
return false;
|
||||
}
|
||||
|
||||
float f = 1.0f / a;
|
||||
Vector3 s = new Vector3(ray.Origin - points[(int)tri.idx0]);
|
||||
float u = f * s.dot(p);
|
||||
|
||||
if ((u < 0.0f) || (u > 1.0f))
|
||||
{
|
||||
// We hit the plane of the m_geometry, but outside the m_geometry
|
||||
return false;
|
||||
}
|
||||
|
||||
Vector3 q = new Vector3(s.cross(e1));
|
||||
float v = f * ray.Direction.dot(q);
|
||||
|
||||
if ((v < 0.0f) || ((u + v) > 1.0f))
|
||||
{
|
||||
// We hit the plane of the triangle, but outside the triangle
|
||||
return false;
|
||||
}
|
||||
|
||||
float t = f * e2.dot(q);
|
||||
|
||||
if ((t > 0.0f) && (t < distance))
|
||||
{
|
||||
// This is a new hit, closer than the previous one
|
||||
distance = t;
|
||||
return true;
|
||||
}
|
||||
// This hit is after the previous hit, so ignore it
|
||||
return false;
|
||||
}
|
||||
|
||||
List<Vector3> vertices;
|
||||
List<MeshTriangle> triangles;
|
||||
public bool hit;
|
||||
}
|
||||
|
||||
public class MapRayCallback : WorkerCallback
|
||||
{
|
||||
public MapRayCallback(ModelInstance[] val)
|
||||
{
|
||||
prims = val;
|
||||
hit = false;
|
||||
}
|
||||
public override bool Invoke(Ray ray, uint entry, ref float distance, bool pStopAtFirstHit = true)
|
||||
{
|
||||
if (prims[entry] == null)
|
||||
return false;
|
||||
bool result = prims[entry].intersectRay(ray, ref distance, pStopAtFirstHit);
|
||||
if (result)
|
||||
hit = true;
|
||||
return result;
|
||||
}
|
||||
public bool didHit() { return hit; }
|
||||
|
||||
ModelInstance[] prims;
|
||||
bool hit;
|
||||
}
|
||||
|
||||
public class AreaInfoCallback : WorkerCallback
|
||||
{
|
||||
public AreaInfoCallback(ModelInstance[] val)
|
||||
{
|
||||
prims = val;
|
||||
}
|
||||
public override void Invoke(Vector3 point, uint entry)
|
||||
{
|
||||
if (prims[entry] == null)
|
||||
return;
|
||||
|
||||
prims[entry].intersectPoint(point, aInfo);
|
||||
}
|
||||
|
||||
ModelInstance[] prims;
|
||||
public AreaInfo aInfo = new AreaInfo();
|
||||
}
|
||||
|
||||
public class LocationInfoCallback : WorkerCallback
|
||||
{
|
||||
public LocationInfoCallback(ModelInstance[] val, LocationInfo info)
|
||||
{
|
||||
prims = val;
|
||||
locInfo = info;
|
||||
result = false;
|
||||
}
|
||||
|
||||
public override void Invoke(Vector3 point, uint entry)
|
||||
{
|
||||
if (prims[entry] != null && prims[entry].GetLocationInfo(point, locInfo))
|
||||
result = true;
|
||||
}
|
||||
|
||||
ModelInstance[] prims;
|
||||
LocationInfo locInfo;
|
||||
public bool result;
|
||||
}
|
||||
|
||||
public class DynamicTreeIntersectionCallback : WorkerCallback
|
||||
{
|
||||
public DynamicTreeIntersectionCallback(List<uint> phases)
|
||||
{
|
||||
_didHit = false;
|
||||
_phases = phases;
|
||||
}
|
||||
|
||||
public override bool Invoke(Ray r, GameObjectModel obj, ref float distance)
|
||||
{
|
||||
_didHit = obj.intersectRay(r, ref distance, true, _phases);
|
||||
return _didHit;
|
||||
}
|
||||
|
||||
public bool didHit() { return _didHit; }
|
||||
|
||||
bool _didHit;
|
||||
List<uint> _phases;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.GameMath;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public class DynamicMapTree
|
||||
{
|
||||
DynTreeImpl impl;
|
||||
|
||||
public DynamicMapTree()
|
||||
{
|
||||
impl = new DynTreeImpl();
|
||||
}
|
||||
public void insert(GameObjectModel mdl)
|
||||
{
|
||||
impl.insert(mdl);
|
||||
}
|
||||
|
||||
public void remove(GameObjectModel mdl)
|
||||
{
|
||||
impl.remove(mdl);
|
||||
}
|
||||
|
||||
public bool contains(GameObjectModel mdl)
|
||||
{
|
||||
return impl.contains(mdl);
|
||||
}
|
||||
|
||||
public void balance()
|
||||
{
|
||||
impl.balance();
|
||||
}
|
||||
int size()
|
||||
{
|
||||
return impl.size();
|
||||
}
|
||||
public void update(uint diff)
|
||||
{
|
||||
impl.update(diff);
|
||||
}
|
||||
|
||||
public bool getIntersectionTime(List<uint> phases, Ray ray, Vector3 endPos, float maxDist)
|
||||
{
|
||||
float distance = maxDist;
|
||||
DynamicTreeIntersectionCallback callback = new DynamicTreeIntersectionCallback(phases);
|
||||
impl.intersectRay(ray, callback, ref distance, endPos);
|
||||
if (callback.didHit())
|
||||
maxDist = distance;
|
||||
return callback.didHit();
|
||||
}
|
||||
|
||||
public bool getObjectHitPos(List<uint> phases, Vector3 startPos, Vector3 endPos, ref Vector3 resultHitPos, float modifyDist)
|
||||
{
|
||||
bool result = false;
|
||||
float maxDist = (endPos - startPos).magnitude();
|
||||
// valid map coords should *never ever* produce float overflow, but this would produce NaNs too
|
||||
Contract.Assert(maxDist < float.MaxValue);
|
||||
// prevent NaN values which can cause BIH intersection to enter infinite loop
|
||||
if (maxDist < 1e-10f)
|
||||
{
|
||||
resultHitPos = endPos;
|
||||
return false;
|
||||
}
|
||||
Vector3 dir = (endPos - startPos) / maxDist; // direction with length of 1
|
||||
Ray ray = new Ray(startPos, dir);
|
||||
float dist = maxDist;
|
||||
if (getIntersectionTime(phases, ray, endPos, dist))
|
||||
{
|
||||
resultHitPos = startPos + dir * dist;
|
||||
if (modifyDist < 0)
|
||||
{
|
||||
if ((resultHitPos - startPos).magnitude() > -modifyDist)
|
||||
resultHitPos += dir * modifyDist;
|
||||
else
|
||||
resultHitPos = startPos;
|
||||
}
|
||||
else
|
||||
resultHitPos += dir * modifyDist;
|
||||
|
||||
result = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
resultHitPos = endPos;
|
||||
result = false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public bool isInLineOfSight(Vector3 startPos, Vector3 endPos, List<uint> phases)
|
||||
{
|
||||
float maxDist = (endPos - startPos).magnitude();
|
||||
|
||||
if (!MathFunctions.fuzzyGt(maxDist, 0))
|
||||
return true;
|
||||
|
||||
Ray r = new Ray(startPos, (endPos - startPos) / maxDist);
|
||||
DynamicTreeIntersectionCallback callback = new DynamicTreeIntersectionCallback(phases);
|
||||
impl.intersectRay(r, callback, ref maxDist, endPos);
|
||||
|
||||
return !callback.didHit();
|
||||
}
|
||||
|
||||
public float getHeight(float x, float y, float z, float maxSearchDist, List<uint> phases)
|
||||
{
|
||||
Vector3 v = new Vector3(x, y, z + 0.5f);
|
||||
Ray r = new Ray(v, new Vector3(0, 0, -1));
|
||||
DynamicTreeIntersectionCallback callback = new DynamicTreeIntersectionCallback(phases);
|
||||
impl.intersectZAllignedRay(r, callback, ref maxSearchDist);
|
||||
|
||||
if (callback.didHit())
|
||||
return v.Z - maxSearchDist;
|
||||
else
|
||||
return float.NegativeInfinity;
|
||||
}
|
||||
}
|
||||
|
||||
public class DynTreeImpl : RegularGrid2D<GameObjectModel, BIHWrap<GameObjectModel>>
|
||||
{
|
||||
public DynTreeImpl()
|
||||
{
|
||||
rebalance_timer = new TimeTrackerSmall(200);
|
||||
unbalanced_times = 0;
|
||||
}
|
||||
|
||||
public override void insert(GameObjectModel mdl)
|
||||
{
|
||||
base.insert(mdl);
|
||||
++unbalanced_times;
|
||||
}
|
||||
|
||||
public override void remove(GameObjectModel mdl)
|
||||
{
|
||||
base.remove(mdl);
|
||||
++unbalanced_times;
|
||||
}
|
||||
|
||||
public override void balance()
|
||||
{
|
||||
base.balance();
|
||||
unbalanced_times = 0;
|
||||
}
|
||||
|
||||
public void update(uint difftime)
|
||||
{
|
||||
if (size() == 0)
|
||||
return;
|
||||
|
||||
rebalance_timer.Update((int)difftime);
|
||||
if (rebalance_timer.Passed())
|
||||
{
|
||||
rebalance_timer.Reset(200);
|
||||
if (unbalanced_times > 0)
|
||||
balance();
|
||||
}
|
||||
}
|
||||
|
||||
TimeTrackerSmall rebalance_timer;
|
||||
int unbalanced_times;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.Constants;
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public enum VMAPLoadResult
|
||||
{
|
||||
Error,
|
||||
OK,
|
||||
Ignored
|
||||
}
|
||||
|
||||
public class VMapManager : Singleton<VMapManager>
|
||||
{
|
||||
VMapManager() { }
|
||||
|
||||
public static string VMapPath = Global.WorldMgr.GetDataPath() + "/vmaps/";
|
||||
|
||||
public VMAPLoadResult loadMap(uint mapId, uint x, uint y)
|
||||
{
|
||||
var result = VMAPLoadResult.Ignored;
|
||||
if (_loadMap(mapId, x, y))
|
||||
result = VMAPLoadResult.OK;
|
||||
else
|
||||
result = VMAPLoadResult.Error;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool _loadMap(uint mapId, uint tileX, uint tileY)
|
||||
{
|
||||
var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
|
||||
if (instanceTree == null)
|
||||
{
|
||||
string filename = string.Format("{0}{1:D4}.vmtree", VMapPath, mapId);
|
||||
StaticMapTree newTree = new StaticMapTree(mapId);
|
||||
if (!newTree.InitMap(filename, this))
|
||||
return false;
|
||||
|
||||
iInstanceMapTrees.Add(mapId, newTree);
|
||||
|
||||
instanceTree = newTree;
|
||||
}
|
||||
|
||||
return instanceTree.LoadMapTile(tileX, tileY, this);
|
||||
}
|
||||
|
||||
public WorldModel acquireModelInstance(string filename)
|
||||
{
|
||||
var model = iLoadedModelFiles.LookupByKey(filename);
|
||||
if (model == null)
|
||||
{
|
||||
WorldModel worldmodel = new WorldModel();
|
||||
if (!worldmodel.readFile(VMapPath + filename + ".vmo"))
|
||||
{
|
||||
Log.outError(LogFilter.Server, "VMapManager: could not load '{0}.vmo'", filename);
|
||||
return null;
|
||||
}
|
||||
Log.outDebug(LogFilter.Maps, "VMapManager: loading file '{0}'", filename);
|
||||
iLoadedModelFiles.Add(filename, new ManagedModel());
|
||||
model = iLoadedModelFiles.LookupByKey(filename);
|
||||
model.setModel(worldmodel);
|
||||
}
|
||||
model.incRefCount();
|
||||
return model.getModel();
|
||||
}
|
||||
|
||||
public void releaseModelInstance(string filename)
|
||||
{
|
||||
var model = iLoadedModelFiles.LookupByKey(filename);
|
||||
if (model == null)
|
||||
{
|
||||
Log.outError(LogFilter.Server, "VMapManager: trying to unload non-loaded file '{0}'", filename);
|
||||
return;
|
||||
}
|
||||
if (model.decRefCount() == 0)
|
||||
{
|
||||
Log.outDebug(LogFilter.Maps, "VMapManager: unloading file '{0}'", filename);
|
||||
iLoadedModelFiles.Remove(filename);
|
||||
}
|
||||
}
|
||||
|
||||
public bool existsMap(uint mapId, uint x, uint y)
|
||||
{
|
||||
return StaticMapTree.CanLoadMap(VMapPath, mapId, x, y);
|
||||
}
|
||||
|
||||
public static string getMapFileName(uint mapId)
|
||||
{
|
||||
return string.Format("{0:D4}.vmtree", mapId);
|
||||
}
|
||||
|
||||
public bool GetLiquidLevel(uint mapId, float x, float y, float z, byte reqLiquidType, ref float level, ref float floor, ref uint type)
|
||||
{
|
||||
if (!Global.DisableMgr.IsDisabledFor(DisableType.VMAP, mapId, null, DisableFlags.VmapLiquidStatus))
|
||||
{
|
||||
var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
|
||||
if (instanceTree != null)
|
||||
{
|
||||
LocationInfo info = new LocationInfo();
|
||||
Vector3 pos = convertPositionToInternalRep(x, y, z);
|
||||
if (instanceTree.GetLocationInfo(pos, info))
|
||||
{
|
||||
floor = info.ground_Z;
|
||||
Contract.Assert(floor < float.MaxValue);
|
||||
type = info.hitModel.GetLiquidType(); // entry from LiquidType.dbc
|
||||
if (reqLiquidType != 0 && !Convert.ToBoolean(Global.DB2Mgr.GetLiquidFlags(type) & reqLiquidType))
|
||||
return false;
|
||||
if (info.hitInstance.GetLiquidLevel(pos, info, ref level))
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public float getHeight(uint mapId, float x, float y, float z, float maxSearchDist)
|
||||
{
|
||||
if (isHeightCalcEnabled() && !Global.DisableMgr.IsDisabledFor(DisableType.VMAP, mapId, null, DisableFlags.VmapHeight))
|
||||
{
|
||||
var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
|
||||
if (instanceTree != null)
|
||||
{
|
||||
Vector3 pos = convertPositionToInternalRep(x, y, z);
|
||||
float height = instanceTree.getHeight(pos, maxSearchDist);
|
||||
if (float.IsInfinity(height))
|
||||
height = MapConst.VMAPInvalidHeightValue; // No height
|
||||
|
||||
return height;
|
||||
}
|
||||
}
|
||||
|
||||
return MapConst.VMAPInvalidHeightValue;
|
||||
}
|
||||
|
||||
public bool getAreaInfo(uint mapId, float x, float y, ref float z, out uint flags, out int adtId, out int rootId, out int groupId)
|
||||
{
|
||||
flags = 0;
|
||||
adtId = 0;
|
||||
rootId = 0;
|
||||
groupId = 0;
|
||||
if (!Global.DisableMgr.IsDisabledFor(DisableType.VMAP, mapId, null, DisableFlags.VmapAreaFlag))
|
||||
{
|
||||
var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
|
||||
if (instanceTree != null)
|
||||
{
|
||||
Vector3 pos = convertPositionToInternalRep(x, y, z);
|
||||
bool result = instanceTree.getAreaInfo(ref pos, out flags, out adtId, out rootId, out groupId);
|
||||
// z is not touched by convertPositionToInternalRep(), so just copy
|
||||
z = pos.Z;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Vector3 convertPositionToInternalRep(float x, float y, float z)
|
||||
{
|
||||
Vector3 pos = new Vector3();
|
||||
float mid = 0.5f * 64.0f * 533.33333333f;
|
||||
pos.X = mid - x;
|
||||
pos.Y = mid - y;
|
||||
pos.Z = z;
|
||||
|
||||
return pos;
|
||||
}
|
||||
|
||||
public void setEnableLineOfSightCalc(bool pVal) { _enableLineOfSightCalc = pVal; }
|
||||
public void setEnableHeightCalc(bool pVal) { _enableHeightCalc = pVal; }
|
||||
|
||||
public bool isLineOfSightCalcEnabled() { return _enableLineOfSightCalc; }
|
||||
public bool isHeightCalcEnabled() { return _enableHeightCalc; }
|
||||
public bool isMapLoadingEnabled() { return _enableLineOfSightCalc || _enableHeightCalc; }
|
||||
|
||||
public bool getObjectHitPos(uint mapId, float x1, float y1, float z1, float x2, float y2, float z2, out float rx, out float ry, out float rz, float modifyDist)
|
||||
{
|
||||
if (isLineOfSightCalcEnabled() && !Global.DisableMgr.IsDisabledFor(DisableType.VMAP, mapId, null, DisableFlags.VmapLOS))
|
||||
{
|
||||
var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
|
||||
if (instanceTree != null)
|
||||
{
|
||||
Vector3 resultPos;
|
||||
Vector3 pos1 = convertPositionToInternalRep(x1, y1, z1);
|
||||
Vector3 pos2 = convertPositionToInternalRep(x2, y2, z2);
|
||||
bool result = instanceTree.getObjectHitPos(pos1, pos2, out resultPos, modifyDist);
|
||||
resultPos = convertPositionToInternalRep(resultPos.X, resultPos.Y, resultPos.Z);
|
||||
rx = resultPos.X;
|
||||
ry = resultPos.Y;
|
||||
rz = resultPos.Z;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
rx = x2;
|
||||
ry = y2;
|
||||
rz = z2;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool isInLineOfSight(uint mapId, float x1, float y1, float z1, float x2, float y2, float z2)
|
||||
{
|
||||
if (!isLineOfSightCalcEnabled() || Global.DisableMgr.IsDisabledFor(DisableType.VMAP, mapId, null, DisableFlags.VmapLOS))
|
||||
return true;
|
||||
|
||||
var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
|
||||
if (instanceTree != null)
|
||||
{
|
||||
Vector3 pos1 = convertPositionToInternalRep(x1, y1, z1);
|
||||
Vector3 pos2 = convertPositionToInternalRep(x2, y2, z2);
|
||||
if (pos1 != pos2)
|
||||
{
|
||||
return instanceTree.isInLineOfSight(pos1, pos2);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public void unloadMap(uint mapId)
|
||||
{
|
||||
var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
|
||||
if (instanceTree != null)
|
||||
{
|
||||
instanceTree.UnloadMap(this);
|
||||
if (instanceTree.numLoadedTiles() == 0)
|
||||
{
|
||||
iInstanceMapTrees.Remove(mapId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void unloadMap(uint mapId, uint x, uint y)
|
||||
{
|
||||
var instanceTree = iInstanceMapTrees.LookupByKey(mapId);
|
||||
if (instanceTree != null)
|
||||
{
|
||||
instanceTree.UnloadMapTile(x, y, this);
|
||||
if (instanceTree.numLoadedTiles() == 0)
|
||||
{
|
||||
iInstanceMapTrees.Remove(mapId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Dictionary<string, ManagedModel> iLoadedModelFiles = new Dictionary<string, ManagedModel>();
|
||||
Dictionary<uint, StaticMapTree> iInstanceMapTrees = new Dictionary<uint, StaticMapTree>();
|
||||
bool _enableLineOfSightCalc;
|
||||
bool _enableHeightCalc;
|
||||
}
|
||||
|
||||
public class ManagedModel
|
||||
{
|
||||
public ManagedModel()
|
||||
{
|
||||
iModel = null;
|
||||
iRefCount = 0;
|
||||
}
|
||||
|
||||
public void setModel(WorldModel model) { iModel = model; }
|
||||
public WorldModel getModel() { return iModel; }
|
||||
public void incRefCount() { ++iRefCount; }
|
||||
public int decRefCount() { return --iRefCount; }
|
||||
|
||||
WorldModel iModel;
|
||||
int iRefCount;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.Constants;
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.IO;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public class LocationInfo
|
||||
{
|
||||
public LocationInfo()
|
||||
{
|
||||
ground_Z = float.NegativeInfinity;
|
||||
}
|
||||
|
||||
public ModelInstance hitInstance;
|
||||
public GroupModel hitModel;
|
||||
public float ground_Z;
|
||||
}
|
||||
|
||||
public class AreaInfo
|
||||
{
|
||||
public AreaInfo()
|
||||
{
|
||||
ground_Z = float.NegativeInfinity;
|
||||
}
|
||||
|
||||
public bool result;
|
||||
public float ground_Z;
|
||||
public uint flags;
|
||||
public int adtId;
|
||||
public int rootId;
|
||||
public int groupId;
|
||||
}
|
||||
|
||||
public class StaticMapTree
|
||||
{
|
||||
public StaticMapTree(uint mapId)
|
||||
{
|
||||
iMapID = mapId;
|
||||
}
|
||||
|
||||
public bool InitMap(string fname, VMapManager vm)
|
||||
{
|
||||
Log.outDebug(LogFilter.Maps, "StaticMapTree.InitMap() : initializing StaticMapTree '{0}'", fname);
|
||||
bool success = false;
|
||||
if (!File.Exists(fname))
|
||||
return false;
|
||||
char tiled = '0';
|
||||
using (BinaryReader reader = new BinaryReader(new FileStream(fname, FileMode.Open, FileAccess.Read)))
|
||||
{
|
||||
var magic = reader.ReadStringFromChars(8);
|
||||
tiled = reader.ReadChar();
|
||||
var node = reader.ReadStringFromChars(4);
|
||||
|
||||
if (magic == MapConst.VMapMagic && node == "NODE" && iTree.readFromFile(reader))
|
||||
{
|
||||
iNTreeValues = iTree.primCount();
|
||||
iTreeValues = new ModelInstance[iNTreeValues];
|
||||
success = reader.ReadStringFromChars(4) == "GOBJ";
|
||||
}
|
||||
|
||||
iIsTiled = (tiled == 1);
|
||||
|
||||
// global model spawns
|
||||
// only non-tiled maps have them, and if so exactly one (so far at least...)
|
||||
ModelSpawn spawn;
|
||||
if (!iIsTiled && ModelSpawn.readFromFile(reader, out spawn))
|
||||
{
|
||||
WorldModel model = vm.acquireModelInstance(spawn.name);
|
||||
Log.outDebug(LogFilter.Maps, "StaticMapTree.InitMap() : loading {0}", spawn.name);
|
||||
if (model != null)
|
||||
{
|
||||
// assume that global model always is the first and only tree value (could be improved...)
|
||||
iTreeValues[0] = new ModelInstance(spawn, model);
|
||||
iLoadedSpawns[0] = 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
success = false;
|
||||
Log.outError(LogFilter.Server, "StaticMapTree.InitMap() : could not acquire WorldModel for '{0}'", spawn.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
public void UnloadMap(VMapManager vm)
|
||||
{
|
||||
foreach (var id in iLoadedSpawns)
|
||||
{
|
||||
iTreeValues[id.Key].setUnloaded();
|
||||
for (uint refCount = 0; refCount < id.Key; ++refCount)
|
||||
vm.releaseModelInstance(iTreeValues[id.Key].name);
|
||||
}
|
||||
iLoadedSpawns.Clear();
|
||||
iLoadedTiles.Clear();
|
||||
}
|
||||
|
||||
public bool LoadMapTile(uint tileX, uint tileY, VMapManager vm)
|
||||
{
|
||||
if (!iIsTiled)
|
||||
{
|
||||
// currently, core creates grids for all maps, whether it has terrain tiles or not
|
||||
// so we need "fake" tile loads to know when we can unload map geometry
|
||||
iLoadedTiles[packTileID(tileX, tileY)] = false;
|
||||
return true;
|
||||
}
|
||||
if (iTreeValues == null)
|
||||
{
|
||||
Log.outError(LogFilter.Server, "StaticMapTree.LoadMapTile() : tree has not been initialized [{0}, {1}]", tileX, tileY);
|
||||
return false;
|
||||
}
|
||||
bool result = true;
|
||||
|
||||
string tilefile = VMapManager.VMapPath + getTileFileName(iMapID, tileX, tileY);
|
||||
|
||||
if (!File.Exists(tilefile))
|
||||
{
|
||||
iLoadedTiles[packTileID(tileX, tileY)] = false;
|
||||
}
|
||||
else
|
||||
{
|
||||
using (BinaryReader reader = new BinaryReader(new FileStream(tilefile, FileMode.Open, FileAccess.Read)))
|
||||
{
|
||||
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
|
||||
return false;
|
||||
|
||||
uint numSpawns = reader.ReadUInt32();
|
||||
|
||||
for (uint i = 0; i < numSpawns && result; ++i)
|
||||
{
|
||||
// read model spawns
|
||||
ModelSpawn spawn;
|
||||
result = ModelSpawn.readFromFile(reader, out spawn);
|
||||
if (result)
|
||||
{
|
||||
// acquire model instance
|
||||
WorldModel model = vm.acquireModelInstance(spawn.name);
|
||||
if (model == null)
|
||||
Log.outError(LogFilter.Server, "StaticMapTree.LoadMapTile() : could not acquire WorldModel [{0}, {1}]", tileX, tileY);
|
||||
|
||||
// update tree
|
||||
uint referencedVal = reader.ReadUInt32();
|
||||
if (!iLoadedSpawns.ContainsKey(referencedVal))
|
||||
{
|
||||
iTreeValues[referencedVal] = new ModelInstance(spawn, model);
|
||||
iLoadedSpawns[referencedVal] = 1;
|
||||
}
|
||||
else
|
||||
++iLoadedSpawns[referencedVal];
|
||||
|
||||
}
|
||||
else
|
||||
result = false;
|
||||
}
|
||||
}
|
||||
iLoadedTiles[packTileID(tileX, tileY)] = true;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public void UnloadMapTile(uint tileX, uint tileY, VMapManager vm)
|
||||
{
|
||||
uint tileID = packTileID(tileX, tileY);
|
||||
var tile = iLoadedTiles.LookupByKey(tileID);
|
||||
if (!iLoadedTiles.ContainsKey(tileID))
|
||||
{
|
||||
Log.outError(LogFilter.Server, "StaticMapTree.UnloadMapTile() : trying to unload non-loaded tile - Map:{0} X:{1} Y:{2}", iMapID, tileX, tileY);
|
||||
return;
|
||||
}
|
||||
if (tile) // file associated with tile
|
||||
{
|
||||
string tilefile = VMapManager.VMapPath + getTileFileName(iMapID, tileX, tileY);
|
||||
using (BinaryReader reader = new BinaryReader(new FileStream(tilefile, FileMode.Open, FileAccess.Read)))
|
||||
{
|
||||
bool result = true;
|
||||
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
|
||||
result = false;
|
||||
|
||||
uint numSpawns = reader.ReadUInt32();
|
||||
for (uint i = 0; i < numSpawns && result; ++i)
|
||||
{
|
||||
// read model spawns
|
||||
ModelSpawn spawn;
|
||||
result = ModelSpawn.readFromFile(reader, out spawn);
|
||||
if (result)
|
||||
{
|
||||
// release model instance
|
||||
vm.releaseModelInstance(spawn.name);
|
||||
|
||||
// update tree
|
||||
uint referencedNode = reader.ReadUInt32();
|
||||
|
||||
|
||||
if (!iLoadedSpawns.ContainsKey(referencedNode))
|
||||
Log.outError(LogFilter.Server, "StaticMapTree.UnloadMapTile() : trying to unload non-referenced model '{0}' (ID:{1})", spawn.name, spawn.ID);
|
||||
else if (--iLoadedSpawns[referencedNode] == 0)
|
||||
{
|
||||
iTreeValues[referencedNode].setUnloaded();
|
||||
iLoadedSpawns.Remove(referencedNode);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
iLoadedTiles.Remove(tileID);
|
||||
}
|
||||
|
||||
static uint packTileID(uint tileX, uint tileY) { return tileX << 16 | tileY; }
|
||||
static void unpackTileID(uint ID, ref uint tileX, ref uint tileY) { tileX = ID >> 16; tileY = ID & 0xFF; }
|
||||
public static bool CanLoadMap(string vmapPath, uint mapID, uint tileX, uint tileY)
|
||||
{
|
||||
string fullname = vmapPath + VMapManager.getMapFileName(mapID);
|
||||
bool success = true;
|
||||
if (!File.Exists(fullname))
|
||||
return false;
|
||||
|
||||
using (BinaryReader reader = new BinaryReader(new FileStream(fullname, FileMode.Open, FileAccess.Read)))
|
||||
{
|
||||
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
|
||||
return false;
|
||||
char tiled = reader.ReadChar();
|
||||
if (tiled == 1)
|
||||
{
|
||||
string tilefile = vmapPath + getTileFileName(mapID, tileX, tileY);
|
||||
if (!File.Exists(tilefile))
|
||||
return false;
|
||||
|
||||
using (BinaryReader reader1 = new BinaryReader(new FileStream(tilefile, FileMode.Open, FileAccess.Read)))
|
||||
{
|
||||
if (reader1.ReadStringFromChars(8) != MapConst.VMapMagic)
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return success;
|
||||
}
|
||||
public static string getTileFileName(uint mapID, uint tileX, uint tileY)
|
||||
{
|
||||
return string.Format("{0:D4}_{1:D2}_{2:D2}.vmtile", mapID, tileY, tileX);
|
||||
}
|
||||
|
||||
public bool getAreaInfo(ref Vector3 pos, out uint flags, out int adtId, out int rootId, out int groupId)
|
||||
{
|
||||
flags = 0;
|
||||
adtId = 0;
|
||||
rootId = 0;
|
||||
groupId = 0;
|
||||
|
||||
AreaInfoCallback intersectionCallBack = new AreaInfoCallback(iTreeValues);
|
||||
iTree.intersectPoint(pos, intersectionCallBack);
|
||||
if (intersectionCallBack.aInfo.result)
|
||||
{
|
||||
flags = intersectionCallBack.aInfo.flags;
|
||||
adtId = intersectionCallBack.aInfo.adtId;
|
||||
rootId = intersectionCallBack.aInfo.rootId;
|
||||
groupId = intersectionCallBack.aInfo.groupId;
|
||||
pos.Z = intersectionCallBack.aInfo.ground_Z;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool GetLocationInfo(Vector3 pos, LocationInfo info)
|
||||
{
|
||||
LocationInfoCallback intersectionCallBack = new LocationInfoCallback(iTreeValues, info);
|
||||
iTree.intersectPoint(pos, intersectionCallBack);
|
||||
return intersectionCallBack.result;
|
||||
}
|
||||
|
||||
public float getHeight(Vector3 pPos, float maxSearchDist)
|
||||
{
|
||||
float height = float.PositiveInfinity;
|
||||
Vector3 dir = new Vector3(0, 0, -1);
|
||||
Ray ray = new Ray(pPos, dir); // direction with length of 1
|
||||
float maxDist = maxSearchDist;
|
||||
if (getIntersectionTime(ray, ref maxDist, false))
|
||||
height = pPos.Z - maxDist;
|
||||
|
||||
return height;
|
||||
}
|
||||
bool getIntersectionTime(Ray pRay, ref float pMaxDist, bool pStopAtFirstHit)
|
||||
{
|
||||
float distance = pMaxDist;
|
||||
MapRayCallback intersectionCallBack = new MapRayCallback(iTreeValues);
|
||||
iTree.intersectRay(pRay, intersectionCallBack, ref distance, pStopAtFirstHit);
|
||||
if (intersectionCallBack.didHit())
|
||||
pMaxDist = distance;
|
||||
return intersectionCallBack.didHit();
|
||||
}
|
||||
|
||||
public bool getObjectHitPos(Vector3 pPos1, Vector3 pPos2, out Vector3 pResultHitPos, float pModifyDist)
|
||||
{
|
||||
bool result = false;
|
||||
float maxDist = (pPos2 - pPos1).magnitude();
|
||||
// valid map coords should *never ever* produce float overflow, but this would produce NaNs too
|
||||
Contract.Assert(maxDist < float.MaxValue);
|
||||
// prevent NaN values which can cause BIH intersection to enter infinite loop
|
||||
if (maxDist < 1e-10f)
|
||||
{
|
||||
pResultHitPos = pPos2;
|
||||
return false;
|
||||
}
|
||||
Vector3 dir = (pPos2 - pPos1) / maxDist; // direction with length of 1
|
||||
Ray ray = new Ray(pPos1, dir);
|
||||
float dist = maxDist;
|
||||
if (getIntersectionTime(ray, ref dist, false))
|
||||
{
|
||||
pResultHitPos = pPos1 + dir * dist;
|
||||
if (pModifyDist < 0)
|
||||
{
|
||||
if ((pResultHitPos - pPos1).magnitude() > -pModifyDist)
|
||||
{
|
||||
pResultHitPos = pResultHitPos + dir * pModifyDist;
|
||||
}
|
||||
else
|
||||
{
|
||||
pResultHitPos = pPos1;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
pResultHitPos = pResultHitPos + dir * pModifyDist;
|
||||
}
|
||||
result = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
pResultHitPos = pPos2;
|
||||
result = false;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public bool isInLineOfSight(Vector3 pos1, Vector3 pos2)
|
||||
{
|
||||
float maxDist = (pos2 - pos1).magnitude();
|
||||
// return false if distance is over max float, in case of cheater teleporting to the end of the universe
|
||||
if (maxDist == float.MaxValue ||
|
||||
maxDist == float.PositiveInfinity)
|
||||
return false;
|
||||
|
||||
// valid map coords should *never ever* produce float overflow, but this would produce NaNs too
|
||||
Contract.Assert(maxDist < float.MaxValue);
|
||||
// prevent NaN values which can cause BIH intersection to enter infinite loop
|
||||
if (maxDist < 1e-10f)
|
||||
return true;
|
||||
// direction with length of 1
|
||||
Ray ray = new Ray(pos1, (pos2 - pos1) / maxDist);
|
||||
if (getIntersectionTime(ray, ref maxDist, true))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public int numLoadedTiles() { return iLoadedTiles.Count; }
|
||||
|
||||
uint iMapID;
|
||||
bool iIsTiled;
|
||||
BIH iTree = new BIH();
|
||||
ModelInstance[] iTreeValues;
|
||||
uint iNTreeValues;
|
||||
|
||||
Dictionary<uint, bool> iLoadedTiles = new Dictionary<uint, bool>();
|
||||
Dictionary<uint, uint> iLoadedSpawns = new Dictionary<uint, uint>();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public class StaticModelList
|
||||
{
|
||||
public static Dictionary<uint, GameobjectModelData> models = new Dictionary<uint, GameobjectModelData>();
|
||||
}
|
||||
|
||||
public class GameObjectModelOwnerBase
|
||||
{
|
||||
public virtual bool IsSpawned() { return false; }
|
||||
public virtual uint GetDisplayId() { return 0; }
|
||||
public virtual bool IsInPhase(List<uint> phases) { return false; }
|
||||
public virtual Vector3 GetPosition() { return Vector3.Zero; }
|
||||
public virtual float GetOrientation() { return 0.0f; }
|
||||
public virtual float GetScale() { return 1.0f; }
|
||||
public virtual void DebugVisualizeCorner(Vector3 corner) { }
|
||||
}
|
||||
|
||||
public class GameObjectModel : IModel
|
||||
{
|
||||
bool initialize(GameObjectModelOwnerBase modelOwner)
|
||||
{
|
||||
var it = StaticModelList.models.LookupByKey(modelOwner.GetDisplayId());
|
||||
if (it == null)
|
||||
return false;
|
||||
|
||||
AxisAlignedBox mdl_box = new AxisAlignedBox(it.bound);
|
||||
// ignore models with no bounds
|
||||
if (mdl_box == AxisAlignedBox.Zero())
|
||||
{
|
||||
Log.outError(LogFilter.Server, "GameObject model {0} has zero bounds, loading skipped", it.name);
|
||||
return false;
|
||||
}
|
||||
|
||||
iModel = Global.VMapMgr.acquireModelInstance(it.name);
|
||||
|
||||
if (iModel == null)
|
||||
return false;
|
||||
|
||||
name = it.name;
|
||||
iPos = modelOwner.GetPosition();
|
||||
iScale = modelOwner.GetScale();
|
||||
iInvScale = 1.0f / iScale;
|
||||
|
||||
Matrix3 iRotation = Matrix3.fromEulerAnglesZYX(modelOwner.GetOrientation(), 0, 0);
|
||||
iInvRot = iRotation.inverse();
|
||||
// transform bounding box:
|
||||
mdl_box = new AxisAlignedBox(mdl_box.Lo * iScale, mdl_box.Hi * iScale);
|
||||
AxisAlignedBox rotated_bounds = new AxisAlignedBox();
|
||||
for (int i = 0; i < 8; ++i)
|
||||
rotated_bounds.merge(iRotation * mdl_box.corner(i));
|
||||
|
||||
iBound = rotated_bounds + iPos;
|
||||
owner = modelOwner;
|
||||
return true;
|
||||
}
|
||||
|
||||
public static GameObjectModel Create(GameObjectModelOwnerBase modelOwner)
|
||||
{
|
||||
GameObjectModel mdl = new GameObjectModel();
|
||||
if (!mdl.initialize(modelOwner))
|
||||
return null;
|
||||
|
||||
return mdl;
|
||||
}
|
||||
|
||||
public bool intersectRay(Ray ray, ref float maxDist, bool stopAtFirstHit, List<uint> phases)
|
||||
{
|
||||
if (!isCollisionEnabled() || !owner.IsSpawned())
|
||||
return false;
|
||||
|
||||
if (!owner.IsInPhase(phases))
|
||||
return false;
|
||||
|
||||
float time = ray.intersectionTime(iBound);
|
||||
if (time == float.PositiveInfinity)
|
||||
return false;
|
||||
|
||||
// child bounds are defined in object space:
|
||||
Vector3 p = iInvRot * (ray.Origin - iPos) * iInvScale;
|
||||
Ray modRay = new Ray(p, iInvRot * ray.Direction);
|
||||
float distance = maxDist * iInvScale;
|
||||
bool hit = iModel.IntersectRay(modRay, ref distance, stopAtFirstHit);
|
||||
if (hit)
|
||||
{
|
||||
distance *= iScale;
|
||||
maxDist = distance;
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
public bool UpdatePosition()
|
||||
{
|
||||
if (iModel == null)
|
||||
return false;
|
||||
|
||||
var it = StaticModelList.models.LookupByKey(owner.GetDisplayId());
|
||||
if (it == null)
|
||||
return false;
|
||||
|
||||
AxisAlignedBox mdl_box = new AxisAlignedBox(it.bound);
|
||||
// ignore models with no bounds
|
||||
if (mdl_box == AxisAlignedBox.Zero())
|
||||
{
|
||||
Log.outError(LogFilter.Server, "GameObject model {0} has zero bounds, loading skipped", it.name);
|
||||
return false;
|
||||
}
|
||||
|
||||
iPos = owner.GetPosition();
|
||||
|
||||
Matrix3 iRotation = Matrix3.fromEulerAnglesZYX(owner.GetOrientation(), 0, 0);
|
||||
iInvRot = iRotation.inverse();
|
||||
// transform bounding box:
|
||||
mdl_box = new AxisAlignedBox(mdl_box.Lo * iScale, mdl_box.Hi * iScale);
|
||||
AxisAlignedBox rotated_bounds = new AxisAlignedBox();
|
||||
for (int i = 0; i < 8; ++i)
|
||||
rotated_bounds.merge(iRotation * mdl_box.corner(i));
|
||||
|
||||
iBound = rotated_bounds + iPos;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public override Vector3 getPosition() { return iPos; }
|
||||
public override AxisAlignedBox getBounds() { return iBound; }
|
||||
|
||||
public void enableCollision(bool enable) { _collisionEnabled = enable; }
|
||||
bool isCollisionEnabled() { return _collisionEnabled; }
|
||||
|
||||
public static void LoadGameObjectModelList()
|
||||
{
|
||||
uint oldMSTime = Time.GetMSTime();
|
||||
var filename = Global.WorldMgr.GetDataPath() + "/vmaps/GameObjectModels.dtree";
|
||||
if (!File.Exists(filename))
|
||||
{
|
||||
Log.outError(LogFilter.Server, "Unable to open '{0}' file.", filename);
|
||||
return;
|
||||
}
|
||||
try
|
||||
{
|
||||
using (BinaryReader reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
|
||||
{
|
||||
uint name_length, displayId;
|
||||
string name;
|
||||
while (true)
|
||||
{
|
||||
if (reader.BaseStream.Position >= reader.BaseStream.Length)
|
||||
break;
|
||||
|
||||
Vector3 v1, v2;
|
||||
displayId = reader.ReadUInt32();
|
||||
name_length = reader.ReadUInt32();
|
||||
name = reader.ReadString((int)name_length);
|
||||
v1 = reader.ReadStruct<Vector3>();
|
||||
v2 = reader.ReadStruct<Vector3>();
|
||||
|
||||
StaticModelList.models.Add(displayId, new GameobjectModelData(name, new AxisAlignedBox(v1, v2)));
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (EndOfStreamException ex)
|
||||
{
|
||||
Log.outException(ex);
|
||||
}
|
||||
|
||||
Log.outInfo(LogFilter.ServerLoading, "Loaded {0} GameObject models in {1} ms", StaticModelList.models.Count, Time.GetMSTimeDiffToNow(oldMSTime));
|
||||
}
|
||||
|
||||
string name;
|
||||
bool _collisionEnabled;
|
||||
AxisAlignedBox iBound;
|
||||
Matrix3 iInvRot;
|
||||
Vector3 iPos;
|
||||
float iInvScale;
|
||||
float iScale;
|
||||
WorldModel iModel;
|
||||
GameObjectModelOwnerBase owner;
|
||||
}
|
||||
public class GameobjectModelData
|
||||
{
|
||||
public GameobjectModelData(string name_, AxisAlignedBox box)
|
||||
{
|
||||
bound = box;
|
||||
name = name_;
|
||||
}
|
||||
|
||||
public AxisAlignedBox bound;
|
||||
public string name;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.GameMath;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public class IModel
|
||||
{
|
||||
public virtual Vector3 getPosition() { return default(Vector3); }
|
||||
public virtual AxisAlignedBox getBounds() { return default(AxisAlignedBox); }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.IO;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public enum ModelFlags
|
||||
{
|
||||
M2 = 1,
|
||||
WorldSpawn = 1 << 1,
|
||||
HasBound = 1 << 2
|
||||
}
|
||||
|
||||
public class ModelSpawn
|
||||
{
|
||||
public ModelSpawn() { }
|
||||
public ModelSpawn(ModelSpawn spawn)
|
||||
{
|
||||
flags = spawn.flags;
|
||||
adtId = spawn.adtId;
|
||||
ID = spawn.ID;
|
||||
iPos = spawn.iPos;
|
||||
iRot = spawn.iRot;
|
||||
iScale = spawn.iScale;
|
||||
iBound = spawn.iBound;
|
||||
name = spawn.name;
|
||||
}
|
||||
|
||||
public static bool readFromFile(BinaryReader reader, out ModelSpawn spawn)
|
||||
{
|
||||
spawn = new ModelSpawn();
|
||||
|
||||
spawn.flags = reader.ReadUInt32();
|
||||
spawn.adtId = reader.ReadUInt16();
|
||||
spawn.ID = reader.ReadUInt32();
|
||||
spawn.iPos = reader.ReadStruct<Vector3>();
|
||||
spawn.iRot = reader.ReadStruct<Vector3>();
|
||||
spawn.iScale = reader.ReadSingle();
|
||||
|
||||
bool has_bound = Convert.ToBoolean(spawn.flags & (uint)ModelFlags.HasBound);
|
||||
if (has_bound) // only WMOs have bound in MPQ, only available after computation
|
||||
{
|
||||
Vector3 bLow = reader.ReadStruct<Vector3>();
|
||||
Vector3 bHigh = reader.ReadStruct<Vector3>();
|
||||
spawn.iBound = new AxisAlignedBox(bLow, bHigh);
|
||||
}
|
||||
uint nameLen = reader.ReadUInt32();
|
||||
|
||||
spawn.name = reader.ReadString((int)nameLen);
|
||||
return true;
|
||||
}
|
||||
|
||||
public uint flags;
|
||||
public ushort adtId;
|
||||
public uint ID;
|
||||
public Vector3 iPos;
|
||||
public Vector3 iRot;
|
||||
public float iScale;
|
||||
public AxisAlignedBox iBound;
|
||||
public string name;
|
||||
}
|
||||
|
||||
public class ModelInstance : ModelSpawn
|
||||
{
|
||||
public ModelInstance()
|
||||
{
|
||||
iInvScale = 0.0f;
|
||||
iModel = null;
|
||||
}
|
||||
public ModelInstance(ModelSpawn spawn, WorldModel model)
|
||||
: base(spawn)
|
||||
{
|
||||
iModel = model;
|
||||
|
||||
iInvRot = Matrix3.fromEulerAnglesZYX(MathFunctions.PI * iRot.Y / 180.0f, MathFunctions.PI * iRot.X / 180.0f, MathFunctions.PI * iRot.Z / 180.0f).inverse();
|
||||
iInvScale = 1.0f / iScale;
|
||||
}
|
||||
|
||||
public bool intersectRay(Ray pRay, ref float pMaxDist, bool pStopAtFirstHit)
|
||||
{
|
||||
if (iModel == null)
|
||||
return false;
|
||||
|
||||
float time = pRay.intersectionTime(iBound);
|
||||
if (float.IsInfinity(time))
|
||||
return false;
|
||||
|
||||
// child bounds are defined in object space:
|
||||
Vector3 p = iInvRot * (pRay.Origin - iPos) * iInvScale;
|
||||
Ray modRay = new Ray(p, iInvRot * pRay.Direction);
|
||||
float distance = pMaxDist * iInvScale;
|
||||
bool hit = iModel.IntersectRay(modRay, ref distance, pStopAtFirstHit);
|
||||
if (hit)
|
||||
{
|
||||
distance *= iScale;
|
||||
pMaxDist = distance;
|
||||
}
|
||||
return hit;
|
||||
}
|
||||
|
||||
public void intersectPoint(Vector3 p, AreaInfo info)
|
||||
{
|
||||
if (iModel == null)
|
||||
return;
|
||||
|
||||
// M2 files don't contain area info, only WMO files
|
||||
if (Convert.ToBoolean(flags & (uint)ModelFlags.M2))
|
||||
return;
|
||||
if (!iBound.contains(p))
|
||||
return;
|
||||
// child bounds are defined in object space:
|
||||
Vector3 pModel = iInvRot * (p - iPos) * iInvScale;
|
||||
Vector3 zDirModel = iInvRot * new Vector3(0.0f, 0.0f, -1.0f);
|
||||
float zDist;
|
||||
if (iModel.IntersectPoint(pModel, zDirModel, out zDist, info))
|
||||
{
|
||||
Vector3 modelGround = pModel + zDist * zDirModel;
|
||||
// Transform back to world space. Note that:
|
||||
// Mat * vec == vec * Mat.transpose()
|
||||
// and for rotation matrices: Mat.inverse() == Mat.transpose()
|
||||
float world_Z = ((modelGround * iInvRot) * iScale + iPos).Z;
|
||||
if (info.ground_Z < world_Z)
|
||||
{
|
||||
info.ground_Z = world_Z;
|
||||
info.adtId = adtId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool GetLiquidLevel(Vector3 p, LocationInfo info, ref float liqHeight)
|
||||
{
|
||||
// child bounds are defined in object space:
|
||||
Vector3 pModel = iInvRot * (p - iPos) * iInvScale;
|
||||
//Vector3 zDirModel = iInvRot * Vector3(0.f, 0.f, -1.f);
|
||||
float zDist;
|
||||
if (info.hitModel.GetLiquidLevel(pModel, out zDist))
|
||||
{
|
||||
// calculate world height (zDist in model coords):
|
||||
// assume WMO not tilted (wouldn't make much sense anyway)
|
||||
liqHeight = zDist * iScale + iPos.Z;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool GetLocationInfo(Vector3 p, LocationInfo info)
|
||||
{
|
||||
if (iModel == null)
|
||||
return false;
|
||||
|
||||
// M2 files don't contain area info, only WMO files
|
||||
if (Convert.ToBoolean(flags & (uint)ModelFlags.M2))
|
||||
return false;
|
||||
if (!iBound.contains(p))
|
||||
return false;
|
||||
// child bounds are defined in object space:
|
||||
Vector3 pModel = iInvRot * (p - iPos) * iInvScale;
|
||||
Vector3 zDirModel = iInvRot * new Vector3(0.0f, 0.0f, -1.0f);
|
||||
float zDist;
|
||||
if (iModel.GetLocationInfo(pModel, zDirModel, out zDist, info))
|
||||
{
|
||||
Vector3 modelGround = pModel + zDist * zDirModel;
|
||||
// Transform back to world space. Note that:
|
||||
// Mat * vec == vec * Mat.transpose()
|
||||
// and for rotation matrices: Mat.inverse() == Mat.transpose()
|
||||
float world_Z = ((modelGround * iInvRot) * iScale + iPos).Z;
|
||||
if (info.ground_Z < world_Z) // hm...could it be handled automatically with zDist at intersection?
|
||||
{
|
||||
info.ground_Z = world_Z;
|
||||
info.hitInstance = this;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
public void setUnloaded() { iModel = null; }
|
||||
|
||||
Matrix3 iInvRot;
|
||||
float iInvScale;
|
||||
WorldModel iModel;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,405 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.Constants;
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public struct MeshTriangle
|
||||
{
|
||||
public MeshTriangle(uint na, uint nb, uint nc)
|
||||
{
|
||||
idx0 = na;
|
||||
idx1 = nb;
|
||||
idx2 = nc;
|
||||
}
|
||||
|
||||
public uint idx0;
|
||||
public uint idx1;
|
||||
public uint idx2;
|
||||
}
|
||||
|
||||
public class WmoLiquid
|
||||
{
|
||||
public WmoLiquid() { }
|
||||
public WmoLiquid(uint width, uint height, Vector3 corner, uint type)
|
||||
{
|
||||
iTilesX = width;
|
||||
iTilesY = height;
|
||||
iCorner = corner;
|
||||
iType = type;
|
||||
|
||||
iHeight = new float[(width + 1) * (height + 1)];
|
||||
iFlags = new byte[width * height];
|
||||
}
|
||||
public WmoLiquid(WmoLiquid other)
|
||||
{
|
||||
if (this == other)
|
||||
return;
|
||||
|
||||
iTilesX = other.iTilesX;
|
||||
iTilesY = other.iTilesY;
|
||||
iCorner = other.iCorner;
|
||||
iType = other.iType;
|
||||
if (other.iHeight != null)
|
||||
{
|
||||
iHeight = new float[(iTilesX + 1) * (iTilesY + 1)];
|
||||
Buffer.BlockCopy(other.iHeight, 0, iHeight, 0, (int)((iTilesX + 1) * (iTilesY + 1)));
|
||||
}
|
||||
else
|
||||
iHeight = null;
|
||||
if (other.iFlags != null)
|
||||
{
|
||||
iFlags = new byte[iTilesX * iTilesY];
|
||||
Buffer.BlockCopy(other.iFlags, 0, iFlags, 0, (int)(iTilesX * iTilesY));
|
||||
}
|
||||
else
|
||||
iFlags = null;
|
||||
}
|
||||
|
||||
public bool GetLiquidHeight(Vector3 pos, out float liqHeight)
|
||||
{
|
||||
liqHeight = 0f;
|
||||
float tx_f = (pos.X - iCorner.X) / MapConst.LiquidTileSize;
|
||||
uint tx = (uint)tx_f;
|
||||
if (tx_f < 0.0f || tx >= iTilesX)
|
||||
return false;
|
||||
float ty_f = (pos.Y - iCorner.Y) / MapConst.LiquidTileSize;
|
||||
uint ty = (uint)ty_f;
|
||||
if (ty_f < 0.0f || ty >= iTilesY)
|
||||
return false;
|
||||
|
||||
// check if tile shall be used for liquid level
|
||||
// checking for 0x08 *might* be enough, but disabled tiles always are 0x?F:
|
||||
if ((iFlags[tx + ty * iTilesX] & 0x0F) == 0x0F)
|
||||
return false;
|
||||
|
||||
// (dx, dy) coordinates inside tile, in [0, 1]^2
|
||||
float dx = tx_f - tx;
|
||||
float dy = ty_f - ty;
|
||||
|
||||
uint rowOffset = iTilesX + 1;
|
||||
if (dx > dy) // case (a)
|
||||
{
|
||||
float sx = iHeight[tx + 1 + ty * rowOffset] - iHeight[tx + ty * rowOffset];
|
||||
float sy = iHeight[tx + 1 + (ty + 1) * rowOffset] - iHeight[tx + 1 + ty * rowOffset];
|
||||
liqHeight = iHeight[tx + ty * rowOffset] + dx * sx + dy * sy;
|
||||
}
|
||||
else // case (b)
|
||||
{
|
||||
float sx = iHeight[tx + 1 + (ty + 1) * rowOffset] - iHeight[tx + (ty + 1) * rowOffset];
|
||||
float sy = iHeight[tx + (ty + 1) * rowOffset] - iHeight[tx + ty * rowOffset];
|
||||
liqHeight = iHeight[tx + ty * rowOffset] + dx * sx + dy * sy;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool writeToFile(BinaryWriter writer)
|
||||
{
|
||||
writer.Write(iTilesX);
|
||||
writer.Write(iTilesY);
|
||||
|
||||
writer.Write(iCorner.X);
|
||||
writer.Write(iCorner.Y);
|
||||
writer.Write(iCorner.Z);
|
||||
writer.Write(iType);
|
||||
|
||||
uint size = (iTilesX + 1) * (iTilesY + 1);
|
||||
for (var i = 0; i < size; i++)
|
||||
writer.Write(iHeight[i]);
|
||||
|
||||
size = iTilesX * iTilesY;
|
||||
for (var i = 0; i < size; i++)
|
||||
writer.Write(iFlags[0]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public static WmoLiquid readFromFile(BinaryReader reader)
|
||||
{
|
||||
WmoLiquid liquid = new WmoLiquid();
|
||||
|
||||
liquid.iTilesX = reader.ReadUInt32();
|
||||
liquid.iTilesY = reader.ReadUInt32();
|
||||
liquid.iCorner = reader.ReadStruct<Vector3>();
|
||||
liquid.iType = reader.ReadUInt32();
|
||||
|
||||
uint size = (liquid.iTilesX + 1) * (liquid.iTilesY + 1);
|
||||
liquid.iHeight = new float[size];
|
||||
for (var i = 0; i < size; i++)
|
||||
liquid.iHeight[i] = reader.ReadSingle();
|
||||
|
||||
size = liquid.iTilesX * liquid.iTilesY;
|
||||
liquid.iFlags = new byte[size];
|
||||
for (var i = 0; i < size; i++)
|
||||
liquid.iFlags[i] = reader.ReadByte();
|
||||
|
||||
return liquid;
|
||||
}
|
||||
|
||||
public uint GetLiquidType() { return iType; }
|
||||
float[] GetHeightStorage() { return iHeight; }
|
||||
byte[] GetFlagsStorage() { return iFlags; }
|
||||
|
||||
uint iTilesX;
|
||||
uint iTilesY;
|
||||
Vector3 iCorner;
|
||||
uint iType;
|
||||
float[] iHeight;
|
||||
byte[] iFlags;
|
||||
}
|
||||
|
||||
public class GroupModel : IModel
|
||||
{
|
||||
public GroupModel()
|
||||
{
|
||||
iLiquid = null;
|
||||
}
|
||||
public GroupModel(GroupModel other)
|
||||
{
|
||||
iBound = other.iBound;
|
||||
iMogpFlags = other.iMogpFlags;
|
||||
iGroupWMOID = other.iGroupWMOID;
|
||||
vertices = other.vertices;
|
||||
triangles = other.triangles;
|
||||
meshTree = other.meshTree;
|
||||
iLiquid = null;
|
||||
|
||||
if (other.iLiquid != null)
|
||||
iLiquid = new WmoLiquid(other.iLiquid);
|
||||
}
|
||||
public GroupModel(uint mogpFlags, uint groupWMOID, AxisAlignedBox bound)
|
||||
{
|
||||
iBound = bound;
|
||||
iMogpFlags = mogpFlags;
|
||||
iGroupWMOID = groupWMOID;
|
||||
iLiquid = null;
|
||||
}
|
||||
|
||||
void setLiquidData(WmoLiquid liquid)
|
||||
{
|
||||
iLiquid = liquid;
|
||||
liquid = null;
|
||||
}
|
||||
|
||||
public bool readFromFile(BinaryReader reader)
|
||||
{
|
||||
uint chunkSize = 0;
|
||||
uint count = 0;
|
||||
triangles.Clear();
|
||||
vertices.Clear();
|
||||
iLiquid = null;
|
||||
|
||||
iBound = reader.ReadStruct<AxisAlignedBox>();
|
||||
iMogpFlags = reader.ReadUInt32();
|
||||
iGroupWMOID = reader.ReadUInt32();
|
||||
|
||||
// read vertices
|
||||
if (reader.ReadStringFromChars(4) != "VERT")
|
||||
return false;
|
||||
|
||||
chunkSize = reader.ReadUInt32();
|
||||
count = reader.ReadUInt32();
|
||||
if (count == 0)
|
||||
return false;
|
||||
|
||||
for (var i = 0; i < count; ++i)
|
||||
vertices.Add(reader.ReadStruct<Vector3>());
|
||||
|
||||
// read triangle mesh
|
||||
if (reader.ReadStringFromChars(4) != "TRIM")
|
||||
return false;
|
||||
|
||||
chunkSize = reader.ReadUInt32();
|
||||
count = reader.ReadUInt32();
|
||||
|
||||
for (var i = 0; i < count; ++i)
|
||||
triangles.Add(reader.ReadStruct<MeshTriangle>());
|
||||
|
||||
// read mesh BIH
|
||||
if (reader.ReadStringFromChars(4) != "MBIH")
|
||||
return false;
|
||||
meshTree.readFromFile(reader);
|
||||
|
||||
// write liquid data
|
||||
if (reader.ReadStringFromChars(4).ToString() != "LIQU")
|
||||
return false;
|
||||
chunkSize = reader.ReadUInt32();
|
||||
if (chunkSize > 0)
|
||||
iLiquid = WmoLiquid.readFromFile(reader);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
public bool IntersectRay(Ray ray, ref float distance, bool stopAtFirstHit)
|
||||
{
|
||||
if (triangles.Empty())
|
||||
return false;
|
||||
|
||||
GModelRayCallback callback = new GModelRayCallback(triangles, vertices);
|
||||
meshTree.intersectRay(ray, callback, ref distance, stopAtFirstHit);
|
||||
return callback.hit;
|
||||
}
|
||||
|
||||
public bool IsInsideObject(Vector3 pos, Vector3 down, out float z_dist)
|
||||
{
|
||||
z_dist = 0f;
|
||||
if (triangles.Empty() || !iBound.contains(pos))
|
||||
return false;
|
||||
GModelRayCallback callback = new GModelRayCallback(triangles, vertices);
|
||||
Vector3 rPos = pos - 0.1f * down;
|
||||
float dist = float.PositiveInfinity;
|
||||
Ray ray = new Ray(rPos, down);
|
||||
bool hit = IntersectRay(ray, ref dist, false);
|
||||
if (hit)
|
||||
z_dist = dist - 0.1f;
|
||||
return hit;
|
||||
}
|
||||
|
||||
public bool GetLiquidLevel(Vector3 pos, out float liqHeight)
|
||||
{
|
||||
liqHeight = 0f;
|
||||
if (iLiquid != null)
|
||||
return iLiquid.GetLiquidHeight(pos, out liqHeight);
|
||||
return false;
|
||||
}
|
||||
|
||||
public uint GetLiquidType()
|
||||
{
|
||||
if (iLiquid != null)
|
||||
return iLiquid.GetLiquidType();
|
||||
return 0;
|
||||
}
|
||||
|
||||
public override AxisAlignedBox getBounds() { return iBound; }
|
||||
|
||||
public uint GetMogpFlags() { return iMogpFlags; }
|
||||
|
||||
public uint GetWmoID() { return iGroupWMOID; }
|
||||
|
||||
AxisAlignedBox iBound;
|
||||
uint iMogpFlags;
|
||||
uint iGroupWMOID;
|
||||
List<Vector3> vertices = new List<Vector3>();
|
||||
List<MeshTriangle> triangles = new List<MeshTriangle>();
|
||||
BIH meshTree = new BIH();
|
||||
WmoLiquid iLiquid;
|
||||
}
|
||||
|
||||
public class WorldModel : IModel
|
||||
{
|
||||
public WorldModel()
|
||||
{
|
||||
RootWMOID = 0;
|
||||
}
|
||||
|
||||
public bool IntersectRay(Ray ray, ref float distance, bool stopAtFirstHit)
|
||||
{
|
||||
// small M2 workaround, maybe better make separate class with virtual intersection funcs
|
||||
// in any case, there's no need to use a bound tree if we only have one submodel
|
||||
if (groupModels.Count == 1)
|
||||
return groupModels[0].IntersectRay(ray, ref distance, stopAtFirstHit);
|
||||
|
||||
WModelRayCallBack isc = new WModelRayCallBack(groupModels);
|
||||
groupTree.intersectRay(ray, isc, ref distance, stopAtFirstHit);
|
||||
return isc.hit;
|
||||
}
|
||||
|
||||
public bool IntersectPoint(Vector3 p, Vector3 down, out float dist, AreaInfo info)
|
||||
{
|
||||
dist = 0f;
|
||||
if (groupModels.Empty())
|
||||
return false;
|
||||
|
||||
WModelAreaCallback callback = new WModelAreaCallback(groupModels, down);
|
||||
groupTree.intersectPoint(p, callback);
|
||||
if (callback.hit != null)
|
||||
{
|
||||
info.rootId = (int)RootWMOID;
|
||||
info.groupId = (int)callback.hit.GetWmoID();
|
||||
info.flags = callback.hit.GetMogpFlags();
|
||||
info.result = true;
|
||||
dist = callback.zDist;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool GetLocationInfo(Vector3 p, Vector3 down, out float dist, LocationInfo info)
|
||||
{
|
||||
dist = 0f;
|
||||
if (groupModels.Empty())
|
||||
return false;
|
||||
|
||||
WModelAreaCallback callback = new WModelAreaCallback(groupModels, down);
|
||||
groupTree.intersectPoint(p, callback);
|
||||
if (callback.hit != null)
|
||||
{
|
||||
info.hitModel = callback.hit;
|
||||
dist = callback.zDist;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public bool readFile(string filename)
|
||||
{
|
||||
if (!File.Exists(filename))
|
||||
return false;
|
||||
using (BinaryReader reader = new BinaryReader(new FileStream(filename, FileMode.Open, FileAccess.Read)))
|
||||
{
|
||||
uint chunkSize = 0;
|
||||
uint count = 0;
|
||||
if (reader.ReadStringFromChars(8) != MapConst.VMapMagic)
|
||||
return false;
|
||||
|
||||
if (reader.ReadStringFromChars(4) != "WMOD")
|
||||
return false;
|
||||
chunkSize = reader.ReadUInt32();
|
||||
RootWMOID = reader.ReadUInt32();
|
||||
|
||||
// read group models
|
||||
if (reader.ReadStringFromChars(4) != "GMOD")
|
||||
return false;
|
||||
|
||||
count = reader.ReadUInt32();
|
||||
for (var i = 0; i < count; ++i)
|
||||
{
|
||||
GroupModel group = new GroupModel();
|
||||
group.readFromFile(reader);
|
||||
groupModels.Add(group);
|
||||
}
|
||||
|
||||
// read group BIH
|
||||
if (reader.ReadStringFromChars(4) != "GBIH")
|
||||
return false;
|
||||
groupTree.readFromFile(reader);
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
List<GroupModel> groupModels = new List<GroupModel>();
|
||||
BIH groupTree = new BIH();
|
||||
uint RootWMOID;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
/*
|
||||
* Copyright (C) 2012-2017 CypherCore <http://github.com/CypherCore>
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
using Framework.GameMath;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.Contracts;
|
||||
|
||||
namespace Game.Collision
|
||||
{
|
||||
public class RegularGrid2D<T, Node> where T : IModel where Node : BIHWrap<T>, new()
|
||||
{
|
||||
public const int CELL_NUMBER = 64;
|
||||
public const float HGRID_MAP_SIZE = (533.33333f * 64.0f); // shouldn't be changed
|
||||
public const float CELL_SIZE = HGRID_MAP_SIZE / CELL_NUMBER;
|
||||
|
||||
public RegularGrid2D()
|
||||
{
|
||||
for (int x = 0; x < CELL_NUMBER; ++x)
|
||||
nodes[x] = new Node[CELL_NUMBER];
|
||||
}
|
||||
|
||||
public virtual void insert(T value)
|
||||
{
|
||||
Vector3 pos = value.getPosition();
|
||||
Node node = getGridFor(pos.X, pos.Y);
|
||||
node.insert(value);
|
||||
memberTable.Add(value, node);
|
||||
}
|
||||
|
||||
public virtual void remove(T value)
|
||||
{
|
||||
memberTable[value].remove(value);
|
||||
// Remove the member
|
||||
memberTable.Remove(value);
|
||||
}
|
||||
|
||||
public virtual void balance()
|
||||
{
|
||||
for (int x = 0; x < CELL_NUMBER; ++x)
|
||||
{
|
||||
for (int y = 0; y < CELL_NUMBER; ++y)
|
||||
{
|
||||
Node n = nodes[x][y];
|
||||
if (n != null)
|
||||
n.balance();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public bool contains(T value) { return memberTable.ContainsKey(value); }
|
||||
public int size() { return memberTable.Count; }
|
||||
|
||||
public struct Cell
|
||||
{
|
||||
public int x, y;
|
||||
public static bool operator ==(Cell c1, Cell c2) { return c1.x == c2.x && c1.y == c2.y; }
|
||||
public static bool operator !=(Cell c1, Cell c2) { return !(c1 == c2); }
|
||||
|
||||
public override bool Equals(object obj)
|
||||
{
|
||||
return base.Equals(obj);
|
||||
}
|
||||
public override int GetHashCode()
|
||||
{
|
||||
return base.GetHashCode();
|
||||
}
|
||||
|
||||
public static Cell ComputeCell(float fx, float fy)
|
||||
{
|
||||
Cell c = new Cell();
|
||||
c.x = (int)(fx * (1.0f / CELL_SIZE) + (CELL_NUMBER / 2));
|
||||
c.y = (int)(fy * (1.0f / CELL_SIZE) + (CELL_NUMBER / 2));
|
||||
return c;
|
||||
}
|
||||
|
||||
public bool isValid() { return x >= 0 && x < CELL_NUMBER && y >= 0 && y < CELL_NUMBER; }
|
||||
}
|
||||
|
||||
Node getGridFor(float fx, float fy)
|
||||
{
|
||||
Cell c = Cell.ComputeCell(fx, fy);
|
||||
return getGrid(c.x, c.y);
|
||||
}
|
||||
|
||||
Node getGrid(int x, int y)
|
||||
{
|
||||
Contract.Assert(x < CELL_NUMBER && y < CELL_NUMBER);
|
||||
if (nodes[x][y] == null)
|
||||
nodes[x][y] = new Node();
|
||||
return nodes[x][y];
|
||||
}
|
||||
|
||||
public void intersectRay(Ray ray, WorkerCallback intersectCallback, ref float max_dist)
|
||||
{
|
||||
intersectRay(ray, intersectCallback, ref max_dist, ray.Origin + ray.Direction * max_dist);
|
||||
}
|
||||
|
||||
public void intersectRay(Ray ray, WorkerCallback intersectCallback, ref float max_dist, Vector3 end)
|
||||
{
|
||||
Cell cell = Cell.ComputeCell(ray.Origin.X, ray.Origin.Y);
|
||||
if (!cell.isValid())
|
||||
return;
|
||||
|
||||
Cell last_cell = Cell.ComputeCell(end.X, end.Y);
|
||||
|
||||
if (cell == last_cell)
|
||||
{
|
||||
Node node = nodes[cell.x][cell.y];
|
||||
if (node != null)
|
||||
node.intersectRay(ray, intersectCallback, ref max_dist);
|
||||
return;
|
||||
}
|
||||
|
||||
float voxel = CELL_SIZE;
|
||||
float kx_inv = ray.invDirection().X, bx = ray.Origin.X;
|
||||
float ky_inv = ray.invDirection().Y, by = ray.Origin.Y;
|
||||
|
||||
int stepX, stepY;
|
||||
float tMaxX, tMaxY;
|
||||
if (kx_inv >= 0)
|
||||
{
|
||||
stepX = 1;
|
||||
float x_border = (cell.x + 1) * voxel;
|
||||
tMaxX = (x_border - bx) * kx_inv;
|
||||
}
|
||||
else
|
||||
{
|
||||
stepX = -1;
|
||||
float x_border = (cell.x - 1) * voxel;
|
||||
tMaxX = (x_border - bx) * kx_inv;
|
||||
}
|
||||
|
||||
if (ky_inv >= 0)
|
||||
{
|
||||
stepY = 1;
|
||||
float y_border = (cell.y + 1) * voxel;
|
||||
tMaxY = (y_border - by) * ky_inv;
|
||||
}
|
||||
else
|
||||
{
|
||||
stepY = -1;
|
||||
float y_border = (cell.y - 1) * voxel;
|
||||
tMaxY = (y_border - by) * ky_inv;
|
||||
}
|
||||
|
||||
float tDeltaX = voxel * Math.Abs(kx_inv);
|
||||
float tDeltaY = voxel * Math.Abs(ky_inv);
|
||||
do
|
||||
{
|
||||
Node node = nodes[cell.x][cell.y];
|
||||
if (node != null)
|
||||
{
|
||||
node.intersectRay(ray, intersectCallback, ref max_dist);
|
||||
}
|
||||
if (cell == last_cell)
|
||||
break;
|
||||
if (tMaxX < tMaxY)
|
||||
{
|
||||
tMaxX += tDeltaX;
|
||||
cell.x += stepX;
|
||||
}
|
||||
else
|
||||
{
|
||||
tMaxY += tDeltaY;
|
||||
cell.y += stepY;
|
||||
}
|
||||
} while (cell.isValid());
|
||||
}
|
||||
|
||||
void intersectPoint(Vector3 point, WorkerCallback intersectCallback)
|
||||
{
|
||||
Cell cell = Cell.ComputeCell(point.X, point.Y);
|
||||
if (!cell.isValid())
|
||||
return;
|
||||
|
||||
Node node = nodes[cell.x][cell.y];
|
||||
if (node != null)
|
||||
node.intersectPoint(point, intersectCallback);
|
||||
}
|
||||
|
||||
// Optimized verson of intersectRay function for rays with vertical directions
|
||||
public void intersectZAllignedRay(Ray ray, WorkerCallback intersectCallback, ref float max_dist)
|
||||
{
|
||||
Cell cell = Cell.ComputeCell(ray.Origin.X, ray.Origin.Y);
|
||||
if (!cell.isValid())
|
||||
return;
|
||||
|
||||
Node node = nodes[cell.x][cell.y];
|
||||
if (node != null)
|
||||
node.intersectRay(ray, intersectCallback, ref max_dist);
|
||||
}
|
||||
|
||||
Dictionary<T, Node> memberTable = new Dictionary<T, Node>();
|
||||
Node[][] nodes = new Node[CELL_NUMBER][];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user