chore(repo): merge tank AI checkpoint for 0.1.6
This commit is contained in:
commit
710c8ecaaa
159 files changed
+35721
-1572
No files matched your search
@@ -0,0 +1,61 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef DETOURALLOCATOR_H
|
||||
#define DETOURALLOCATOR_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
/// Provides hint values to the memory allocator on how long the
|
||||
/// memory is expected to be used.
|
||||
enum dtAllocHint
|
||||
{
|
||||
DT_ALLOC_PERM, ///< Memory persist after a function call.
|
||||
DT_ALLOC_TEMP ///< Memory used temporarily within a function.
|
||||
};
|
||||
|
||||
/// A memory allocation function.
|
||||
// @param[in] size The size, in bytes of memory, to allocate.
|
||||
// @param[in] rcAllocHint A hint to the allocator on how long the memory is expected to be in use.
|
||||
// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
|
||||
/// @see dtAllocSetCustom
|
||||
typedef void* (dtAllocFunc)(size_t size, dtAllocHint hint);
|
||||
|
||||
/// A memory deallocation function.
|
||||
/// @param[in] ptr A pointer to a memory block previously allocated using #dtAllocFunc.
|
||||
/// @see dtAllocSetCustom
|
||||
typedef void (dtFreeFunc)(void* ptr);
|
||||
|
||||
/// Sets the base custom allocation functions to be used by Detour.
|
||||
/// @param[in] allocFunc The memory allocation function to be used by #dtAlloc
|
||||
/// @param[in] freeFunc The memory de-allocation function to be used by #dtFree
|
||||
void dtAllocSetCustom(dtAllocFunc *allocFunc, dtFreeFunc *freeFunc);
|
||||
|
||||
/// Allocates a memory block.
|
||||
/// @param[in] size The size, in bytes of memory, to allocate.
|
||||
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
|
||||
/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
|
||||
/// @see dtFree
|
||||
void* dtAlloc(size_t size, dtAllocHint hint);
|
||||
|
||||
/// Deallocates a memory block.
|
||||
/// @param[in] ptr A pointer to a memory block previously allocated using #dtAlloc.
|
||||
/// @see dtAlloc
|
||||
void dtFree(void* ptr);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,56 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef DETOURASSERT_H
|
||||
#define DETOURASSERT_H
|
||||
|
||||
// Note: This header file's only purpose is to include define assert.
|
||||
// Feel free to change the file and include your own implementation instead.
|
||||
|
||||
#ifdef RC_DISABLE_ASSERTS
|
||||
|
||||
// From https://web.archive.org/web/20210117002833/http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
|
||||
# define dtAssert(x) do { (void)sizeof(x); } while((void)(__LINE__==-1),false)
|
||||
|
||||
#else
|
||||
|
||||
/// An assertion failure function.
|
||||
// @param[in] expression asserted expression.
|
||||
// @param[in] file Filename of the failed assertion.
|
||||
// @param[in] line Line number of the failed assertion.
|
||||
/// @see dtAssertFailSetCustom
|
||||
typedef void (dtAssertFailFunc)(const char* expression, const char* file, int line);
|
||||
|
||||
/// Sets the base custom assertion failure function to be used by Detour.
|
||||
/// @param[in] assertFailFunc The function to be invoked in case of failure of #dtAssert
|
||||
void dtAssertFailSetCustom(dtAssertFailFunc *assertFailFunc);
|
||||
|
||||
/// Gets the base custom assertion failure function to be used by Detour.
|
||||
dtAssertFailFunc* dtAssertFailGetCustom();
|
||||
|
||||
# include <assert.h>
|
||||
# define dtAssert(expression) \
|
||||
{ \
|
||||
dtAssertFailFunc* failFunc = dtAssertFailGetCustom(); \
|
||||
if(failFunc == NULL) { assert(expression); } \
|
||||
else if(!(expression)) { (*failFunc)(#expression, __FILE__, __LINE__); } \
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
#endif // DETOURASSERT_H
|
||||
@@ -0,0 +1,571 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef DETOURCOMMON_H
|
||||
#define DETOURCOMMON_H
|
||||
|
||||
#include "DetourMath.h"
|
||||
#include <stddef.h>
|
||||
|
||||
/**
|
||||
@defgroup detour Detour
|
||||
|
||||
Members in this module are used to create, manipulate, and query navigation
|
||||
meshes.
|
||||
|
||||
@note This is a summary list of members. Use the index or search
|
||||
feature to find minor members.
|
||||
*/
|
||||
|
||||
/// @name General helper functions
|
||||
/// @{
|
||||
|
||||
/// Used to ignore a function parameter. VS complains about unused parameters
|
||||
/// and this silences the warning.
|
||||
template<class T> void dtIgnoreUnused(const T&) { }
|
||||
|
||||
/// Swaps the values of the two parameters.
|
||||
/// @param[in,out] a Value A
|
||||
/// @param[in,out] b Value B
|
||||
template<class T> inline void dtSwap(T& a, T& b) { T t = a; a = b; b = t; }
|
||||
|
||||
/// Returns the minimum of two values.
|
||||
/// @param[in] a Value A
|
||||
/// @param[in] b Value B
|
||||
/// @return The minimum of the two values.
|
||||
template<class T> inline T dtMin(T a, T b) { return a < b ? a : b; }
|
||||
|
||||
/// Returns the maximum of two values.
|
||||
/// @param[in] a Value A
|
||||
/// @param[in] b Value B
|
||||
/// @return The maximum of the two values.
|
||||
template<class T> inline T dtMax(T a, T b) { return a > b ? a : b; }
|
||||
|
||||
/// Returns the absolute value.
|
||||
/// @param[in] a The value.
|
||||
/// @return The absolute value of the specified value.
|
||||
template<class T> inline T dtAbs(T a) { return a < 0 ? -a : a; }
|
||||
|
||||
/// Returns the square of the value.
|
||||
/// @param[in] a The value.
|
||||
/// @return The square of the value.
|
||||
template<class T> inline T dtSqr(T a) { return a*a; }
|
||||
|
||||
/// Clamps the value to the specified range.
|
||||
/// @param[in] v The value to clamp.
|
||||
/// @param[in] mn The minimum permitted return value.
|
||||
/// @param[in] mx The maximum permitted return value.
|
||||
/// @return The value, clamped to the specified range.
|
||||
template<class T> inline T dtClamp(T v, T mn, T mx) { return v < mn ? mn : (v > mx ? mx : v); }
|
||||
|
||||
/// @}
|
||||
/// @name Vector helper functions.
|
||||
/// @{
|
||||
|
||||
/// Derives the cross product of two vectors. (@p v1 x @p v2)
|
||||
/// @param[out] dest The cross product. [(x, y, z)]
|
||||
/// @param[in] v1 A Vector [(x, y, z)]
|
||||
/// @param[in] v2 A vector [(x, y, z)]
|
||||
inline void dtVcross(float* dest, const float* v1, const float* v2)
|
||||
{
|
||||
dest[0] = v1[1]*v2[2] - v1[2]*v2[1];
|
||||
dest[1] = v1[2]*v2[0] - v1[0]*v2[2];
|
||||
dest[2] = v1[0]*v2[1] - v1[1]*v2[0];
|
||||
}
|
||||
|
||||
/// Derives the dot product of two vectors. (@p v1 . @p v2)
|
||||
/// @param[in] v1 A Vector [(x, y, z)]
|
||||
/// @param[in] v2 A vector [(x, y, z)]
|
||||
/// @return The dot product.
|
||||
inline float dtVdot(const float* v1, const float* v2)
|
||||
{
|
||||
return v1[0]*v2[0] + v1[1]*v2[1] + v1[2]*v2[2];
|
||||
}
|
||||
|
||||
/// Performs a scaled vector addition. (@p v1 + (@p v2 * @p s))
|
||||
/// @param[out] dest The result vector. [(x, y, z)]
|
||||
/// @param[in] v1 The base vector. [(x, y, z)]
|
||||
/// @param[in] v2 The vector to scale and add to @p v1. [(x, y, z)]
|
||||
/// @param[in] s The amount to scale @p v2 by before adding to @p v1.
|
||||
inline void dtVmad(float* dest, const float* v1, const float* v2, const float s)
|
||||
{
|
||||
dest[0] = v1[0]+v2[0]*s;
|
||||
dest[1] = v1[1]+v2[1]*s;
|
||||
dest[2] = v1[2]+v2[2]*s;
|
||||
}
|
||||
|
||||
/// Performs a linear interpolation between two vectors. (@p v1 toward @p v2)
|
||||
/// @param[out] dest The result vector. [(x, y, x)]
|
||||
/// @param[in] v1 The starting vector.
|
||||
/// @param[in] v2 The destination vector.
|
||||
/// @param[in] t The interpolation factor. [Limits: 0 <= value <= 1.0]
|
||||
inline void dtVlerp(float* dest, const float* v1, const float* v2, const float t)
|
||||
{
|
||||
dest[0] = v1[0]+(v2[0]-v1[0])*t;
|
||||
dest[1] = v1[1]+(v2[1]-v1[1])*t;
|
||||
dest[2] = v1[2]+(v2[2]-v1[2])*t;
|
||||
}
|
||||
|
||||
/// Performs a vector addition. (@p v1 + @p v2)
|
||||
/// @param[out] dest The result vector. [(x, y, z)]
|
||||
/// @param[in] v1 The base vector. [(x, y, z)]
|
||||
/// @param[in] v2 The vector to add to @p v1. [(x, y, z)]
|
||||
inline void dtVadd(float* dest, const float* v1, const float* v2)
|
||||
{
|
||||
dest[0] = v1[0]+v2[0];
|
||||
dest[1] = v1[1]+v2[1];
|
||||
dest[2] = v1[2]+v2[2];
|
||||
}
|
||||
|
||||
/// Performs a vector subtraction. (@p v1 - @p v2)
|
||||
/// @param[out] dest The result vector. [(x, y, z)]
|
||||
/// @param[in] v1 The base vector. [(x, y, z)]
|
||||
/// @param[in] v2 The vector to subtract from @p v1. [(x, y, z)]
|
||||
inline void dtVsub(float* dest, const float* v1, const float* v2)
|
||||
{
|
||||
dest[0] = v1[0]-v2[0];
|
||||
dest[1] = v1[1]-v2[1];
|
||||
dest[2] = v1[2]-v2[2];
|
||||
}
|
||||
|
||||
/// Scales the vector by the specified value. (@p v * @p t)
|
||||
/// @param[out] dest The result vector. [(x, y, z)]
|
||||
/// @param[in] v The vector to scale. [(x, y, z)]
|
||||
/// @param[in] t The scaling factor.
|
||||
inline void dtVscale(float* dest, const float* v, const float t)
|
||||
{
|
||||
dest[0] = v[0]*t;
|
||||
dest[1] = v[1]*t;
|
||||
dest[2] = v[2]*t;
|
||||
}
|
||||
|
||||
/// Selects the minimum value of each element from the specified vectors.
|
||||
/// @param[in,out] mn A vector. (Will be updated with the result.) [(x, y, z)]
|
||||
/// @param[in] v A vector. [(x, y, z)]
|
||||
inline void dtVmin(float* mn, const float* v)
|
||||
{
|
||||
mn[0] = dtMin(mn[0], v[0]);
|
||||
mn[1] = dtMin(mn[1], v[1]);
|
||||
mn[2] = dtMin(mn[2], v[2]);
|
||||
}
|
||||
|
||||
/// Selects the maximum value of each element from the specified vectors.
|
||||
/// @param[in,out] mx A vector. (Will be updated with the result.) [(x, y, z)]
|
||||
/// @param[in] v A vector. [(x, y, z)]
|
||||
inline void dtVmax(float* mx, const float* v)
|
||||
{
|
||||
mx[0] = dtMax(mx[0], v[0]);
|
||||
mx[1] = dtMax(mx[1], v[1]);
|
||||
mx[2] = dtMax(mx[2], v[2]);
|
||||
}
|
||||
|
||||
/// Sets the vector elements to the specified values.
|
||||
/// @param[out] dest The result vector. [(x, y, z)]
|
||||
/// @param[in] x The x-value of the vector.
|
||||
/// @param[in] y The y-value of the vector.
|
||||
/// @param[in] z The z-value of the vector.
|
||||
inline void dtVset(float* dest, const float x, const float y, const float z)
|
||||
{
|
||||
dest[0] = x; dest[1] = y; dest[2] = z;
|
||||
}
|
||||
|
||||
/// Performs a vector copy.
|
||||
/// @param[out] dest The result. [(x, y, z)]
|
||||
/// @param[in] a The vector to copy. [(x, y, z)]
|
||||
inline void dtVcopy(float* dest, const float* a)
|
||||
{
|
||||
dest[0] = a[0];
|
||||
dest[1] = a[1];
|
||||
dest[2] = a[2];
|
||||
}
|
||||
|
||||
/// Derives the scalar length of the vector.
|
||||
/// @param[in] v The vector. [(x, y, z)]
|
||||
/// @return The scalar length of the vector.
|
||||
inline float dtVlen(const float* v)
|
||||
{
|
||||
return dtMathSqrtf(v[0] * v[0] + v[1] * v[1] + v[2] * v[2]);
|
||||
}
|
||||
|
||||
/// Derives the square of the scalar length of the vector. (len * len)
|
||||
/// @param[in] v The vector. [(x, y, z)]
|
||||
/// @return The square of the scalar length of the vector.
|
||||
inline float dtVlenSqr(const float* v)
|
||||
{
|
||||
return v[0]*v[0] + v[1]*v[1] + v[2]*v[2];
|
||||
}
|
||||
|
||||
/// Returns the distance between two points.
|
||||
/// @param[in] v1 A point. [(x, y, z)]
|
||||
/// @param[in] v2 A point. [(x, y, z)]
|
||||
/// @return The distance between the two points.
|
||||
inline float dtVdist(const float* v1, const float* v2)
|
||||
{
|
||||
const float dx = v2[0] - v1[0];
|
||||
const float dy = v2[1] - v1[1];
|
||||
const float dz = v2[2] - v1[2];
|
||||
return dtMathSqrtf(dx*dx + dy*dy + dz*dz);
|
||||
}
|
||||
|
||||
/// Returns the square of the distance between two points.
|
||||
/// @param[in] v1 A point. [(x, y, z)]
|
||||
/// @param[in] v2 A point. [(x, y, z)]
|
||||
/// @return The square of the distance between the two points.
|
||||
inline float dtVdistSqr(const float* v1, const float* v2)
|
||||
{
|
||||
const float dx = v2[0] - v1[0];
|
||||
const float dy = v2[1] - v1[1];
|
||||
const float dz = v2[2] - v1[2];
|
||||
return dx*dx + dy*dy + dz*dz;
|
||||
}
|
||||
|
||||
/// Derives the distance between the specified points on the xz-plane.
|
||||
/// @param[in] v1 A point. [(x, y, z)]
|
||||
/// @param[in] v2 A point. [(x, y, z)]
|
||||
/// @return The distance between the point on the xz-plane.
|
||||
///
|
||||
/// The vectors are projected onto the xz-plane, so the y-values are ignored.
|
||||
inline float dtVdist2D(const float* v1, const float* v2)
|
||||
{
|
||||
const float dx = v2[0] - v1[0];
|
||||
const float dz = v2[2] - v1[2];
|
||||
return dtMathSqrtf(dx*dx + dz*dz);
|
||||
}
|
||||
|
||||
/// Derives the square of the distance between the specified points on the xz-plane.
|
||||
/// @param[in] v1 A point. [(x, y, z)]
|
||||
/// @param[in] v2 A point. [(x, y, z)]
|
||||
/// @return The square of the distance between the point on the xz-plane.
|
||||
inline float dtVdist2DSqr(const float* v1, const float* v2)
|
||||
{
|
||||
const float dx = v2[0] - v1[0];
|
||||
const float dz = v2[2] - v1[2];
|
||||
return dx*dx + dz*dz;
|
||||
}
|
||||
|
||||
/// Normalizes the vector.
|
||||
/// @param[in,out] v The vector to normalize. [(x, y, z)]
|
||||
inline void dtVnormalize(float* v)
|
||||
{
|
||||
float d = 1.0f / dtMathSqrtf(dtSqr(v[0]) + dtSqr(v[1]) + dtSqr(v[2]));
|
||||
v[0] *= d;
|
||||
v[1] *= d;
|
||||
v[2] *= d;
|
||||
}
|
||||
|
||||
/// Performs a 'sloppy' colocation check of the specified points.
|
||||
/// @param[in] p0 A point. [(x, y, z)]
|
||||
/// @param[in] p1 A point. [(x, y, z)]
|
||||
/// @return True if the points are considered to be at the same location.
|
||||
///
|
||||
/// Basically, this function will return true if the specified points are
|
||||
/// close enough to eachother to be considered colocated.
|
||||
inline bool dtVequal(const float* p0, const float* p1)
|
||||
{
|
||||
static const float thr = dtSqr(1.0f/16384.0f);
|
||||
const float d = dtVdistSqr(p0, p1);
|
||||
return d < thr;
|
||||
}
|
||||
|
||||
/// Checks that the specified vector's components are all finite.
|
||||
/// @param[in] v A point. [(x, y, z)]
|
||||
/// @return True if all of the point's components are finite, i.e. not NaN
|
||||
/// or any of the infinities.
|
||||
inline bool dtVisfinite(const float* v)
|
||||
{
|
||||
bool result =
|
||||
dtMathIsfinite(v[0]) &&
|
||||
dtMathIsfinite(v[1]) &&
|
||||
dtMathIsfinite(v[2]);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Checks that the specified vector's 2D components are finite.
|
||||
/// @param[in] v A point. [(x, y, z)]
|
||||
inline bool dtVisfinite2D(const float* v)
|
||||
{
|
||||
bool result = dtMathIsfinite(v[0]) && dtMathIsfinite(v[2]);
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Derives the dot product of two vectors on the xz-plane. (@p u . @p v)
|
||||
/// @param[in] u A vector [(x, y, z)]
|
||||
/// @param[in] v A vector [(x, y, z)]
|
||||
/// @return The dot product on the xz-plane.
|
||||
///
|
||||
/// The vectors are projected onto the xz-plane, so the y-values are ignored.
|
||||
inline float dtVdot2D(const float* u, const float* v)
|
||||
{
|
||||
return u[0]*v[0] + u[2]*v[2];
|
||||
}
|
||||
|
||||
/// Derives the xz-plane 2D perp product of the two vectors. (uz*vx - ux*vz)
|
||||
/// @param[in] u The LHV vector [(x, y, z)]
|
||||
/// @param[in] v The RHV vector [(x, y, z)]
|
||||
/// @return The perp dot product on the xz-plane.
|
||||
///
|
||||
/// The vectors are projected onto the xz-plane, so the y-values are ignored.
|
||||
inline float dtVperp2D(const float* u, const float* v)
|
||||
{
|
||||
return u[2]*v[0] - u[0]*v[2];
|
||||
}
|
||||
|
||||
/// @}
|
||||
/// @name Computational geometry helper functions.
|
||||
/// @{
|
||||
|
||||
/// Derives the signed xz-plane area of the triangle ABC, or the relationship of line AB to point C.
|
||||
/// @param[in] a Vertex A. [(x, y, z)]
|
||||
/// @param[in] b Vertex B. [(x, y, z)]
|
||||
/// @param[in] c Vertex C. [(x, y, z)]
|
||||
/// @return The signed xz-plane area of the triangle.
|
||||
inline float dtTriArea2D(const float* a, const float* b, const float* c)
|
||||
{
|
||||
const float abx = b[0] - a[0];
|
||||
const float abz = b[2] - a[2];
|
||||
const float acx = c[0] - a[0];
|
||||
const float acz = c[2] - a[2];
|
||||
return acx*abz - abx*acz;
|
||||
}
|
||||
|
||||
/// Determines if two axis-aligned bounding boxes overlap.
|
||||
/// @param[in] amin Minimum bounds of box A. [(x, y, z)]
|
||||
/// @param[in] amax Maximum bounds of box A. [(x, y, z)]
|
||||
/// @param[in] bmin Minimum bounds of box B. [(x, y, z)]
|
||||
/// @param[in] bmax Maximum bounds of box B. [(x, y, z)]
|
||||
/// @return True if the two AABB's overlap.
|
||||
/// @see dtOverlapBounds
|
||||
inline bool dtOverlapQuantBounds(const unsigned short amin[3], const unsigned short amax[3],
|
||||
const unsigned short bmin[3], const unsigned short bmax[3])
|
||||
{
|
||||
bool overlap = true;
|
||||
overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap;
|
||||
overlap = (amin[1] > bmax[1] || amax[1] < bmin[1]) ? false : overlap;
|
||||
overlap = (amin[2] > bmax[2] || amax[2] < bmin[2]) ? false : overlap;
|
||||
return overlap;
|
||||
}
|
||||
|
||||
/// Determines if two axis-aligned bounding boxes overlap.
|
||||
/// @param[in] amin Minimum bounds of box A. [(x, y, z)]
|
||||
/// @param[in] amax Maximum bounds of box A. [(x, y, z)]
|
||||
/// @param[in] bmin Minimum bounds of box B. [(x, y, z)]
|
||||
/// @param[in] bmax Maximum bounds of box B. [(x, y, z)]
|
||||
/// @return True if the two AABB's overlap.
|
||||
/// @see dtOverlapQuantBounds
|
||||
inline bool dtOverlapBounds(const float* amin, const float* amax,
|
||||
const float* bmin, const float* bmax)
|
||||
{
|
||||
bool overlap = true;
|
||||
overlap = (amin[0] > bmax[0] || amax[0] < bmin[0]) ? false : overlap;
|
||||
overlap = (amin[1] > bmax[1] || amax[1] < bmin[1]) ? false : overlap;
|
||||
overlap = (amin[2] > bmax[2] || amax[2] < bmin[2]) ? false : overlap;
|
||||
return overlap;
|
||||
}
|
||||
|
||||
/// Derives the closest point on a triangle from the specified reference point.
|
||||
/// @param[out] closest The closest point on the triangle.
|
||||
/// @param[in] p The reference point from which to test. [(x, y, z)]
|
||||
/// @param[in] a Vertex A of triangle ABC. [(x, y, z)]
|
||||
/// @param[in] b Vertex B of triangle ABC. [(x, y, z)]
|
||||
/// @param[in] c Vertex C of triangle ABC. [(x, y, z)]
|
||||
void dtClosestPtPointTriangle(float* closest, const float* p,
|
||||
const float* a, const float* b, const float* c);
|
||||
|
||||
/// Derives the y-axis height of the closest point on the triangle from the specified reference point.
|
||||
/// @param[in] p The reference point from which to test. [(x, y, z)]
|
||||
/// @param[in] a Vertex A of triangle ABC. [(x, y, z)]
|
||||
/// @param[in] b Vertex B of triangle ABC. [(x, y, z)]
|
||||
/// @param[in] c Vertex C of triangle ABC. [(x, y, z)]
|
||||
/// @param[out] h The resulting height.
|
||||
bool dtClosestHeightPointTriangle(const float* p, const float* a, const float* b, const float* c, float& h);
|
||||
|
||||
bool dtIntersectSegmentPoly2D(const float* p0, const float* p1,
|
||||
const float* verts, int nverts,
|
||||
float& tmin, float& tmax,
|
||||
int& segMin, int& segMax);
|
||||
|
||||
bool dtIntersectSegSeg2D(const float* ap, const float* aq,
|
||||
const float* bp, const float* bq,
|
||||
float& s, float& t);
|
||||
|
||||
/// Determines if the specified point is inside the convex polygon on the xz-plane.
|
||||
/// @param[in] pt The point to check. [(x, y, z)]
|
||||
/// @param[in] verts The polygon vertices. [(x, y, z) * @p nverts]
|
||||
/// @param[in] nverts The number of vertices. [Limit: >= 3]
|
||||
/// @return True if the point is inside the polygon.
|
||||
bool dtPointInPolygon(const float* pt, const float* verts, const int nverts);
|
||||
|
||||
bool dtDistancePtPolyEdgesSqr(const float* pt, const float* verts, const int nverts,
|
||||
float* ed, float* et);
|
||||
|
||||
float dtDistancePtSegSqr2D(const float* pt, const float* p, const float* q, float& t);
|
||||
|
||||
/// Derives the centroid of a convex polygon.
|
||||
/// @param[out] tc The centroid of the polgyon. [(x, y, z)]
|
||||
/// @param[in] idx The polygon indices. [(vertIndex) * @p nidx]
|
||||
/// @param[in] nidx The number of indices in the polygon. [Limit: >= 3]
|
||||
/// @param[in] verts The polygon vertices. [(x, y, z) * vertCount]
|
||||
void dtCalcPolyCenter(float* tc, const unsigned short* idx, int nidx, const float* verts);
|
||||
|
||||
/// Determines if the two convex polygons overlap on the xz-plane.
|
||||
/// @param[in] polya Polygon A vertices. [(x, y, z) * @p npolya]
|
||||
/// @param[in] npolya The number of vertices in polygon A.
|
||||
/// @param[in] polyb Polygon B vertices. [(x, y, z) * @p npolyb]
|
||||
/// @param[in] npolyb The number of vertices in polygon B.
|
||||
/// @return True if the two polygons overlap.
|
||||
bool dtOverlapPolyPoly2D(const float* polya, const int npolya,
|
||||
const float* polyb, const int npolyb);
|
||||
|
||||
/// @}
|
||||
/// @name Miscellanious functions.
|
||||
/// @{
|
||||
|
||||
inline unsigned int dtNextPow2(unsigned int v)
|
||||
{
|
||||
v--;
|
||||
v |= v >> 1;
|
||||
v |= v >> 2;
|
||||
v |= v >> 4;
|
||||
v |= v >> 8;
|
||||
v |= v >> 16;
|
||||
v++;
|
||||
return v;
|
||||
}
|
||||
|
||||
inline unsigned int dtIlog2(unsigned int v)
|
||||
{
|
||||
unsigned int r;
|
||||
unsigned int shift;
|
||||
r = (v > 0xffff) << 4; v >>= r;
|
||||
shift = (v > 0xff) << 3; v >>= shift; r |= shift;
|
||||
shift = (v > 0xf) << 2; v >>= shift; r |= shift;
|
||||
shift = (v > 0x3) << 1; v >>= shift; r |= shift;
|
||||
r |= (v >> 1);
|
||||
return r;
|
||||
}
|
||||
|
||||
inline int dtAlign4(int x) { return (x+3) & ~3; }
|
||||
|
||||
inline int dtOppositeTile(int side) { return (side+4) & 0x7; }
|
||||
|
||||
inline void dtSwapByte(unsigned char* a, unsigned char* b)
|
||||
{
|
||||
unsigned char tmp = *a;
|
||||
*a = *b;
|
||||
*b = tmp;
|
||||
}
|
||||
|
||||
inline void dtSwapEndian(unsigned short* v)
|
||||
{
|
||||
unsigned char* x = (unsigned char*)v;
|
||||
dtSwapByte(x+0, x+1);
|
||||
}
|
||||
|
||||
inline void dtSwapEndian(short* v)
|
||||
{
|
||||
unsigned char* x = (unsigned char*)v;
|
||||
dtSwapByte(x+0, x+1);
|
||||
}
|
||||
|
||||
inline void dtSwapEndian(unsigned int* v)
|
||||
{
|
||||
unsigned char* x = (unsigned char*)v;
|
||||
dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2);
|
||||
}
|
||||
|
||||
inline void dtSwapEndian(int* v)
|
||||
{
|
||||
unsigned char* x = (unsigned char*)v;
|
||||
dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2);
|
||||
}
|
||||
|
||||
inline void dtSwapEndian(float* v)
|
||||
{
|
||||
unsigned char* x = (unsigned char*)v;
|
||||
dtSwapByte(x+0, x+3); dtSwapByte(x+1, x+2);
|
||||
}
|
||||
|
||||
void dtRandomPointInConvexPoly(const float* pts, const int npts, float* areas,
|
||||
const float s, const float t, float* out);
|
||||
|
||||
template<typename TypeToRetrieveAs>
|
||||
TypeToRetrieveAs* dtGetThenAdvanceBufferPointer(const unsigned char*& buffer, const size_t distanceToAdvance)
|
||||
{
|
||||
TypeToRetrieveAs* returnPointer = reinterpret_cast<TypeToRetrieveAs*>(buffer);
|
||||
buffer += distanceToAdvance;
|
||||
return returnPointer;
|
||||
}
|
||||
|
||||
template<typename TypeToRetrieveAs>
|
||||
TypeToRetrieveAs* dtGetThenAdvanceBufferPointer(unsigned char*& buffer, const size_t distanceToAdvance)
|
||||
{
|
||||
TypeToRetrieveAs* returnPointer = reinterpret_cast<TypeToRetrieveAs*>(buffer);
|
||||
buffer += distanceToAdvance;
|
||||
return returnPointer;
|
||||
}
|
||||
|
||||
|
||||
/// @}
|
||||
|
||||
#endif // DETOURCOMMON_H
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// This section contains detailed documentation for members that don't have
|
||||
// a source file. It reduces clutter in the main section of the header.
|
||||
|
||||
/**
|
||||
|
||||
@fn float dtTriArea2D(const float* a, const float* b, const float* c)
|
||||
@par
|
||||
|
||||
The vertices are projected onto the xz-plane, so the y-values are ignored.
|
||||
|
||||
This is a low cost function than can be used for various purposes. Its main purpose
|
||||
is for point/line relationship testing.
|
||||
|
||||
In all cases: A value of zero indicates that all vertices are collinear or represent the same point.
|
||||
(On the xz-plane.)
|
||||
|
||||
When used for point/line relationship tests, AB usually represents a line against which
|
||||
the C point is to be tested. In this case:
|
||||
|
||||
A positive value indicates that point C is to the left of line AB, looking from A toward B.<br/>
|
||||
A negative value indicates that point C is to the right of lineAB, looking from A toward B.
|
||||
|
||||
When used for evaluating a triangle:
|
||||
|
||||
The absolute value of the return value is two times the area of the triangle when it is
|
||||
projected onto the xz-plane.
|
||||
|
||||
A positive return value indicates:
|
||||
|
||||
<ul>
|
||||
<li>The vertices are wrapped in the normal Detour wrap direction.</li>
|
||||
<li>The triangle's 3D face normal is in the general up direction.</li>
|
||||
</ul>
|
||||
|
||||
A negative return value indicates:
|
||||
|
||||
<ul>
|
||||
<li>The vertices are reverse wrapped. (Wrapped opposite the normal Detour wrap direction.)</li>
|
||||
<li>The triangle's 3D face normal is in the general down direction.</li>
|
||||
</ul>
|
||||
|
||||
*/
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
@defgroup detour Detour
|
||||
|
||||
Members in this module are wrappers around the standard math library
|
||||
*/
|
||||
|
||||
#ifndef DETOURMATH_H
|
||||
#define DETOURMATH_H
|
||||
|
||||
#include <math.h>
|
||||
|
||||
inline float dtMathFabsf(float x) { return fabsf(x); }
|
||||
inline float dtMathSqrtf(float x) { return sqrtf(x); }
|
||||
inline float dtMathFloorf(float x) { return floorf(x); }
|
||||
inline float dtMathCeilf(float x) { return ceilf(x); }
|
||||
inline float dtMathCosf(float x) { return cosf(x); }
|
||||
inline float dtMathSinf(float x) { return sinf(x); }
|
||||
inline float dtMathAtan2f(float y, float x) { return atan2f(y, x); }
|
||||
inline bool dtMathIsfinite(float x)
|
||||
{
|
||||
#ifndef RC_FAST_MATH
|
||||
return isfinite(x);
|
||||
#else
|
||||
// Infinity and NaN are disabled when compiling with -ffast-math
|
||||
(void)x;
|
||||
return true;
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,781 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef DETOURNAVMESH_H
|
||||
#define DETOURNAVMESH_H
|
||||
|
||||
#include "DetourAlloc.h"
|
||||
#include "DetourStatus.h"
|
||||
|
||||
// Undefine (or define in a build config) the following line to use 64bit polyref.
|
||||
// Generally not needed, useful for very large worlds.
|
||||
// Note: tiles build using 32bit refs are not compatible with 64bit refs!
|
||||
//#define DT_POLYREF64 1
|
||||
|
||||
#ifdef DT_POLYREF64
|
||||
// TODO: figure out a multiplatform version of uint64_t
|
||||
// - maybe: https://code.google.com/p/msinttypes/
|
||||
// - or: http://www.azillionmonkeys.com/qed/pstdint.h
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
|
||||
// Note: If you want to use 64-bit refs, change the types of both dtPolyRef & dtTileRef.
|
||||
// It is also recommended that you change dtHashRef() to a proper 64-bit hash.
|
||||
|
||||
/// A handle to a polygon within a navigation mesh tile.
|
||||
/// @ingroup detour
|
||||
#ifdef DT_POLYREF64
|
||||
static const unsigned int DT_SALT_BITS = 16;
|
||||
static const unsigned int DT_TILE_BITS = 28;
|
||||
static const unsigned int DT_POLY_BITS = 20;
|
||||
typedef uint64_t dtPolyRef;
|
||||
#else
|
||||
typedef unsigned int dtPolyRef;
|
||||
#endif
|
||||
|
||||
/// A handle to a tile within a navigation mesh.
|
||||
/// @ingroup detour
|
||||
#ifdef DT_POLYREF64
|
||||
typedef uint64_t dtTileRef;
|
||||
#else
|
||||
typedef unsigned int dtTileRef;
|
||||
#endif
|
||||
|
||||
/// The maximum number of vertices per navigation polygon.
|
||||
/// @ingroup detour
|
||||
static const int DT_VERTS_PER_POLYGON = 6;
|
||||
|
||||
/// @{
|
||||
/// @name Tile Serialization Constants
|
||||
/// These constants are used to detect whether a navigation tile's data
|
||||
/// and state format is compatible with the current build.
|
||||
///
|
||||
|
||||
/// A magic number used to detect compatibility of navigation tile data.
|
||||
static const int DT_NAVMESH_MAGIC = 'D'<<24 | 'N'<<16 | 'A'<<8 | 'V';
|
||||
|
||||
/// A version number used to detect compatibility of navigation tile data.
|
||||
static const int DT_NAVMESH_VERSION = 7;
|
||||
|
||||
/// A magic number used to detect the compatibility of navigation tile states.
|
||||
static const int DT_NAVMESH_STATE_MAGIC = 'D'<<24 | 'N'<<16 | 'M'<<8 | 'S';
|
||||
|
||||
/// A version number used to detect compatibility of navigation tile states.
|
||||
static const int DT_NAVMESH_STATE_VERSION = 1;
|
||||
|
||||
/// @}
|
||||
|
||||
/// A flag that indicates that an entity links to an external entity.
|
||||
/// (E.g. A polygon edge is a portal that links to another polygon.)
|
||||
static const unsigned short DT_EXT_LINK = 0x8000;
|
||||
|
||||
/// A value that indicates the entity does not link to anything.
|
||||
static const unsigned int DT_NULL_LINK = 0xffffffff;
|
||||
|
||||
/// A flag that indicates that an off-mesh connection can be traversed in both directions. (Is bidirectional.)
|
||||
static const unsigned int DT_OFFMESH_CON_BIDIR = 1;
|
||||
|
||||
/// The maximum number of user defined area ids.
|
||||
/// @ingroup detour
|
||||
static const int DT_MAX_AREAS = 64;
|
||||
|
||||
/// Tile flags used for various functions and fields.
|
||||
/// For an example, see dtNavMesh::addTile().
|
||||
enum dtTileFlags
|
||||
{
|
||||
/// The navigation mesh owns the tile memory and is responsible for freeing it.
|
||||
DT_TILE_FREE_DATA = 0x01
|
||||
};
|
||||
|
||||
/// Vertex flags returned by dtNavMeshQuery::findStraightPath.
|
||||
enum dtStraightPathFlags
|
||||
{
|
||||
DT_STRAIGHTPATH_START = 0x01, ///< The vertex is the start position in the path.
|
||||
DT_STRAIGHTPATH_END = 0x02, ///< The vertex is the end position in the path.
|
||||
DT_STRAIGHTPATH_OFFMESH_CONNECTION = 0x04 ///< The vertex is the start of an off-mesh connection.
|
||||
};
|
||||
|
||||
/// Options for dtNavMeshQuery::findStraightPath.
|
||||
enum dtStraightPathOptions
|
||||
{
|
||||
DT_STRAIGHTPATH_AREA_CROSSINGS = 0x01, ///< Add a vertex at every polygon edge crossing where area changes.
|
||||
DT_STRAIGHTPATH_ALL_CROSSINGS = 0x02 ///< Add a vertex at every polygon edge crossing.
|
||||
};
|
||||
|
||||
|
||||
/// Options for dtNavMeshQuery::initSlicedFindPath and updateSlicedFindPath
|
||||
enum dtFindPathOptions
|
||||
{
|
||||
DT_FINDPATH_ANY_ANGLE = 0x02 ///< use raycasts during pathfind to "shortcut" (raycast still consider costs)
|
||||
};
|
||||
|
||||
/// Options for dtNavMeshQuery::raycast
|
||||
enum dtRaycastOptions
|
||||
{
|
||||
DT_RAYCAST_USE_COSTS = 0x01 ///< Raycast should calculate movement cost along the ray and fill RaycastHit::cost
|
||||
};
|
||||
|
||||
enum dtDetailTriEdgeFlags
|
||||
{
|
||||
DT_DETAIL_EDGE_BOUNDARY = 0x01 ///< Detail triangle edge is part of the poly boundary
|
||||
};
|
||||
|
||||
|
||||
/// Limit raycasting during any angle pahfinding
|
||||
/// The limit is given as a multiple of the character radius
|
||||
static const float DT_RAY_CAST_LIMIT_PROPORTIONS = 50.0f;
|
||||
|
||||
/// Flags representing the type of a navigation mesh polygon.
|
||||
enum dtPolyTypes
|
||||
{
|
||||
/// The polygon is a standard convex polygon that is part of the surface of the mesh.
|
||||
DT_POLYTYPE_GROUND = 0,
|
||||
/// The polygon is an off-mesh connection consisting of two vertices.
|
||||
DT_POLYTYPE_OFFMESH_CONNECTION = 1
|
||||
};
|
||||
|
||||
|
||||
/// Defines a polygon within a dtMeshTile object.
|
||||
/// @ingroup detour
|
||||
struct dtPoly
|
||||
{
|
||||
/// Index to first link in linked list. (Or #DT_NULL_LINK if there is no link.)
|
||||
unsigned int firstLink;
|
||||
|
||||
/// The indices of the polygon's vertices.
|
||||
/// The actual vertices are located in dtMeshTile::verts.
|
||||
unsigned short verts[DT_VERTS_PER_POLYGON];
|
||||
|
||||
/// Packed data representing neighbor polygons references and flags for each edge.
|
||||
unsigned short neis[DT_VERTS_PER_POLYGON];
|
||||
|
||||
/// The user defined polygon flags.
|
||||
unsigned short flags;
|
||||
|
||||
/// The number of vertices in the polygon.
|
||||
unsigned char vertCount;
|
||||
|
||||
/// The bit packed area id and polygon type.
|
||||
/// @note Use the structure's set and get methods to access this value.
|
||||
unsigned char areaAndtype;
|
||||
|
||||
/// Sets the user defined area id. [Limit: < #DT_MAX_AREAS]
|
||||
inline void setArea(unsigned char a) { areaAndtype = (areaAndtype & 0xc0) | (a & 0x3f); }
|
||||
|
||||
/// Sets the polygon type. (See: #dtPolyTypes.)
|
||||
inline void setType(unsigned char t) { areaAndtype = (areaAndtype & 0x3f) | (t << 6); }
|
||||
|
||||
/// Gets the user defined area id.
|
||||
inline unsigned char getArea() const { return areaAndtype & 0x3f; }
|
||||
|
||||
/// Gets the polygon type. (See: #dtPolyTypes)
|
||||
inline unsigned char getType() const { return areaAndtype >> 6; }
|
||||
};
|
||||
|
||||
/// Defines the location of detail sub-mesh data within a dtMeshTile.
|
||||
struct dtPolyDetail
|
||||
{
|
||||
unsigned int vertBase; ///< The offset of the vertices in the dtMeshTile::detailVerts array.
|
||||
unsigned int triBase; ///< The offset of the triangles in the dtMeshTile::detailTris array.
|
||||
unsigned char vertCount; ///< The number of vertices in the sub-mesh.
|
||||
unsigned char triCount; ///< The number of triangles in the sub-mesh.
|
||||
};
|
||||
|
||||
/// Defines a link between polygons.
|
||||
/// @note This structure is rarely if ever used by the end user.
|
||||
/// @see dtMeshTile
|
||||
struct dtLink
|
||||
{
|
||||
dtPolyRef ref; ///< Neighbour reference. (The neighbor that is linked to.)
|
||||
unsigned int next; ///< Index of the next link.
|
||||
unsigned char edge; ///< Index of the polygon edge that owns this link.
|
||||
unsigned char side; ///< If a boundary link, defines on which side the link is.
|
||||
unsigned char bmin; ///< If a boundary link, defines the minimum sub-edge area.
|
||||
unsigned char bmax; ///< If a boundary link, defines the maximum sub-edge area.
|
||||
};
|
||||
|
||||
/// Bounding volume node.
|
||||
/// @note This structure is rarely if ever used by the end user.
|
||||
/// @see dtMeshTile
|
||||
struct dtBVNode
|
||||
{
|
||||
unsigned short bmin[3]; ///< Minimum bounds of the node's AABB. [(x, y, z)]
|
||||
unsigned short bmax[3]; ///< Maximum bounds of the node's AABB. [(x, y, z)]
|
||||
int i; ///< The node's index. (Negative for escape sequence.)
|
||||
};
|
||||
|
||||
/// Defines an navigation mesh off-mesh connection within a dtMeshTile object.
|
||||
/// An off-mesh connection is a user defined traversable connection made up to two vertices.
|
||||
struct dtOffMeshConnection
|
||||
{
|
||||
/// The endpoints of the connection. [(ax, ay, az, bx, by, bz)]
|
||||
float pos[6];
|
||||
|
||||
/// The radius of the endpoints. [Limit: >= 0]
|
||||
float rad;
|
||||
|
||||
/// The polygon reference of the connection within the tile.
|
||||
unsigned short poly;
|
||||
|
||||
/// Link flags.
|
||||
/// @note These are not the connection's user defined flags. Those are assigned via the
|
||||
/// connection's dtPoly definition. These are link flags used for internal purposes.
|
||||
unsigned char flags;
|
||||
|
||||
/// End point side.
|
||||
unsigned char side;
|
||||
|
||||
/// The id of the offmesh connection. (User assigned when the navigation mesh is built.)
|
||||
unsigned int userId;
|
||||
};
|
||||
|
||||
/// Provides high level information related to a dtMeshTile object.
|
||||
/// @ingroup detour
|
||||
struct dtMeshHeader
|
||||
{
|
||||
int magic; ///< Tile magic number. (Used to identify the data format.)
|
||||
int version; ///< Tile data format version number.
|
||||
int x; ///< The x-position of the tile within the dtNavMesh tile grid. (x, y, layer)
|
||||
int y; ///< The y-position of the tile within the dtNavMesh tile grid. (x, y, layer)
|
||||
int layer; ///< The layer of the tile within the dtNavMesh tile grid. (x, y, layer)
|
||||
unsigned int userId; ///< The user defined id of the tile.
|
||||
int polyCount; ///< The number of polygons in the tile.
|
||||
int vertCount; ///< The number of vertices in the tile.
|
||||
int maxLinkCount; ///< The number of allocated links.
|
||||
int detailMeshCount; ///< The number of sub-meshes in the detail mesh.
|
||||
|
||||
/// The number of unique vertices in the detail mesh. (In addition to the polygon vertices.)
|
||||
int detailVertCount;
|
||||
|
||||
int detailTriCount; ///< The number of triangles in the detail mesh.
|
||||
int bvNodeCount; ///< The number of bounding volume nodes. (Zero if bounding volumes are disabled.)
|
||||
int offMeshConCount; ///< The number of off-mesh connections.
|
||||
int offMeshBase; ///< The index of the first polygon which is an off-mesh connection.
|
||||
float walkableHeight; ///< The height of the agents using the tile.
|
||||
float walkableRadius; ///< The radius of the agents using the tile.
|
||||
float walkableClimb; ///< The maximum climb height of the agents using the tile.
|
||||
float bmin[3]; ///< The minimum bounds of the tile's AABB. [(x, y, z)]
|
||||
float bmax[3]; ///< The maximum bounds of the tile's AABB. [(x, y, z)]
|
||||
|
||||
/// The bounding volume quantization factor.
|
||||
float bvQuantFactor;
|
||||
};
|
||||
|
||||
/// Defines a navigation mesh tile.
|
||||
/// @ingroup detour
|
||||
struct dtMeshTile
|
||||
{
|
||||
unsigned int salt; ///< Counter describing modifications to the tile.
|
||||
|
||||
unsigned int linksFreeList; ///< Index to the next free link.
|
||||
dtMeshHeader* header; ///< The tile header.
|
||||
dtPoly* polys; ///< The tile polygons. [Size: dtMeshHeader::polyCount]
|
||||
float* verts; ///< The tile vertices. [(x, y, z) * dtMeshHeader::vertCount]
|
||||
dtLink* links; ///< The tile links. [Size: dtMeshHeader::maxLinkCount]
|
||||
dtPolyDetail* detailMeshes; ///< The tile's detail sub-meshes. [Size: dtMeshHeader::detailMeshCount]
|
||||
|
||||
/// The detail mesh's unique vertices. [(x, y, z) * dtMeshHeader::detailVertCount]
|
||||
float* detailVerts;
|
||||
|
||||
/// The detail mesh's triangles. [(vertA, vertB, vertC, triFlags) * dtMeshHeader::detailTriCount].
|
||||
/// See dtDetailTriEdgeFlags and dtGetDetailTriEdgeFlags.
|
||||
unsigned char* detailTris;
|
||||
|
||||
/// The tile bounding volume nodes. [Size: dtMeshHeader::bvNodeCount]
|
||||
/// (Will be null if bounding volumes are disabled.)
|
||||
dtBVNode* bvTree;
|
||||
|
||||
dtOffMeshConnection* offMeshCons; ///< The tile off-mesh connections. [Size: dtMeshHeader::offMeshConCount]
|
||||
|
||||
unsigned char* data; ///< The tile data. (Not directly accessed under normal situations.)
|
||||
int dataSize; ///< Size of the tile data.
|
||||
int flags; ///< Tile flags. (See: #dtTileFlags)
|
||||
dtMeshTile* next; ///< The next free tile, or the next tile in the spatial grid.
|
||||
};
|
||||
|
||||
/// Get flags for edge in detail triangle.
|
||||
/// @param[in] triFlags The flags for the triangle (last component of detail vertices above).
|
||||
/// @param[in] edgeIndex The index of the first vertex of the edge. For instance, if 0,
|
||||
/// returns flags for edge AB.
|
||||
inline int dtGetDetailTriEdgeFlags(unsigned char triFlags, int edgeIndex)
|
||||
{
|
||||
return (triFlags >> (edgeIndex * 2)) & 0x3;
|
||||
}
|
||||
|
||||
/// Configuration parameters used to define multi-tile navigation meshes.
|
||||
/// The values are used to allocate space during the initialization of a navigation mesh.
|
||||
/// @see dtNavMesh::init()
|
||||
/// @ingroup detour
|
||||
struct dtNavMeshParams
|
||||
{
|
||||
float orig[3]; ///< The world space origin of the navigation mesh's tile space. [(x, y, z)]
|
||||
float tileWidth; ///< The width of each tile. (Along the x-axis.)
|
||||
float tileHeight; ///< The height of each tile. (Along the z-axis.)
|
||||
int maxTiles; ///< The maximum number of tiles the navigation mesh can contain. This and maxPolys are used to calculate how many bits are needed to identify tiles and polygons uniquely.
|
||||
int maxPolys; ///< The maximum number of polygons each tile can contain. This and maxTiles are used to calculate how many bits are needed to identify tiles and polygons uniquely.
|
||||
};
|
||||
|
||||
/// A navigation mesh based on tiles of convex polygons.
|
||||
/// @ingroup detour
|
||||
class dtNavMesh
|
||||
{
|
||||
public:
|
||||
dtNavMesh();
|
||||
~dtNavMesh();
|
||||
|
||||
/// @{
|
||||
/// @name Initialization and Tile Management
|
||||
|
||||
/// Initializes the navigation mesh for tiled use.
|
||||
/// @param[in] params Initialization parameters.
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus init(const dtNavMeshParams* params);
|
||||
|
||||
/// Initializes the navigation mesh for single tile use.
|
||||
/// @param[in] data Data of the new tile. (See: #dtCreateNavMeshData)
|
||||
/// @param[in] dataSize The data size of the new tile.
|
||||
/// @param[in] flags The tile flags. (See: #dtTileFlags)
|
||||
/// @return The status flags for the operation.
|
||||
/// @see dtCreateNavMeshData
|
||||
dtStatus init(unsigned char* data, const int dataSize, const int flags);
|
||||
|
||||
/// The navigation mesh initialization params.
|
||||
const dtNavMeshParams* getParams() const;
|
||||
|
||||
/// Adds a tile to the navigation mesh.
|
||||
/// @param[in] data Data for the new tile mesh. (See: #dtCreateNavMeshData)
|
||||
/// @param[in] dataSize Data size of the new tile mesh.
|
||||
/// @param[in] flags Tile flags. (See: #dtTileFlags)
|
||||
/// @param[in] lastRef The desired reference for the tile. (When reloading a tile.) [opt] [Default: 0]
|
||||
/// @param[out] result The tile reference. (If the tile was succesfully added.) [opt]
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus addTile(unsigned char* data, int dataSize, int flags, dtTileRef lastRef, dtTileRef* result);
|
||||
|
||||
/// Removes the specified tile from the navigation mesh.
|
||||
/// @param[in] ref The reference of the tile to remove.
|
||||
/// @param[out] data Data associated with deleted tile.
|
||||
/// @param[out] dataSize Size of the data associated with deleted tile.
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus removeTile(dtTileRef ref, unsigned char** data, int* dataSize);
|
||||
|
||||
/// @}
|
||||
|
||||
/// @{
|
||||
/// @name Query Functions
|
||||
|
||||
/// Calculates the tile grid location for the specified world position.
|
||||
/// @param[in] pos The world position for the query. [(x, y, z)]
|
||||
/// @param[out] tx The tile's x-location. (x, y)
|
||||
/// @param[out] ty The tile's y-location. (x, y)
|
||||
void calcTileLoc(const float* pos, int* tx, int* ty) const;
|
||||
|
||||
/// Gets the tile at the specified grid location.
|
||||
/// @param[in] x The tile's x-location. (x, y, layer)
|
||||
/// @param[in] y The tile's y-location. (x, y, layer)
|
||||
/// @param[in] layer The tile's layer. (x, y, layer)
|
||||
/// @return The tile, or null if the tile does not exist.
|
||||
const dtMeshTile* getTileAt(const int x, const int y, const int layer) const;
|
||||
|
||||
/// Gets all tiles at the specified grid location. (All layers.)
|
||||
/// @param[in] x The tile's x-location. (x, y)
|
||||
/// @param[in] y The tile's y-location. (x, y)
|
||||
/// @param[out] tiles A pointer to an array of tiles that will hold the result.
|
||||
/// @param[in] maxTiles The maximum tiles the tiles parameter can hold.
|
||||
/// @return The number of tiles returned in the tiles array.
|
||||
int getTilesAt(const int x, const int y,
|
||||
dtMeshTile const** tiles, const int maxTiles) const;
|
||||
|
||||
/// Gets the tile reference for the tile at specified grid location.
|
||||
/// @param[in] x The tile's x-location. (x, y, layer)
|
||||
/// @param[in] y The tile's y-location. (x, y, layer)
|
||||
/// @param[in] layer The tile's layer. (x, y, layer)
|
||||
/// @return The tile reference of the tile, or 0 if there is none.
|
||||
dtTileRef getTileRefAt(int x, int y, int layer) const;
|
||||
|
||||
/// Gets the tile reference for the specified tile.
|
||||
/// @param[in] tile The tile.
|
||||
/// @return The tile reference of the tile.
|
||||
dtTileRef getTileRef(const dtMeshTile* tile) const;
|
||||
|
||||
/// Gets the tile for the specified tile reference.
|
||||
/// @param[in] ref The tile reference of the tile to retrieve.
|
||||
/// @return The tile for the specified reference, or null if the
|
||||
/// reference is invalid.
|
||||
const dtMeshTile* getTileByRef(dtTileRef ref) const;
|
||||
|
||||
/// The maximum number of tiles supported by the navigation mesh.
|
||||
/// @return The maximum number of tiles supported by the navigation mesh.
|
||||
int getMaxTiles() const;
|
||||
|
||||
/// Gets the tile at the specified index.
|
||||
/// @param[in] i The tile index. [Limit: 0 >= index < #getMaxTiles()]
|
||||
/// @return The tile at the specified index.
|
||||
const dtMeshTile* getTile(int i) const;
|
||||
|
||||
/// Gets the tile and polygon for the specified polygon reference.
|
||||
/// @param[in] ref The reference for the a polygon.
|
||||
/// @param[out] tile The tile containing the polygon.
|
||||
/// @param[out] poly The polygon.
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus getTileAndPolyByRef(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const;
|
||||
|
||||
/// Returns the tile and polygon for the specified polygon reference.
|
||||
/// @param[in] ref A known valid reference for a polygon.
|
||||
/// @param[out] tile The tile containing the polygon.
|
||||
/// @param[out] poly The polygon.
|
||||
void getTileAndPolyByRefUnsafe(const dtPolyRef ref, const dtMeshTile** tile, const dtPoly** poly) const;
|
||||
|
||||
/// Checks the validity of a polygon reference.
|
||||
/// @param[in] ref The polygon reference to check.
|
||||
/// @return True if polygon reference is valid for the navigation mesh.
|
||||
bool isValidPolyRef(dtPolyRef ref) const;
|
||||
|
||||
/// Gets the polygon reference for the tile's base polygon.
|
||||
/// @param[in] tile The tile.
|
||||
/// @return The polygon reference for the base polygon in the specified tile.
|
||||
dtPolyRef getPolyRefBase(const dtMeshTile* tile) const;
|
||||
|
||||
/// Gets the endpoints for an off-mesh connection, ordered by "direction of travel".
|
||||
/// @param[in] prevRef The reference of the polygon before the connection.
|
||||
/// @param[in] polyRef The reference of the off-mesh connection polygon.
|
||||
/// @param[out] startPos The start position of the off-mesh connection. [(x, y, z)]
|
||||
/// @param[out] endPos The end position of the off-mesh connection. [(x, y, z)]
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus getOffMeshConnectionPolyEndPoints(dtPolyRef prevRef, dtPolyRef polyRef, float* startPos, float* endPos) const;
|
||||
|
||||
/// Gets the specified off-mesh connection.
|
||||
/// @param[in] ref The polygon reference of the off-mesh connection.
|
||||
/// @return The specified off-mesh connection, or null if the polygon reference is not valid.
|
||||
const dtOffMeshConnection* getOffMeshConnectionByRef(dtPolyRef ref) const;
|
||||
|
||||
/// @}
|
||||
|
||||
/// @{
|
||||
/// @name State Management
|
||||
/// These functions do not effect #dtTileRef or #dtPolyRef's.
|
||||
|
||||
/// Sets the user defined flags for the specified polygon.
|
||||
/// @param[in] ref The polygon reference.
|
||||
/// @param[in] flags The new flags for the polygon.
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus setPolyFlags(dtPolyRef ref, unsigned short flags);
|
||||
|
||||
/// Gets the user defined flags for the specified polygon.
|
||||
/// @param[in] ref The polygon reference.
|
||||
/// @param[out] resultFlags The polygon flags.
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus getPolyFlags(dtPolyRef ref, unsigned short* resultFlags) const;
|
||||
|
||||
/// Sets the user defined area for the specified polygon.
|
||||
/// @param[in] ref The polygon reference.
|
||||
/// @param[in] area The new area id for the polygon. [Limit: < #DT_MAX_AREAS]
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus setPolyArea(dtPolyRef ref, unsigned char area);
|
||||
|
||||
/// Gets the user defined area for the specified polygon.
|
||||
/// @param[in] ref The polygon reference.
|
||||
/// @param[out] resultArea The area id for the polygon.
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus getPolyArea(dtPolyRef ref, unsigned char* resultArea) const;
|
||||
|
||||
/// Gets the size of the buffer required by #storeTileState to store the specified tile's state.
|
||||
/// @param[in] tile The tile.
|
||||
/// @return The size of the buffer required to store the state.
|
||||
int getTileStateSize(const dtMeshTile* tile) const;
|
||||
|
||||
/// Stores the non-structural state of the tile in the specified buffer. (Flags, area ids, etc.)
|
||||
/// @param[in] tile The tile.
|
||||
/// @param[out] data The buffer to store the tile's state in.
|
||||
/// @param[in] maxDataSize The size of the data buffer. [Limit: >= #getTileStateSize]
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus storeTileState(const dtMeshTile* tile, unsigned char* data, const int maxDataSize) const;
|
||||
|
||||
/// Restores the state of the tile.
|
||||
/// @param[in] tile The tile.
|
||||
/// @param[in] data The new state. (Obtained from #storeTileState.)
|
||||
/// @param[in] maxDataSize The size of the state within the data buffer.
|
||||
/// @return The status flags for the operation.
|
||||
dtStatus restoreTileState(dtMeshTile* tile, const unsigned char* data, const int maxDataSize);
|
||||
|
||||
/// @}
|
||||
|
||||
/// @{
|
||||
/// @name Encoding and Decoding
|
||||
/// These functions are generally meant for internal use only.
|
||||
|
||||
/// Derives a standard polygon reference.
|
||||
/// @note This function is generally meant for internal use only.
|
||||
/// @param[in] salt The tile's salt value.
|
||||
/// @param[in] it The index of the tile.
|
||||
/// @param[in] ip The index of the polygon within the tile.
|
||||
inline dtPolyRef encodePolyId(unsigned int salt, unsigned int it, unsigned int ip) const
|
||||
{
|
||||
#ifdef DT_POLYREF64
|
||||
return ((dtPolyRef)salt << (DT_POLY_BITS+DT_TILE_BITS)) | ((dtPolyRef)it << DT_POLY_BITS) | (dtPolyRef)ip;
|
||||
#else
|
||||
return ((dtPolyRef)salt << (m_polyBits+m_tileBits)) | ((dtPolyRef)it << m_polyBits) | (dtPolyRef)ip;
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Decodes a standard polygon reference.
|
||||
/// @note This function is generally meant for internal use only.
|
||||
/// @param[in] ref The polygon reference to decode.
|
||||
/// @param[out] salt The tile's salt value.
|
||||
/// @param[out] it The index of the tile.
|
||||
/// @param[out] ip The index of the polygon within the tile.
|
||||
/// @see #encodePolyId
|
||||
inline void decodePolyId(dtPolyRef ref, unsigned int& salt, unsigned int& it, unsigned int& ip) const
|
||||
{
|
||||
#ifdef DT_POLYREF64
|
||||
const dtPolyRef saltMask = ((dtPolyRef)1<<DT_SALT_BITS)-1;
|
||||
const dtPolyRef tileMask = ((dtPolyRef)1<<DT_TILE_BITS)-1;
|
||||
const dtPolyRef polyMask = ((dtPolyRef)1<<DT_POLY_BITS)-1;
|
||||
salt = (unsigned int)((ref >> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask);
|
||||
it = (unsigned int)((ref >> DT_POLY_BITS) & tileMask);
|
||||
ip = (unsigned int)(ref & polyMask);
|
||||
#else
|
||||
const dtPolyRef saltMask = ((dtPolyRef)1<<m_saltBits)-1;
|
||||
const dtPolyRef tileMask = ((dtPolyRef)1<<m_tileBits)-1;
|
||||
const dtPolyRef polyMask = ((dtPolyRef)1<<m_polyBits)-1;
|
||||
salt = (unsigned int)((ref >> (m_polyBits+m_tileBits)) & saltMask);
|
||||
it = (unsigned int)((ref >> m_polyBits) & tileMask);
|
||||
ip = (unsigned int)(ref & polyMask);
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Extracts a tile's salt value from the specified polygon reference.
|
||||
/// @note This function is generally meant for internal use only.
|
||||
/// @param[in] ref The polygon reference.
|
||||
/// @see #encodePolyId
|
||||
inline unsigned int decodePolyIdSalt(dtPolyRef ref) const
|
||||
{
|
||||
#ifdef DT_POLYREF64
|
||||
const dtPolyRef saltMask = ((dtPolyRef)1<<DT_SALT_BITS)-1;
|
||||
return (unsigned int)((ref >> (DT_POLY_BITS+DT_TILE_BITS)) & saltMask);
|
||||
#else
|
||||
const dtPolyRef saltMask = ((dtPolyRef)1<<m_saltBits)-1;
|
||||
return (unsigned int)((ref >> (m_polyBits+m_tileBits)) & saltMask);
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Extracts the tile's index from the specified polygon reference.
|
||||
/// @note This function is generally meant for internal use only.
|
||||
/// @param[in] ref The polygon reference.
|
||||
/// @see #encodePolyId
|
||||
inline unsigned int decodePolyIdTile(dtPolyRef ref) const
|
||||
{
|
||||
#ifdef DT_POLYREF64
|
||||
const dtPolyRef tileMask = ((dtPolyRef)1<<DT_TILE_BITS)-1;
|
||||
return (unsigned int)((ref >> DT_POLY_BITS) & tileMask);
|
||||
#else
|
||||
const dtPolyRef tileMask = ((dtPolyRef)1<<m_tileBits)-1;
|
||||
return (unsigned int)((ref >> m_polyBits) & tileMask);
|
||||
#endif
|
||||
}
|
||||
|
||||
/// Extracts the polygon's index (within its tile) from the specified polygon reference.
|
||||
/// @note This function is generally meant for internal use only.
|
||||
/// @param[in] ref The polygon reference.
|
||||
/// @see #encodePolyId
|
||||
inline unsigned int decodePolyIdPoly(dtPolyRef ref) const
|
||||
{
|
||||
#ifdef DT_POLYREF64
|
||||
const dtPolyRef polyMask = ((dtPolyRef)1<<DT_POLY_BITS)-1;
|
||||
return (unsigned int)(ref & polyMask);
|
||||
#else
|
||||
const dtPolyRef polyMask = ((dtPolyRef)1<<m_polyBits)-1;
|
||||
return (unsigned int)(ref & polyMask);
|
||||
#endif
|
||||
}
|
||||
|
||||
/// @}
|
||||
|
||||
private:
|
||||
// Explicitly disabled copy constructor and copy assignment operator.
|
||||
dtNavMesh(const dtNavMesh&);
|
||||
dtNavMesh& operator=(const dtNavMesh&);
|
||||
|
||||
/// Returns pointer to tile in the tile array.
|
||||
dtMeshTile* getTile(int i);
|
||||
|
||||
/// Returns neighbour tile based on side.
|
||||
int getTilesAt(const int x, const int y,
|
||||
dtMeshTile** tiles, const int maxTiles) const;
|
||||
|
||||
/// Returns neighbour tile based on side.
|
||||
int getNeighbourTilesAt(const int x, const int y, const int side,
|
||||
dtMeshTile** tiles, const int maxTiles) const;
|
||||
|
||||
/// Returns all polygons in neighbour tile based on portal defined by the segment.
|
||||
int findConnectingPolys(const float* va, const float* vb,
|
||||
const dtMeshTile* tile, int side,
|
||||
dtPolyRef* con, float* conarea, int maxcon) const;
|
||||
|
||||
/// Builds internal polygons links for a tile.
|
||||
void connectIntLinks(dtMeshTile* tile);
|
||||
/// Builds internal polygons links for a tile.
|
||||
void baseOffMeshLinks(dtMeshTile* tile);
|
||||
|
||||
/// Builds external polygon links for a tile.
|
||||
void connectExtLinks(dtMeshTile* tile, dtMeshTile* target, int side);
|
||||
/// Builds external polygon links for a tile.
|
||||
void connectExtOffMeshLinks(dtMeshTile* tile, dtMeshTile* target, int side);
|
||||
|
||||
/// Removes external links at specified side.
|
||||
void unconnectLinks(dtMeshTile* tile, dtMeshTile* target);
|
||||
|
||||
|
||||
// TODO: These methods are duplicates from dtNavMeshQuery, but are needed for off-mesh connection finding.
|
||||
|
||||
/// Queries polygons within a tile.
|
||||
int queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
|
||||
dtPolyRef* polys, const int maxPolys) const;
|
||||
/// Find nearest polygon within a tile.
|
||||
dtPolyRef findNearestPolyInTile(const dtMeshTile* tile, const float* center,
|
||||
const float* halfExtents, float* nearestPt) const;
|
||||
/// Returns whether position is over the poly and the height at the position if so.
|
||||
bool getPolyHeight(const dtMeshTile* tile, const dtPoly* poly, const float* pos, float* height) const;
|
||||
/// Returns closest point on polygon.
|
||||
void closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const;
|
||||
|
||||
dtNavMeshParams m_params; ///< Current initialization params. TODO: do not store this info twice.
|
||||
float m_orig[3]; ///< Origin of the tile (0,0)
|
||||
float m_tileWidth, m_tileHeight; ///< Dimensions of each tile.
|
||||
int m_maxTiles; ///< Max number of tiles.
|
||||
int m_tileLutSize; ///< Tile hash lookup size (must be pot).
|
||||
int m_tileLutMask; ///< Tile hash lookup mask.
|
||||
|
||||
dtMeshTile** m_posLookup; ///< Tile hash lookup.
|
||||
dtMeshTile* m_nextFree; ///< Freelist of tiles.
|
||||
dtMeshTile* m_tiles; ///< List of tiles.
|
||||
|
||||
#ifndef DT_POLYREF64
|
||||
unsigned int m_saltBits; ///< Number of salt bits in the tile ID.
|
||||
unsigned int m_tileBits; ///< Number of tile bits in the tile ID.
|
||||
unsigned int m_polyBits; ///< Number of poly bits in the tile ID.
|
||||
#endif
|
||||
|
||||
friend class dtNavMeshQuery;
|
||||
};
|
||||
|
||||
/// Allocates a navigation mesh object using the Detour allocator.
|
||||
/// @return A navigation mesh that is ready for initialization, or null on failure.
|
||||
/// @ingroup detour
|
||||
dtNavMesh* dtAllocNavMesh();
|
||||
|
||||
/// Frees the specified navigation mesh object using the Detour allocator.
|
||||
/// @param[in] navmesh A navigation mesh allocated using #dtAllocNavMesh
|
||||
/// @ingroup detour
|
||||
void dtFreeNavMesh(dtNavMesh* navmesh);
|
||||
|
||||
#endif // DETOURNAVMESH_H
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////
|
||||
|
||||
// This section contains detailed documentation for members that don't have
|
||||
// a source file. It reduces clutter in the main section of the header.
|
||||
|
||||
/**
|
||||
|
||||
@typedef dtPolyRef
|
||||
@par
|
||||
|
||||
Polygon references are subject to the same invalidate/preserve/restore
|
||||
rules that apply to #dtTileRef's. If the #dtTileRef for the polygon's
|
||||
tile changes, the polygon reference becomes invalid.
|
||||
|
||||
Changing a polygon's flags, area id, etc. does not impact its polygon
|
||||
reference.
|
||||
|
||||
@typedef dtTileRef
|
||||
@par
|
||||
|
||||
The following changes will invalidate a tile reference:
|
||||
|
||||
- The referenced tile has been removed from the navigation mesh.
|
||||
- The navigation mesh has been initialized using a different set
|
||||
of #dtNavMeshParams.
|
||||
|
||||
A tile reference is preserved/restored if the tile is added to a navigation
|
||||
mesh initialized with the original #dtNavMeshParams and is added at the
|
||||
original reference location. (E.g. The lastRef parameter is used with
|
||||
dtNavMesh::addTile.)
|
||||
|
||||
Basically, if the storage structure of a tile changes, its associated
|
||||
tile reference changes.
|
||||
|
||||
|
||||
@var unsigned short dtPoly::neis[DT_VERTS_PER_POLYGON]
|
||||
@par
|
||||
|
||||
Each entry represents data for the edge starting at the vertex of the same index.
|
||||
E.g. The entry at index n represents the edge data for vertex[n] to vertex[n+1].
|
||||
|
||||
A value of zero indicates the edge has no polygon connection. (It makes up the
|
||||
border of the navigation mesh.)
|
||||
|
||||
The information can be extracted as follows:
|
||||
@code
|
||||
neighborRef = neis[n] & 0xff; // Get the neighbor polygon reference.
|
||||
|
||||
if (neis[n] & #DT_EX_LINK)
|
||||
{
|
||||
// The edge is an external (portal) edge.
|
||||
}
|
||||
@endcode
|
||||
|
||||
@var float dtMeshHeader::bvQuantFactor
|
||||
@par
|
||||
|
||||
This value is used for converting between world and bounding volume coordinates.
|
||||
For example:
|
||||
@code
|
||||
const float cs = 1.0f / tile->header->bvQuantFactor;
|
||||
const dtBVNode* n = &tile->bvTree[i];
|
||||
if (n->i >= 0)
|
||||
{
|
||||
// This is a leaf node.
|
||||
float worldMinX = tile->header->bmin[0] + n->bmin[0]*cs;
|
||||
float worldMinY = tile->header->bmin[0] + n->bmin[1]*cs;
|
||||
// Etc...
|
||||
}
|
||||
@endcode
|
||||
|
||||
@struct dtMeshTile
|
||||
@par
|
||||
|
||||
Tiles generally only exist within the context of a dtNavMesh object.
|
||||
|
||||
Some tile content is optional. For example, a tile may not contain any
|
||||
off-mesh connections. In this case the associated pointer will be null.
|
||||
|
||||
If a detail mesh exists it will share vertices with the base polygon mesh.
|
||||
Only the vertices unique to the detail mesh will be stored in #detailVerts.
|
||||
|
||||
@warning Tiles returned by a dtNavMesh object are not guarenteed to be populated.
|
||||
For example: The tile at a location might not have been loaded yet, or may have been removed.
|
||||
In this case, pointers will be null. So if in doubt, check the polygon count in the
|
||||
tile's header to determine if a tile has polygons defined.
|
||||
|
||||
@var float dtOffMeshConnection::pos[6]
|
||||
@par
|
||||
|
||||
For a properly built navigation mesh, vertex A will always be within the bounds of the mesh.
|
||||
Vertex B is not required to be within the bounds of the mesh.
|
||||
|
||||
*/
|
||||
@@ -0,0 +1,149 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef DETOURNAVMESHBUILDER_H
|
||||
#define DETOURNAVMESHBUILDER_H
|
||||
|
||||
#include "DetourAlloc.h"
|
||||
|
||||
/// Represents the source data used to build an navigation mesh tile.
|
||||
/// @ingroup detour
|
||||
struct dtNavMeshCreateParams
|
||||
{
|
||||
|
||||
/// @name Polygon Mesh Attributes
|
||||
/// Used to create the base navigation graph.
|
||||
/// See #rcPolyMesh for details related to these attributes.
|
||||
/// @{
|
||||
|
||||
const unsigned short* verts; ///< The polygon mesh vertices. [(x, y, z) * #vertCount] [Unit: vx]
|
||||
int vertCount; ///< The number vertices in the polygon mesh. [Limit: >= 3]
|
||||
const unsigned short* polys; ///< The polygon data. [Size: #polyCount * 2 * #nvp]
|
||||
const unsigned short* polyFlags; ///< The user defined flags assigned to each polygon. [Size: #polyCount]
|
||||
const unsigned char* polyAreas; ///< The user defined area ids assigned to each polygon. [Size: #polyCount]
|
||||
int polyCount; ///< Number of polygons in the mesh. [Limit: >= 1]
|
||||
int nvp; ///< Number maximum number of vertices per polygon. [Limit: >= 3]
|
||||
|
||||
/// @}
|
||||
/// @name Height Detail Attributes (Optional)
|
||||
/// See #rcPolyMeshDetail for details related to these attributes.
|
||||
/// @{
|
||||
|
||||
const unsigned int* detailMeshes; ///< The height detail sub-mesh data. [Size: 4 * #polyCount]
|
||||
const float* detailVerts; ///< The detail mesh vertices. [Size: 3 * #detailVertsCount] [Unit: wu]
|
||||
int detailVertsCount; ///< The number of vertices in the detail mesh.
|
||||
const unsigned char* detailTris; ///< The detail mesh triangles. [Size: 4 * #detailTriCount]
|
||||
int detailTriCount; ///< The number of triangles in the detail mesh.
|
||||
|
||||
/// @}
|
||||
/// @name Off-Mesh Connections Attributes (Optional)
|
||||
/// Used to define a custom point-to-point edge within the navigation graph, an
|
||||
/// off-mesh connection is a user defined traversable connection made up to two vertices,
|
||||
/// at least one of which resides within a navigation mesh polygon.
|
||||
/// @{
|
||||
|
||||
/// Off-mesh connection vertices. [(ax, ay, az, bx, by, bz) * #offMeshConCount] [Unit: wu]
|
||||
const float* offMeshConVerts;
|
||||
/// Off-mesh connection radii. [Size: #offMeshConCount] [Unit: wu]
|
||||
const float* offMeshConRad;
|
||||
/// User defined flags assigned to the off-mesh connections. [Size: #offMeshConCount]
|
||||
const unsigned short* offMeshConFlags;
|
||||
/// User defined area ids assigned to the off-mesh connections. [Size: #offMeshConCount]
|
||||
const unsigned char* offMeshConAreas;
|
||||
/// The permitted travel direction of the off-mesh connections. [Size: #offMeshConCount]
|
||||
///
|
||||
/// 0 = Travel only from endpoint A to endpoint B.<br/>
|
||||
/// #DT_OFFMESH_CON_BIDIR = Bidirectional travel.
|
||||
const unsigned char* offMeshConDir;
|
||||
/// The user defined ids of the off-mesh connection. [Size: #offMeshConCount]
|
||||
const unsigned int* offMeshConUserID;
|
||||
/// The number of off-mesh connections. [Limit: >= 0]
|
||||
int offMeshConCount;
|
||||
|
||||
/// @}
|
||||
/// @name Tile Attributes
|
||||
/// @note The tile grid/layer data can be left at zero if the destination is a single tile mesh.
|
||||
/// @{
|
||||
|
||||
unsigned int userId; ///< The user defined id of the tile.
|
||||
int tileX; ///< The tile's x-grid location within the multi-tile destination mesh. (Along the x-axis.)
|
||||
int tileY; ///< The tile's y-grid location within the multi-tile destination mesh. (Along the z-axis.)
|
||||
int tileLayer; ///< The tile's layer within the layered destination mesh. [Limit: >= 0] (Along the y-axis.)
|
||||
float bmin[3]; ///< The minimum bounds of the tile. [(x, y, z)] [Unit: wu]
|
||||
float bmax[3]; ///< The maximum bounds of the tile. [(x, y, z)] [Unit: wu]
|
||||
|
||||
/// @}
|
||||
/// @name General Configuration Attributes
|
||||
/// @{
|
||||
|
||||
float walkableHeight; ///< The agent height. [Unit: wu]
|
||||
float walkableRadius; ///< The agent radius. [Unit: wu]
|
||||
float walkableClimb; ///< The agent maximum traversable ledge. (Up/Down) [Unit: wu]
|
||||
float cs; ///< The xz-plane cell size of the polygon mesh. [Limit: > 0] [Unit: wu]
|
||||
float ch; ///< The y-axis cell height of the polygon mesh. [Limit: > 0] [Unit: wu]
|
||||
|
||||
/// True if a bounding volume tree should be built for the tile.
|
||||
/// @note The BVTree is not normally needed for layered navigation meshes.
|
||||
bool buildBvTree;
|
||||
|
||||
/// @}
|
||||
};
|
||||
|
||||
/// Builds navigation mesh tile data from the provided tile creation data.
|
||||
/// @ingroup detour
|
||||
/// @param[in] params Tile creation data.
|
||||
/// @param[out] outData The resulting tile data.
|
||||
/// @param[out] outDataSize The size of the tile data array.
|
||||
/// @return True if the tile data was successfully created.
|
||||
bool dtCreateNavMeshData(dtNavMeshCreateParams* params, unsigned char** outData, int* outDataSize);
|
||||
|
||||
/// Swaps the endianness of the tile data's header (#dtMeshHeader).
|
||||
/// @param[in,out] data The tile data array.
|
||||
/// @param[in] dataSize The size of the data array.
|
||||
bool dtNavMeshHeaderSwapEndian(unsigned char* data, const int dataSize);
|
||||
|
||||
/// Swaps endianness of the tile data.
|
||||
/// @param[in,out] data The tile data array.
|
||||
/// @param[in] dataSize The size of the data array.
|
||||
bool dtNavMeshDataSwapEndian(unsigned char* data, const int dataSize);
|
||||
|
||||
#endif // DETOURNAVMESHBUILDER_H
|
||||
|
||||
// This section contains detailed documentation for members that don't have
|
||||
// a source file. It reduces clutter in the main section of the header.
|
||||
|
||||
/**
|
||||
|
||||
@struct dtNavMeshCreateParams
|
||||
@par
|
||||
|
||||
This structure is used to marshal data between the Recast mesh generation pipeline and Detour navigation components.
|
||||
|
||||
See the rcPolyMesh and rcPolyMeshDetail documentation for detailed information related to mesh structure.
|
||||
|
||||
Units are usually in voxels (vx) or world units (wu). The units for voxels, grid size, and cell size
|
||||
are all based on the values of #cs and #ch.
|
||||
|
||||
The standard navigation mesh build process is to create tile data using dtCreateNavMeshData, then add the tile
|
||||
to a navigation mesh using either the dtNavMesh single tile <tt>init()</tt> function or the dtNavMesh::addTile()
|
||||
function.
|
||||
|
||||
@see dtCreateNavMeshData
|
||||
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,590 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef DETOURNAVMESHQUERY_H
|
||||
#define DETOURNAVMESHQUERY_H
|
||||
|
||||
#include "DetourNavMesh.h"
|
||||
#include "DetourStatus.h"
|
||||
|
||||
|
||||
// Define DT_VIRTUAL_QUERYFILTER if you wish to derive a custom filter from dtQueryFilter.
|
||||
// On certain platforms indirect or virtual function call is expensive. The default
|
||||
// setting is to use non-virtual functions, the actual implementations of the functions
|
||||
// are declared as inline for maximum speed.
|
||||
|
||||
//#define DT_VIRTUAL_QUERYFILTER 1
|
||||
|
||||
/// Defines polygon filtering and traversal costs for navigation mesh query operations.
|
||||
/// @ingroup detour
|
||||
class dtQueryFilter
|
||||
{
|
||||
float m_areaCost[DT_MAX_AREAS]; ///< Cost per area type. (Used by default implementation.)
|
||||
unsigned short m_includeFlags; ///< Flags for polygons that can be visited. (Used by default implementation.)
|
||||
unsigned short m_excludeFlags; ///< Flags for polygons that should not be visited. (Used by default implementation.)
|
||||
|
||||
public:
|
||||
dtQueryFilter();
|
||||
|
||||
#ifdef DT_VIRTUAL_QUERYFILTER
|
||||
virtual ~dtQueryFilter() { }
|
||||
#endif
|
||||
|
||||
/// Returns true if the polygon can be visited. (I.e. Is traversable.)
|
||||
/// @param[in] ref The reference id of the polygon test.
|
||||
/// @param[in] tile The tile containing the polygon.
|
||||
/// @param[in] poly The polygon to test.
|
||||
#ifdef DT_VIRTUAL_QUERYFILTER
|
||||
virtual bool passFilter(const dtPolyRef ref,
|
||||
const dtMeshTile* tile,
|
||||
const dtPoly* poly) const;
|
||||
#else
|
||||
bool passFilter(const dtPolyRef ref,
|
||||
const dtMeshTile* tile,
|
||||
const dtPoly* poly) const;
|
||||
#endif
|
||||
|
||||
/// Returns cost to move from the beginning to the end of a line segment
|
||||
/// that is fully contained within a polygon.
|
||||
/// @param[in] pa The start position on the edge of the previous and current polygon. [(x, y, z)]
|
||||
/// @param[in] pb The end position on the edge of the current and next polygon. [(x, y, z)]
|
||||
/// @param[in] prevRef The reference id of the previous polygon. [opt]
|
||||
/// @param[in] prevTile The tile containing the previous polygon. [opt]
|
||||
/// @param[in] prevPoly The previous polygon. [opt]
|
||||
/// @param[in] curRef The reference id of the current polygon.
|
||||
/// @param[in] curTile The tile containing the current polygon.
|
||||
/// @param[in] curPoly The current polygon.
|
||||
/// @param[in] nextRef The refernece id of the next polygon. [opt]
|
||||
/// @param[in] nextTile The tile containing the next polygon. [opt]
|
||||
/// @param[in] nextPoly The next polygon. [opt]
|
||||
#ifdef DT_VIRTUAL_QUERYFILTER
|
||||
virtual float getCost(const float* pa, const float* pb,
|
||||
const dtPolyRef prevRef, const dtMeshTile* prevTile, const dtPoly* prevPoly,
|
||||
const dtPolyRef curRef, const dtMeshTile* curTile, const dtPoly* curPoly,
|
||||
const dtPolyRef nextRef, const dtMeshTile* nextTile, const dtPoly* nextPoly) const;
|
||||
#else
|
||||
float getCost(const float* pa, const float* pb,
|
||||
const dtPolyRef prevRef, const dtMeshTile* prevTile, const dtPoly* prevPoly,
|
||||
const dtPolyRef curRef, const dtMeshTile* curTile, const dtPoly* curPoly,
|
||||
const dtPolyRef nextRef, const dtMeshTile* nextTile, const dtPoly* nextPoly) const;
|
||||
#endif
|
||||
|
||||
/// @name Getters and setters for the default implementation data.
|
||||
///@{
|
||||
|
||||
/// Returns the traversal cost of the area.
|
||||
/// @param[in] i The id of the area.
|
||||
/// @returns The traversal cost of the area.
|
||||
inline float getAreaCost(const int i) const { return m_areaCost[i]; }
|
||||
|
||||
/// Sets the traversal cost of the area.
|
||||
/// @param[in] i The id of the area.
|
||||
/// @param[in] cost The new cost of traversing the area.
|
||||
inline void setAreaCost(const int i, const float cost) { m_areaCost[i] = cost; }
|
||||
|
||||
/// Returns the include flags for the filter.
|
||||
/// Any polygons that include one or more of these flags will be
|
||||
/// included in the operation.
|
||||
inline unsigned short getIncludeFlags() const { return m_includeFlags; }
|
||||
|
||||
/// Sets the include flags for the filter.
|
||||
/// @param[in] flags The new flags.
|
||||
inline void setIncludeFlags(const unsigned short flags) { m_includeFlags = flags; }
|
||||
|
||||
/// Returns the exclude flags for the filter.
|
||||
/// Any polygons that include one ore more of these flags will be
|
||||
/// excluded from the operation.
|
||||
inline unsigned short getExcludeFlags() const { return m_excludeFlags; }
|
||||
|
||||
/// Sets the exclude flags for the filter.
|
||||
/// @param[in] flags The new flags.
|
||||
inline void setExcludeFlags(const unsigned short flags) { m_excludeFlags = flags; }
|
||||
|
||||
///@}
|
||||
|
||||
};
|
||||
|
||||
/// Provides information about raycast hit
|
||||
/// filled by dtNavMeshQuery::raycast
|
||||
/// @ingroup detour
|
||||
struct dtRaycastHit
|
||||
{
|
||||
/// The hit parameter. (FLT_MAX if no wall hit.)
|
||||
float t;
|
||||
|
||||
/// hitNormal The normal of the nearest wall hit. [(x, y, z)]
|
||||
float hitNormal[3];
|
||||
|
||||
/// The index of the edge on the final polygon where the wall was hit.
|
||||
int hitEdgeIndex;
|
||||
|
||||
/// Pointer to an array of reference ids of the visited polygons. [opt]
|
||||
dtPolyRef* path;
|
||||
|
||||
/// The number of visited polygons. [opt]
|
||||
int pathCount;
|
||||
|
||||
/// The maximum number of polygons the @p path array can hold.
|
||||
int maxPath;
|
||||
|
||||
/// The cost of the path until hit.
|
||||
float pathCost;
|
||||
};
|
||||
|
||||
/// Provides custom polygon query behavior.
|
||||
/// Used by dtNavMeshQuery::queryPolygons.
|
||||
/// @ingroup detour
|
||||
class dtPolyQuery
|
||||
{
|
||||
public:
|
||||
virtual ~dtPolyQuery();
|
||||
|
||||
/// Called for each batch of unique polygons touched by the search area in dtNavMeshQuery::queryPolygons.
|
||||
/// This can be called multiple times for a single query.
|
||||
virtual void process(const dtMeshTile* tile, dtPoly** polys, dtPolyRef* refs, int count) = 0;
|
||||
};
|
||||
|
||||
/// Provides the ability to perform pathfinding related queries against
|
||||
/// a navigation mesh.
|
||||
/// @ingroup detour
|
||||
class dtNavMeshQuery
|
||||
{
|
||||
public:
|
||||
dtNavMeshQuery();
|
||||
~dtNavMeshQuery();
|
||||
|
||||
/// Initializes the query object.
|
||||
/// @param[in] nav Pointer to the dtNavMesh object to use for all queries.
|
||||
/// @param[in] maxNodes Maximum number of search nodes. [Limits: 0 < value <= 65535]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus init(const dtNavMesh* nav, const int maxNodes);
|
||||
|
||||
/// @name Standard Pathfinding Functions
|
||||
/// @{
|
||||
|
||||
/// Finds a path from the start polygon to the end polygon.
|
||||
/// @param[in] startRef The reference id of the start polygon.
|
||||
/// @param[in] endRef The reference id of the end polygon.
|
||||
/// @param[in] startPos A position within the start polygon. [(x, y, z)]
|
||||
/// @param[in] endPos A position within the end polygon. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
|
||||
/// [(polyRef) * @p pathCount]
|
||||
/// @param[out] pathCount The number of polygons returned in the @p path array.
|
||||
/// @param[in] maxPath The maximum number of polygons the @p path array can hold. [Limit: >= 1]
|
||||
dtStatus findPath(dtPolyRef startRef, dtPolyRef endRef,
|
||||
const float* startPos, const float* endPos,
|
||||
const dtQueryFilter* filter,
|
||||
dtPolyRef* path, int* pathCount, const int maxPath) const;
|
||||
|
||||
/// Finds the straight path from the start to the end position within the polygon corridor.
|
||||
/// @param[in] startPos Path start position. [(x, y, z)]
|
||||
/// @param[in] endPos Path end position. [(x, y, z)]
|
||||
/// @param[in] path An array of polygon references that represent the path corridor.
|
||||
/// @param[in] pathSize The number of polygons in the @p path array.
|
||||
/// @param[out] straightPath Points describing the straight path. [(x, y, z) * @p straightPathCount].
|
||||
/// @param[out] straightPathFlags Flags describing each point. (See: #dtStraightPathFlags) [opt]
|
||||
/// @param[out] straightPathRefs The reference id of the polygon that is being entered at each point. [opt]
|
||||
/// @param[out] straightPathCount The number of points in the straight path.
|
||||
/// @param[in] maxStraightPath The maximum number of points the straight path arrays can hold. [Limit: > 0]
|
||||
/// @param[in] options Query options. (see: #dtStraightPathOptions)
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findStraightPath(const float* startPos, const float* endPos,
|
||||
const dtPolyRef* path, const int pathSize,
|
||||
float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
|
||||
int* straightPathCount, const int maxStraightPath, const int options = 0) const;
|
||||
|
||||
///@}
|
||||
/// @name Sliced Pathfinding Functions
|
||||
/// Common use case:
|
||||
/// -# Call initSlicedFindPath() to initialize the sliced path query.
|
||||
/// -# Call updateSlicedFindPath() until it returns complete.
|
||||
/// -# Call finalizeSlicedFindPath() to get the path.
|
||||
///@{
|
||||
|
||||
/// Initializes a sliced path query.
|
||||
/// @param[in] startRef The reference id of the start polygon.
|
||||
/// @param[in] endRef The reference id of the end polygon.
|
||||
/// @param[in] startPos A position within the start polygon. [(x, y, z)]
|
||||
/// @param[in] endPos A position within the end polygon. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[in] options query options (see: #dtFindPathOptions)
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus initSlicedFindPath(dtPolyRef startRef, dtPolyRef endRef,
|
||||
const float* startPos, const float* endPos,
|
||||
const dtQueryFilter* filter, const unsigned int options = 0);
|
||||
|
||||
/// Updates an in-progress sliced path query.
|
||||
/// @param[in] maxIter The maximum number of iterations to perform.
|
||||
/// @param[out] doneIters The actual number of iterations completed. [opt]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus updateSlicedFindPath(const int maxIter, int* doneIters);
|
||||
|
||||
/// Finalizes and returns the results of a sliced path query.
|
||||
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
|
||||
/// [(polyRef) * @p pathCount]
|
||||
/// @param[out] pathCount The number of polygons returned in the @p path array.
|
||||
/// @param[in] maxPath The max number of polygons the path array can hold. [Limit: >= 1]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus finalizeSlicedFindPath(dtPolyRef* path, int* pathCount, const int maxPath);
|
||||
|
||||
/// Finalizes and returns the results of an incomplete sliced path query, returning the path to the furthest
|
||||
/// polygon on the existing path that was visited during the search.
|
||||
/// @param[in] existing An array of polygon references for the existing path.
|
||||
/// @param[in] existingSize The number of polygon in the @p existing array.
|
||||
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
|
||||
/// [(polyRef) * @p pathCount]
|
||||
/// @param[out] pathCount The number of polygons returned in the @p path array.
|
||||
/// @param[in] maxPath The max number of polygons the @p path array can hold. [Limit: >= 1]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus finalizeSlicedFindPathPartial(const dtPolyRef* existing, const int existingSize,
|
||||
dtPolyRef* path, int* pathCount, const int maxPath);
|
||||
|
||||
///@}
|
||||
/// @name Dijkstra Search Functions
|
||||
/// @{
|
||||
|
||||
/// Finds the polygons along the navigation graph that touch the specified circle.
|
||||
/// @param[in] startRef The reference id of the polygon where the search starts.
|
||||
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
|
||||
/// @param[in] radius The radius of the search circle.
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] resultRef The reference ids of the polygons touched by the circle. [opt]
|
||||
/// @param[out] resultParent The reference ids of the parent polygons for each result.
|
||||
/// Zero if a result polygon has no parent. [opt]
|
||||
/// @param[out] resultCost The search cost from @p centerPos to the polygon. [opt]
|
||||
/// @param[out] resultCount The number of polygons found. [opt]
|
||||
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findPolysAroundCircle(dtPolyRef startRef, const float* centerPos, const float radius,
|
||||
const dtQueryFilter* filter,
|
||||
dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost,
|
||||
int* resultCount, const int maxResult) const;
|
||||
|
||||
/// Finds the polygons along the naviation graph that touch the specified convex polygon.
|
||||
/// @param[in] startRef The reference id of the polygon where the search starts.
|
||||
/// @param[in] verts The vertices describing the convex polygon. (CCW)
|
||||
/// [(x, y, z) * @p nverts]
|
||||
/// @param[in] nverts The number of vertices in the polygon.
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] resultRef The reference ids of the polygons touched by the search polygon. [opt]
|
||||
/// @param[out] resultParent The reference ids of the parent polygons for each result. Zero if a
|
||||
/// result polygon has no parent. [opt]
|
||||
/// @param[out] resultCost The search cost from the centroid point to the polygon. [opt]
|
||||
/// @param[out] resultCount The number of polygons found.
|
||||
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findPolysAroundShape(dtPolyRef startRef, const float* verts, const int nverts,
|
||||
const dtQueryFilter* filter,
|
||||
dtPolyRef* resultRef, dtPolyRef* resultParent, float* resultCost,
|
||||
int* resultCount, const int maxResult) const;
|
||||
|
||||
/// Gets a path from the explored nodes in the previous search.
|
||||
/// @param[in] endRef The reference id of the end polygon.
|
||||
/// @param[out] path An ordered list of polygon references representing the path. (Start to end.)
|
||||
/// [(polyRef) * @p pathCount]
|
||||
/// @param[out] pathCount The number of polygons returned in the @p path array.
|
||||
/// @param[in] maxPath The maximum number of polygons the @p path array can hold. [Limit: >= 0]
|
||||
/// @returns The status flags. Returns DT_FAILURE | DT_INVALID_PARAM if any parameter is wrong, or if
|
||||
/// @p endRef was not explored in the previous search. Returns DT_SUCCESS | DT_BUFFER_TOO_SMALL
|
||||
/// if @p path cannot contain the entire path. In this case it is filled to capacity with a partial path.
|
||||
/// Otherwise returns DT_SUCCESS.
|
||||
/// @remarks The result of this function depends on the state of the query object. For that reason it should only
|
||||
/// be used immediately after one of the two Dijkstra searches, findPolysAroundCircle or findPolysAroundShape.
|
||||
dtStatus getPathFromDijkstraSearch(dtPolyRef endRef, dtPolyRef* path, int* pathCount, int maxPath) const;
|
||||
|
||||
/// @}
|
||||
/// @name Local Query Functions
|
||||
///@{
|
||||
|
||||
/// Finds the polygon nearest to the specified center point.
|
||||
/// [opt] means the specified parameter can be a null pointer, in that case the output parameter will not be set.
|
||||
///
|
||||
/// @param[in] center The center of the search box. [(x, y, z)]
|
||||
/// @param[in] halfExtents The search distance along each axis. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] nearestRef The reference id of the nearest polygon. Will be set to 0 if no polygon is found.
|
||||
/// @param[out] nearestPt The nearest point on the polygon. Unchanged if no polygon is found. [opt] [(x, y, z)]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findNearestPoly(const float* center, const float* halfExtents,
|
||||
const dtQueryFilter* filter,
|
||||
dtPolyRef* nearestRef, float* nearestPt) const;
|
||||
|
||||
/// Finds the polygon nearest to the specified center point.
|
||||
/// [opt] means the specified parameter can be a null pointer, in that case the output parameter will not be set.
|
||||
///
|
||||
/// @param[in] center The center of the search box. [(x, y, z)]
|
||||
/// @param[in] halfExtents The search distance along each axis. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] nearestRef The reference id of the nearest polygon. Will be set to 0 if no polygon is found.
|
||||
/// @param[out] nearestPt The nearest point on the polygon. Unchanged if no polygon is found. [opt] [(x, y, z)]
|
||||
/// @param[out] isOverPoly Set to true if the point's X/Z coordinate lies inside the polygon, false otherwise. Unchanged if no polygon is found. [opt]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findNearestPoly(const float* center, const float* halfExtents,
|
||||
const dtQueryFilter* filter,
|
||||
dtPolyRef* nearestRef, float* nearestPt, bool* isOverPoly) const;
|
||||
|
||||
/// Finds polygons that overlap the search box.
|
||||
/// @param[in] center The center of the search box. [(x, y, z)]
|
||||
/// @param[in] halfExtents The search distance along each axis. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] polys The reference ids of the polygons that overlap the query box.
|
||||
/// @param[out] polyCount The number of polygons in the search result.
|
||||
/// @param[in] maxPolys The maximum number of polygons the search result can hold.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus queryPolygons(const float* center, const float* halfExtents,
|
||||
const dtQueryFilter* filter,
|
||||
dtPolyRef* polys, int* polyCount, const int maxPolys) const;
|
||||
|
||||
/// Finds polygons that overlap the search box.
|
||||
/// @param[in] center The center of the search box. [(x, y, z)]
|
||||
/// @param[in] halfExtents The search distance along each axis. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[in] query The query. Polygons found will be batched together and passed to this query.
|
||||
dtStatus queryPolygons(const float* center, const float* halfExtents,
|
||||
const dtQueryFilter* filter, dtPolyQuery* query) const;
|
||||
|
||||
/// Finds the non-overlapping navigation polygons in the local neighbourhood around the center position.
|
||||
/// @param[in] startRef The reference id of the polygon where the search starts.
|
||||
/// @param[in] centerPos The center of the query circle. [(x, y, z)]
|
||||
/// @param[in] radius The radius of the query circle.
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] resultRef The reference ids of the polygons touched by the circle.
|
||||
/// @param[out] resultParent The reference ids of the parent polygons for each result.
|
||||
/// Zero if a result polygon has no parent. [opt]
|
||||
/// @param[out] resultCount The number of polygons found.
|
||||
/// @param[in] maxResult The maximum number of polygons the result arrays can hold.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findLocalNeighbourhood(dtPolyRef startRef, const float* centerPos, const float radius,
|
||||
const dtQueryFilter* filter,
|
||||
dtPolyRef* resultRef, dtPolyRef* resultParent,
|
||||
int* resultCount, const int maxResult) const;
|
||||
|
||||
/// Moves from the start to the end position constrained to the navigation mesh.
|
||||
/// @param[in] startRef The reference id of the start polygon.
|
||||
/// @param[in] startPos A position of the mover within the start polygon. [(x, y, x)]
|
||||
/// @param[in] endPos The desired end position of the mover. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] resultPos The result position of the mover. [(x, y, z)]
|
||||
/// @param[out] visited The reference ids of the polygons visited during the move.
|
||||
/// @param[out] visitedCount The number of polygons visited during the move.
|
||||
/// @param[in] maxVisitedSize The maximum number of polygons the @p visited array can hold.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus moveAlongSurface(dtPolyRef startRef, const float* startPos, const float* endPos,
|
||||
const dtQueryFilter* filter,
|
||||
float* resultPos, dtPolyRef* visited, int* visitedCount, const int maxVisitedSize) const;
|
||||
|
||||
/// Casts a 'walkability' ray along the surface of the navigation mesh from
|
||||
/// the start position toward the end position.
|
||||
/// @note A wrapper around raycast(..., RaycastHit*). Retained for backward compatibility.
|
||||
/// @param[in] startRef The reference id of the start polygon.
|
||||
/// @param[in] startPos A position within the start polygon representing
|
||||
/// the start of the ray. [(x, y, z)]
|
||||
/// @param[in] endPos The position to cast the ray toward. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] t The hit parameter. (FLT_MAX if no wall hit.)
|
||||
/// @param[out] hitNormal The normal of the nearest wall hit. [(x, y, z)]
|
||||
/// @param[out] path The reference ids of the visited polygons. [opt]
|
||||
/// @param[out] pathCount The number of visited polygons. [opt]
|
||||
/// @param[in] maxPath The maximum number of polygons the @p path array can hold.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus raycast(dtPolyRef startRef, const float* startPos, const float* endPos,
|
||||
const dtQueryFilter* filter,
|
||||
float* t, float* hitNormal, dtPolyRef* path, int* pathCount, const int maxPath) const;
|
||||
|
||||
/// Casts a 'walkability' ray along the surface of the navigation mesh from
|
||||
/// the start position toward the end position.
|
||||
/// @param[in] startRef The reference id of the start polygon.
|
||||
/// @param[in] startPos A position within the start polygon representing
|
||||
/// the start of the ray. [(x, y, z)]
|
||||
/// @param[in] endPos The position to cast the ray toward. [(x, y, z)]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[in] options govern how the raycast behaves. See dtRaycastOptions
|
||||
/// @param[out] hit Pointer to a raycast hit structure which will be filled by the results.
|
||||
/// @param[in] prevRef parent of start ref. Used during for cost calculation [opt]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus raycast(dtPolyRef startRef, const float* startPos, const float* endPos,
|
||||
const dtQueryFilter* filter, const unsigned int options,
|
||||
dtRaycastHit* hit, dtPolyRef prevRef = 0) const;
|
||||
|
||||
|
||||
/// Finds the distance from the specified position to the nearest polygon wall.
|
||||
/// @param[in] startRef The reference id of the polygon containing @p centerPos.
|
||||
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
|
||||
/// @param[in] maxRadius The radius of the search circle.
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] hitDist The distance to the nearest wall from @p centerPos.
|
||||
/// @param[out] hitPos The nearest position on the wall that was hit. [(x, y, z)]
|
||||
/// @param[out] hitNormal The normalized ray formed from the wall point to the
|
||||
/// source point. [(x, y, z)]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findDistanceToWall(dtPolyRef startRef, const float* centerPos, const float maxRadius,
|
||||
const dtQueryFilter* filter,
|
||||
float* hitDist, float* hitPos, float* hitNormal) const;
|
||||
|
||||
/// Returns the segments for the specified polygon, optionally including portals.
|
||||
/// @param[in] ref The reference id of the polygon.
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[out] segmentVerts The segments. [(ax, ay, az, bx, by, bz) * segmentCount]
|
||||
/// @param[out] segmentRefs The reference ids of each segment's neighbor polygon.
|
||||
/// Or zero if the segment is a wall. [opt] [(parentRef) * @p segmentCount]
|
||||
/// @param[out] segmentCount The number of segments returned.
|
||||
/// @param[in] maxSegments The maximum number of segments the result arrays can hold.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus getPolyWallSegments(dtPolyRef ref, const dtQueryFilter* filter,
|
||||
float* segmentVerts, dtPolyRef* segmentRefs, int* segmentCount,
|
||||
const int maxSegments) const;
|
||||
|
||||
/// Returns random location on navmesh.
|
||||
/// Polygons are chosen weighted by area. The search runs in linear related to number of polygon.
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[in] frand Function returning a random number [0..1).
|
||||
/// @param[out] randomRef The reference id of the random location.
|
||||
/// @param[out] randomPt The random location.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findRandomPoint(const dtQueryFilter* filter, float (*frand)(),
|
||||
dtPolyRef* randomRef, float* randomPt) const;
|
||||
|
||||
/// Returns random location on navmesh within the reach of specified location.
|
||||
/// Polygons are chosen weighted by area. The search runs in linear related to number of polygon.
|
||||
/// The location is not exactly constrained by the circle, but it limits the visited polygons.
|
||||
/// @param[in] startRef The reference id of the polygon where the search starts.
|
||||
/// @param[in] centerPos The center of the search circle. [(x, y, z)]
|
||||
/// @param[in] maxRadius The radius of the search circle. [Units: wu]
|
||||
/// @param[in] filter The polygon filter to apply to the query.
|
||||
/// @param[in] frand Function returning a random number [0..1).
|
||||
/// @param[out] randomRef The reference id of the random location.
|
||||
/// @param[out] randomPt The random location. [(x, y, z)]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus findRandomPointAroundCircle(dtPolyRef startRef, const float* centerPos, const float maxRadius,
|
||||
const dtQueryFilter* filter, float (*frand)(),
|
||||
dtPolyRef* randomRef, float* randomPt) const;
|
||||
|
||||
/// Finds the closest point on the specified polygon.
|
||||
/// @param[in] ref The reference id of the polygon.
|
||||
/// @param[in] pos The position to check. [(x, y, z)]
|
||||
/// @param[out] closest The closest point on the polygon. [(x, y, z)]
|
||||
/// @param[out] posOverPoly True of the position is over the polygon.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus closestPointOnPoly(dtPolyRef ref, const float* pos, float* closest, bool* posOverPoly) const;
|
||||
|
||||
/// Returns a point on the boundary closest to the source point if the source point is outside the
|
||||
/// polygon's xz-bounds.
|
||||
/// @param[in] ref The reference id to the polygon.
|
||||
/// @param[in] pos The position to check. [(x, y, z)]
|
||||
/// @param[out] closest The closest point. [(x, y, z)]
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus closestPointOnPolyBoundary(dtPolyRef ref, const float* pos, float* closest) const;
|
||||
|
||||
/// Gets the height of the polygon at the provided position using the height detail. (Most accurate.)
|
||||
/// @param[in] ref The reference id of the polygon.
|
||||
/// @param[in] pos A position within the xz-bounds of the polygon. [(x, y, z)]
|
||||
/// @param[out] height The height at the surface of the polygon.
|
||||
/// @returns The status flags for the query.
|
||||
dtStatus getPolyHeight(dtPolyRef ref, const float* pos, float* height) const;
|
||||
|
||||
/// @}
|
||||
/// @name Miscellaneous Functions
|
||||
/// @{
|
||||
|
||||
/// Returns true if the polygon reference is valid and passes the filter restrictions.
|
||||
/// @param[in] ref The polygon reference to check.
|
||||
/// @param[in] filter The filter to apply.
|
||||
bool isValidPolyRef(dtPolyRef ref, const dtQueryFilter* filter) const;
|
||||
|
||||
/// Returns true if the polygon reference is in the closed list.
|
||||
/// @param[in] ref The reference id of the polygon to check.
|
||||
/// @returns True if the polygon is in closed list.
|
||||
bool isInClosedList(dtPolyRef ref) const;
|
||||
|
||||
/// Gets the node pool.
|
||||
/// @returns The node pool.
|
||||
class dtNodePool* getNodePool() const { return m_nodePool; }
|
||||
|
||||
/// Gets the navigation mesh the query object is using.
|
||||
/// @return The navigation mesh the query object is using.
|
||||
const dtNavMesh* getAttachedNavMesh() const { return m_nav; }
|
||||
|
||||
/// @}
|
||||
|
||||
private:
|
||||
// Explicitly disabled copy constructor and copy assignment operator
|
||||
dtNavMeshQuery(const dtNavMeshQuery&);
|
||||
dtNavMeshQuery& operator=(const dtNavMeshQuery&);
|
||||
|
||||
/// Queries polygons within a tile.
|
||||
void queryPolygonsInTile(const dtMeshTile* tile, const float* qmin, const float* qmax,
|
||||
const dtQueryFilter* filter, dtPolyQuery* query) const;
|
||||
|
||||
/// Returns portal points between two polygons.
|
||||
dtStatus getPortalPoints(dtPolyRef from, dtPolyRef to, float* left, float* right,
|
||||
unsigned char& fromType, unsigned char& toType) const;
|
||||
dtStatus getPortalPoints(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile,
|
||||
dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile,
|
||||
float* left, float* right) const;
|
||||
|
||||
/// Returns edge mid point between two polygons.
|
||||
dtStatus getEdgeMidPoint(dtPolyRef from, dtPolyRef to, float* mid) const;
|
||||
dtStatus getEdgeMidPoint(dtPolyRef from, const dtPoly* fromPoly, const dtMeshTile* fromTile,
|
||||
dtPolyRef to, const dtPoly* toPoly, const dtMeshTile* toTile,
|
||||
float* mid) const;
|
||||
|
||||
// Appends vertex to a straight path
|
||||
dtStatus appendVertex(const float* pos, const unsigned char flags, const dtPolyRef ref,
|
||||
float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
|
||||
int* straightPathCount, const int maxStraightPath) const;
|
||||
|
||||
// Appends intermediate portal points to a straight path.
|
||||
dtStatus appendPortals(const int startIdx, const int endIdx, const float* endPos, const dtPolyRef* path,
|
||||
float* straightPath, unsigned char* straightPathFlags, dtPolyRef* straightPathRefs,
|
||||
int* straightPathCount, const int maxStraightPath, const int options) const;
|
||||
|
||||
// Gets the path leading to the specified end node.
|
||||
dtStatus getPathToNode(struct dtNode* endNode, dtPolyRef* path, int* pathCount, int maxPath) const;
|
||||
|
||||
const dtNavMesh* m_nav; ///< Pointer to navmesh data.
|
||||
|
||||
struct dtQueryData
|
||||
{
|
||||
dtStatus status;
|
||||
struct dtNode* lastBestNode;
|
||||
float lastBestNodeCost;
|
||||
dtPolyRef startRef, endRef;
|
||||
float startPos[3], endPos[3];
|
||||
const dtQueryFilter* filter;
|
||||
unsigned int options;
|
||||
float raycastLimitSqr;
|
||||
};
|
||||
dtQueryData m_query; ///< Sliced query state.
|
||||
|
||||
class dtNodePool* m_tinyNodePool; ///< Pointer to small node pool.
|
||||
class dtNodePool* m_nodePool; ///< Pointer to node pool.
|
||||
class dtNodeQueue* m_openList; ///< Pointer to open list queue.
|
||||
};
|
||||
|
||||
/// Allocates a query object using the Detour allocator.
|
||||
/// @return An allocated query object, or null on failure.
|
||||
/// @ingroup detour
|
||||
dtNavMeshQuery* dtAllocNavMeshQuery();
|
||||
|
||||
/// Frees the specified query object using the Detour allocator.
|
||||
/// @param[in] query A query object allocated using #dtAllocNavMeshQuery
|
||||
/// @ingroup detour
|
||||
void dtFreeNavMeshQuery(dtNavMeshQuery* query);
|
||||
|
||||
#endif // DETOURNAVMESHQUERY_H
|
||||
@@ -0,0 +1,168 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef DETOURNODE_H
|
||||
#define DETOURNODE_H
|
||||
|
||||
#include "DetourNavMesh.h"
|
||||
|
||||
enum dtNodeFlags
|
||||
{
|
||||
DT_NODE_OPEN = 0x01,
|
||||
DT_NODE_CLOSED = 0x02,
|
||||
DT_NODE_PARENT_DETACHED = 0x04 // parent of the node is not adjacent. Found using raycast.
|
||||
};
|
||||
|
||||
typedef unsigned short dtNodeIndex;
|
||||
static const dtNodeIndex DT_NULL_IDX = (dtNodeIndex)~0;
|
||||
|
||||
static const int DT_NODE_PARENT_BITS = 24;
|
||||
static const int DT_NODE_STATE_BITS = 2;
|
||||
struct dtNode
|
||||
{
|
||||
float pos[3]; ///< Position of the node.
|
||||
float cost; ///< Cost from previous node to current node.
|
||||
float total; ///< Cost up to the node.
|
||||
unsigned int pidx : DT_NODE_PARENT_BITS; ///< Index to parent node.
|
||||
unsigned int state : DT_NODE_STATE_BITS; ///< extra state information. A polyRef can have multiple nodes with different extra info. see DT_MAX_STATES_PER_NODE
|
||||
unsigned int flags : 3; ///< Node flags. A combination of dtNodeFlags.
|
||||
dtPolyRef id; ///< Polygon ref the node corresponds to.
|
||||
};
|
||||
|
||||
static const int DT_MAX_STATES_PER_NODE = 1 << DT_NODE_STATE_BITS; // number of extra states per node. See dtNode::state
|
||||
|
||||
class dtNodePool
|
||||
{
|
||||
public:
|
||||
dtNodePool(int maxNodes, int hashSize);
|
||||
~dtNodePool();
|
||||
void clear();
|
||||
|
||||
// Get a dtNode by ref and extra state information. If there is none then - allocate
|
||||
// There can be more than one node for the same polyRef but with different extra state information
|
||||
dtNode* getNode(dtPolyRef id, unsigned char state=0);
|
||||
dtNode* findNode(dtPolyRef id, unsigned char state);
|
||||
unsigned int findNodes(dtPolyRef id, dtNode** nodes, const int maxNodes);
|
||||
|
||||
inline unsigned int getNodeIdx(const dtNode* node) const
|
||||
{
|
||||
if (!node) return 0;
|
||||
return (unsigned int)(node - m_nodes) + 1;
|
||||
}
|
||||
|
||||
inline dtNode* getNodeAtIdx(unsigned int idx)
|
||||
{
|
||||
if (!idx) return 0;
|
||||
return &m_nodes[idx - 1];
|
||||
}
|
||||
|
||||
inline const dtNode* getNodeAtIdx(unsigned int idx) const
|
||||
{
|
||||
if (!idx) return 0;
|
||||
return &m_nodes[idx - 1];
|
||||
}
|
||||
|
||||
inline int getMemUsed() const
|
||||
{
|
||||
return sizeof(*this) +
|
||||
sizeof(dtNode)*m_maxNodes +
|
||||
sizeof(dtNodeIndex)*m_maxNodes +
|
||||
sizeof(dtNodeIndex)*m_hashSize;
|
||||
}
|
||||
|
||||
inline int getMaxNodes() const { return m_maxNodes; }
|
||||
|
||||
inline int getHashSize() const { return m_hashSize; }
|
||||
inline dtNodeIndex getFirst(int bucket) const { return m_first[bucket]; }
|
||||
inline dtNodeIndex getNext(int i) const { return m_next[i]; }
|
||||
inline int getNodeCount() const { return m_nodeCount; }
|
||||
|
||||
private:
|
||||
// Explicitly disabled copy constructor and copy assignment operator.
|
||||
dtNodePool(const dtNodePool&);
|
||||
dtNodePool& operator=(const dtNodePool&);
|
||||
|
||||
dtNode* m_nodes;
|
||||
dtNodeIndex* m_first;
|
||||
dtNodeIndex* m_next;
|
||||
const int m_maxNodes;
|
||||
const int m_hashSize;
|
||||
int m_nodeCount;
|
||||
};
|
||||
|
||||
class dtNodeQueue
|
||||
{
|
||||
public:
|
||||
dtNodeQueue(int n);
|
||||
~dtNodeQueue();
|
||||
|
||||
inline void clear() { m_size = 0; }
|
||||
|
||||
inline dtNode* top() { return m_heap[0]; }
|
||||
|
||||
inline dtNode* pop()
|
||||
{
|
||||
dtNode* result = m_heap[0];
|
||||
m_size--;
|
||||
trickleDown(0, m_heap[m_size]);
|
||||
return result;
|
||||
}
|
||||
|
||||
inline void push(dtNode* node)
|
||||
{
|
||||
m_size++;
|
||||
bubbleUp(m_size-1, node);
|
||||
}
|
||||
|
||||
inline void modify(dtNode* node)
|
||||
{
|
||||
for (int i = 0; i < m_size; ++i)
|
||||
{
|
||||
if (m_heap[i] == node)
|
||||
{
|
||||
bubbleUp(i, node);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
inline bool empty() const { return m_size == 0; }
|
||||
|
||||
inline int getMemUsed() const
|
||||
{
|
||||
return sizeof(*this) +
|
||||
sizeof(dtNode*) * (m_capacity + 1);
|
||||
}
|
||||
|
||||
inline int getCapacity() const { return m_capacity; }
|
||||
|
||||
private:
|
||||
// Explicitly disabled copy constructor and copy assignment operator.
|
||||
dtNodeQueue(const dtNodeQueue&);
|
||||
dtNodeQueue& operator=(const dtNodeQueue&);
|
||||
|
||||
void bubbleUp(int i, dtNode* node);
|
||||
void trickleDown(int i, dtNode* node);
|
||||
|
||||
dtNode** m_heap;
|
||||
const int m_capacity;
|
||||
int m_size;
|
||||
};
|
||||
|
||||
|
||||
#endif // DETOURNODE_H
|
||||
@@ -0,0 +1,65 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef DETOURSTATUS_H
|
||||
#define DETOURSTATUS_H
|
||||
|
||||
typedef unsigned int dtStatus;
|
||||
|
||||
// High level status.
|
||||
static const unsigned int DT_FAILURE = 1u << 31; // Operation failed.
|
||||
static const unsigned int DT_SUCCESS = 1u << 30; // Operation succeed.
|
||||
static const unsigned int DT_IN_PROGRESS = 1u << 29; // Operation still in progress.
|
||||
|
||||
// Detail information for status.
|
||||
static const unsigned int DT_STATUS_DETAIL_MASK = 0x0ffffff;
|
||||
static const unsigned int DT_WRONG_MAGIC = 1 << 0; // Input data is not recognized.
|
||||
static const unsigned int DT_WRONG_VERSION = 1 << 1; // Input data is in wrong version.
|
||||
static const unsigned int DT_OUT_OF_MEMORY = 1 << 2; // Operation ran out of memory.
|
||||
static const unsigned int DT_INVALID_PARAM = 1 << 3; // An input parameter was invalid.
|
||||
static const unsigned int DT_BUFFER_TOO_SMALL = 1 << 4; // Result buffer for the query was too small to store all results.
|
||||
static const unsigned int DT_OUT_OF_NODES = 1 << 5; // Query ran out of nodes during search.
|
||||
static const unsigned int DT_PARTIAL_RESULT = 1 << 6; // Query did not reach the end location, returning best guess.
|
||||
static const unsigned int DT_ALREADY_OCCUPIED = 1 << 7; // A tile has already been assigned to the given x,y coordinate
|
||||
|
||||
|
||||
// Returns true of status is success.
|
||||
inline bool dtStatusSucceed(dtStatus status)
|
||||
{
|
||||
return (status & DT_SUCCESS) != 0;
|
||||
}
|
||||
|
||||
// Returns true of status is failure.
|
||||
inline bool dtStatusFailed(dtStatus status)
|
||||
{
|
||||
return (status & DT_FAILURE) != 0;
|
||||
}
|
||||
|
||||
// Returns true of status is in progress.
|
||||
inline bool dtStatusInProgress(dtStatus status)
|
||||
{
|
||||
return (status & DT_IN_PROGRESS) != 0;
|
||||
}
|
||||
|
||||
// Returns true if specific detail is set.
|
||||
inline bool dtStatusDetail(dtStatus status, unsigned int detail)
|
||||
{
|
||||
return (status & detail) != 0;
|
||||
}
|
||||
|
||||
#endif // DETOURSTATUS_H
|
||||
@@ -0,0 +1,50 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "DetourAlloc.h"
|
||||
|
||||
static void *dtAllocDefault(size_t size, dtAllocHint)
|
||||
{
|
||||
return malloc(size);
|
||||
}
|
||||
|
||||
static void dtFreeDefault(void *ptr)
|
||||
{
|
||||
free(ptr);
|
||||
}
|
||||
|
||||
static dtAllocFunc* sAllocFunc = dtAllocDefault;
|
||||
static dtFreeFunc* sFreeFunc = dtFreeDefault;
|
||||
|
||||
void dtAllocSetCustom(dtAllocFunc *allocFunc, dtFreeFunc *freeFunc)
|
||||
{
|
||||
sAllocFunc = allocFunc ? allocFunc : dtAllocDefault;
|
||||
sFreeFunc = freeFunc ? freeFunc : dtFreeDefault;
|
||||
}
|
||||
|
||||
void* dtAlloc(size_t size, dtAllocHint hint)
|
||||
{
|
||||
return sAllocFunc(size, hint);
|
||||
}
|
||||
|
||||
void dtFree(void* ptr)
|
||||
{
|
||||
if (ptr)
|
||||
sFreeFunc(ptr);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include "DetourAssert.h"
|
||||
|
||||
#ifndef RC_DISABLE_ASSERTS
|
||||
|
||||
static dtAssertFailFunc* sAssertFailFunc = 0;
|
||||
|
||||
void dtAssertFailSetCustom(dtAssertFailFunc *assertFailFunc)
|
||||
{
|
||||
sAssertFailFunc = assertFailFunc;
|
||||
}
|
||||
|
||||
dtAssertFailFunc* dtAssertFailGetCustom()
|
||||
{
|
||||
return sAssertFailFunc;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,387 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include "DetourCommon.h"
|
||||
#include "DetourMath.h"
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
void dtClosestPtPointTriangle(float* closest, const float* p,
|
||||
const float* a, const float* b, const float* c)
|
||||
{
|
||||
// Check if P in vertex region outside A
|
||||
float ab[3], ac[3], ap[3];
|
||||
dtVsub(ab, b, a);
|
||||
dtVsub(ac, c, a);
|
||||
dtVsub(ap, p, a);
|
||||
float d1 = dtVdot(ab, ap);
|
||||
float d2 = dtVdot(ac, ap);
|
||||
if (d1 <= 0.0f && d2 <= 0.0f)
|
||||
{
|
||||
// barycentric coordinates (1,0,0)
|
||||
dtVcopy(closest, a);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if P in vertex region outside B
|
||||
float bp[3];
|
||||
dtVsub(bp, p, b);
|
||||
float d3 = dtVdot(ab, bp);
|
||||
float d4 = dtVdot(ac, bp);
|
||||
if (d3 >= 0.0f && d4 <= d3)
|
||||
{
|
||||
// barycentric coordinates (0,1,0)
|
||||
dtVcopy(closest, b);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if P in edge region of AB, if so return projection of P onto AB
|
||||
float vc = d1*d4 - d3*d2;
|
||||
if (vc <= 0.0f && d1 >= 0.0f && d3 <= 0.0f)
|
||||
{
|
||||
// barycentric coordinates (1-v,v,0)
|
||||
float v = d1 / (d1 - d3);
|
||||
closest[0] = a[0] + v * ab[0];
|
||||
closest[1] = a[1] + v * ab[1];
|
||||
closest[2] = a[2] + v * ab[2];
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if P in vertex region outside C
|
||||
float cp[3];
|
||||
dtVsub(cp, p, c);
|
||||
float d5 = dtVdot(ab, cp);
|
||||
float d6 = dtVdot(ac, cp);
|
||||
if (d6 >= 0.0f && d5 <= d6)
|
||||
{
|
||||
// barycentric coordinates (0,0,1)
|
||||
dtVcopy(closest, c);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if P in edge region of AC, if so return projection of P onto AC
|
||||
float vb = d5*d2 - d1*d6;
|
||||
if (vb <= 0.0f && d2 >= 0.0f && d6 <= 0.0f)
|
||||
{
|
||||
// barycentric coordinates (1-w,0,w)
|
||||
float w = d2 / (d2 - d6);
|
||||
closest[0] = a[0] + w * ac[0];
|
||||
closest[1] = a[1] + w * ac[1];
|
||||
closest[2] = a[2] + w * ac[2];
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if P in edge region of BC, if so return projection of P onto BC
|
||||
float va = d3*d6 - d5*d4;
|
||||
if (va <= 0.0f && (d4 - d3) >= 0.0f && (d5 - d6) >= 0.0f)
|
||||
{
|
||||
// barycentric coordinates (0,1-w,w)
|
||||
float w = (d4 - d3) / ((d4 - d3) + (d5 - d6));
|
||||
closest[0] = b[0] + w * (c[0] - b[0]);
|
||||
closest[1] = b[1] + w * (c[1] - b[1]);
|
||||
closest[2] = b[2] + w * (c[2] - b[2]);
|
||||
return;
|
||||
}
|
||||
|
||||
// P inside face region. Compute Q through its barycentric coordinates (u,v,w)
|
||||
float denom = 1.0f / (va + vb + vc);
|
||||
float v = vb * denom;
|
||||
float w = vc * denom;
|
||||
closest[0] = a[0] + ab[0] * v + ac[0] * w;
|
||||
closest[1] = a[1] + ab[1] * v + ac[1] * w;
|
||||
closest[2] = a[2] + ab[2] * v + ac[2] * w;
|
||||
}
|
||||
|
||||
bool dtIntersectSegmentPoly2D(const float* p0, const float* p1,
|
||||
const float* verts, int nverts,
|
||||
float& tmin, float& tmax,
|
||||
int& segMin, int& segMax)
|
||||
{
|
||||
static const float EPS = 0.000001f;
|
||||
|
||||
tmin = 0;
|
||||
tmax = 1;
|
||||
segMin = -1;
|
||||
segMax = -1;
|
||||
|
||||
float dir[3];
|
||||
dtVsub(dir, p1, p0);
|
||||
|
||||
for (int i = 0, j = nverts-1; i < nverts; j=i++)
|
||||
{
|
||||
float edge[3], diff[3];
|
||||
dtVsub(edge, &verts[i*3], &verts[j*3]);
|
||||
dtVsub(diff, p0, &verts[j*3]);
|
||||
const float n = dtVperp2D(edge, diff);
|
||||
const float d = dtVperp2D(dir, edge);
|
||||
if (fabsf(d) < EPS)
|
||||
{
|
||||
// S is nearly parallel to this edge
|
||||
if (n < 0)
|
||||
return false;
|
||||
else
|
||||
continue;
|
||||
}
|
||||
const float t = n / d;
|
||||
if (d < 0)
|
||||
{
|
||||
// segment S is entering across this edge
|
||||
if (t > tmin)
|
||||
{
|
||||
tmin = t;
|
||||
segMin = j;
|
||||
// S enters after leaving polygon
|
||||
if (tmin > tmax)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// segment S is leaving across this edge
|
||||
if (t < tmax)
|
||||
{
|
||||
tmax = t;
|
||||
segMax = j;
|
||||
// S leaves before entering polygon
|
||||
if (tmax < tmin)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
float dtDistancePtSegSqr2D(const float* pt, const float* p, const float* q, float& t)
|
||||
{
|
||||
float pqx = q[0] - p[0];
|
||||
float pqz = q[2] - p[2];
|
||||
float dx = pt[0] - p[0];
|
||||
float dz = pt[2] - p[2];
|
||||
float d = pqx*pqx + pqz*pqz;
|
||||
t = pqx*dx + pqz*dz;
|
||||
if (d > 0) t /= d;
|
||||
if (t < 0) t = 0;
|
||||
else if (t > 1) t = 1;
|
||||
dx = p[0] + t*pqx - pt[0];
|
||||
dz = p[2] + t*pqz - pt[2];
|
||||
return dx*dx + dz*dz;
|
||||
}
|
||||
|
||||
void dtCalcPolyCenter(float* tc, const unsigned short* idx, int nidx, const float* verts)
|
||||
{
|
||||
tc[0] = 0.0f;
|
||||
tc[1] = 0.0f;
|
||||
tc[2] = 0.0f;
|
||||
for (int j = 0; j < nidx; ++j)
|
||||
{
|
||||
const float* v = &verts[idx[j]*3];
|
||||
tc[0] += v[0];
|
||||
tc[1] += v[1];
|
||||
tc[2] += v[2];
|
||||
}
|
||||
const float s = 1.0f / nidx;
|
||||
tc[0] *= s;
|
||||
tc[1] *= s;
|
||||
tc[2] *= s;
|
||||
}
|
||||
|
||||
bool dtClosestHeightPointTriangle(const float* p, const float* a, const float* b, const float* c, float& h)
|
||||
{
|
||||
const float EPS = 1e-6f;
|
||||
float v0[3], v1[3], v2[3];
|
||||
|
||||
dtVsub(v0, c, a);
|
||||
dtVsub(v1, b, a);
|
||||
dtVsub(v2, p, a);
|
||||
|
||||
// Compute scaled barycentric coordinates
|
||||
float denom = v0[0] * v1[2] - v0[2] * v1[0];
|
||||
if (fabsf(denom) < EPS)
|
||||
return false;
|
||||
|
||||
float u = v1[2] * v2[0] - v1[0] * v2[2];
|
||||
float v = v0[0] * v2[2] - v0[2] * v2[0];
|
||||
|
||||
if (denom < 0) {
|
||||
denom = -denom;
|
||||
u = -u;
|
||||
v = -v;
|
||||
}
|
||||
|
||||
// If point lies inside the triangle, return interpolated ycoord.
|
||||
if (u >= 0.0f && v >= 0.0f && (u + v) <= denom) {
|
||||
h = a[1] + (v0[1] * u + v1[1] * v) / denom;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// @par
|
||||
///
|
||||
/// All points are projected onto the xz-plane, so the y-values are ignored.
|
||||
bool dtPointInPolygon(const float* pt, const float* verts, const int nverts)
|
||||
{
|
||||
// TODO: Replace pnpoly with triArea2D tests?
|
||||
int i, j;
|
||||
bool c = false;
|
||||
for (i = 0, j = nverts-1; i < nverts; j = i++)
|
||||
{
|
||||
const float* vi = &verts[i*3];
|
||||
const float* vj = &verts[j*3];
|
||||
if (((vi[2] > pt[2]) != (vj[2] > pt[2])) &&
|
||||
(pt[0] < (vj[0]-vi[0]) * (pt[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )
|
||||
c = !c;
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
bool dtDistancePtPolyEdgesSqr(const float* pt, const float* verts, const int nverts,
|
||||
float* ed, float* et)
|
||||
{
|
||||
// TODO: Replace pnpoly with triArea2D tests?
|
||||
int i, j;
|
||||
bool c = false;
|
||||
for (i = 0, j = nverts-1; i < nverts; j = i++)
|
||||
{
|
||||
const float* vi = &verts[i*3];
|
||||
const float* vj = &verts[j*3];
|
||||
if (((vi[2] > pt[2]) != (vj[2] > pt[2])) &&
|
||||
(pt[0] < (vj[0]-vi[0]) * (pt[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )
|
||||
c = !c;
|
||||
ed[j] = dtDistancePtSegSqr2D(pt, vj, vi, et[j]);
|
||||
}
|
||||
return c;
|
||||
}
|
||||
|
||||
static void projectPoly(const float* axis, const float* poly, const int npoly,
|
||||
float& rmin, float& rmax)
|
||||
{
|
||||
rmin = rmax = dtVdot2D(axis, &poly[0]);
|
||||
for (int i = 1; i < npoly; ++i)
|
||||
{
|
||||
const float d = dtVdot2D(axis, &poly[i*3]);
|
||||
rmin = dtMin(rmin, d);
|
||||
rmax = dtMax(rmax, d);
|
||||
}
|
||||
}
|
||||
|
||||
inline bool overlapRange(const float amin, const float amax,
|
||||
const float bmin, const float bmax,
|
||||
const float eps)
|
||||
{
|
||||
return ((amin+eps) > bmax || (amax-eps) < bmin) ? false : true;
|
||||
}
|
||||
|
||||
/// @par
|
||||
///
|
||||
/// All vertices are projected onto the xz-plane, so the y-values are ignored.
|
||||
bool dtOverlapPolyPoly2D(const float* polya, const int npolya,
|
||||
const float* polyb, const int npolyb)
|
||||
{
|
||||
const float eps = 1e-4f;
|
||||
|
||||
for (int i = 0, j = npolya-1; i < npolya; j=i++)
|
||||
{
|
||||
const float* va = &polya[j*3];
|
||||
const float* vb = &polya[i*3];
|
||||
const float n[3] = { vb[2]-va[2], 0, -(vb[0]-va[0]) };
|
||||
float amin,amax,bmin,bmax;
|
||||
projectPoly(n, polya, npolya, amin,amax);
|
||||
projectPoly(n, polyb, npolyb, bmin,bmax);
|
||||
if (!overlapRange(amin,amax, bmin,bmax, eps))
|
||||
{
|
||||
// Found separating axis
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (int i = 0, j = npolyb-1; i < npolyb; j=i++)
|
||||
{
|
||||
const float* va = &polyb[j*3];
|
||||
const float* vb = &polyb[i*3];
|
||||
const float n[3] = { vb[2]-va[2], 0, -(vb[0]-va[0]) };
|
||||
float amin,amax,bmin,bmax;
|
||||
projectPoly(n, polya, npolya, amin,amax);
|
||||
projectPoly(n, polyb, npolyb, bmin,bmax);
|
||||
if (!overlapRange(amin,amax, bmin,bmax, eps))
|
||||
{
|
||||
// Found separating axis
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Returns a random point in a convex polygon.
|
||||
// Adapted from Graphics Gems article.
|
||||
void dtRandomPointInConvexPoly(const float* pts, const int npts, float* areas,
|
||||
const float s, const float t, float* out)
|
||||
{
|
||||
// Calc triangle araes
|
||||
float areasum = 0.0f;
|
||||
for (int i = 2; i < npts; i++) {
|
||||
areas[i] = dtTriArea2D(&pts[0], &pts[(i-1)*3], &pts[i*3]);
|
||||
areasum += dtMax(0.001f, areas[i]);
|
||||
}
|
||||
// Find sub triangle weighted by area.
|
||||
const float thr = s*areasum;
|
||||
float acc = 0.0f;
|
||||
float u = 1.0f;
|
||||
int tri = npts - 1;
|
||||
for (int i = 2; i < npts; i++) {
|
||||
const float dacc = areas[i];
|
||||
if (thr >= acc && thr < (acc+dacc))
|
||||
{
|
||||
u = (thr - acc) / dacc;
|
||||
tri = i;
|
||||
break;
|
||||
}
|
||||
acc += dacc;
|
||||
}
|
||||
|
||||
float v = dtMathSqrtf(t);
|
||||
|
||||
const float a = 1 - v;
|
||||
const float b = (1 - u) * v;
|
||||
const float c = u * v;
|
||||
const float* pa = &pts[0];
|
||||
const float* pb = &pts[(tri-1)*3];
|
||||
const float* pc = &pts[tri*3];
|
||||
|
||||
out[0] = a*pa[0] + b*pb[0] + c*pc[0];
|
||||
out[1] = a*pa[1] + b*pb[1] + c*pc[1];
|
||||
out[2] = a*pa[2] + b*pb[2] + c*pc[2];
|
||||
}
|
||||
|
||||
inline float vperpXZ(const float* a, const float* b) { return a[0]*b[2] - a[2]*b[0]; }
|
||||
|
||||
bool dtIntersectSegSeg2D(const float* ap, const float* aq,
|
||||
const float* bp, const float* bq,
|
||||
float& s, float& t)
|
||||
{
|
||||
float u[3], v[3], w[3];
|
||||
dtVsub(u,aq,ap);
|
||||
dtVsub(v,bq,bp);
|
||||
dtVsub(w,ap,bp);
|
||||
float d = vperpXZ(u,v);
|
||||
if (fabsf(d) < 1e-6f) return false;
|
||||
s = vperpXZ(v,w) / d;
|
||||
t = vperpXZ(u,w) / d;
|
||||
return true;
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,802 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <float.h>
|
||||
#include "DetourNavMesh.h"
|
||||
#include "DetourCommon.h"
|
||||
#include "DetourMath.h"
|
||||
#include "DetourNavMeshBuilder.h"
|
||||
#include "DetourAlloc.h"
|
||||
#include "DetourAssert.h"
|
||||
|
||||
static unsigned short MESH_NULL_IDX = 0xffff;
|
||||
|
||||
|
||||
struct BVItem
|
||||
{
|
||||
unsigned short bmin[3];
|
||||
unsigned short bmax[3];
|
||||
int i;
|
||||
};
|
||||
|
||||
static int compareItemX(const void* va, const void* vb)
|
||||
{
|
||||
const BVItem* a = (const BVItem*)va;
|
||||
const BVItem* b = (const BVItem*)vb;
|
||||
if (a->bmin[0] < b->bmin[0])
|
||||
return -1;
|
||||
if (a->bmin[0] > b->bmin[0])
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int compareItemY(const void* va, const void* vb)
|
||||
{
|
||||
const BVItem* a = (const BVItem*)va;
|
||||
const BVItem* b = (const BVItem*)vb;
|
||||
if (a->bmin[1] < b->bmin[1])
|
||||
return -1;
|
||||
if (a->bmin[1] > b->bmin[1])
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static int compareItemZ(const void* va, const void* vb)
|
||||
{
|
||||
const BVItem* a = (const BVItem*)va;
|
||||
const BVItem* b = (const BVItem*)vb;
|
||||
if (a->bmin[2] < b->bmin[2])
|
||||
return -1;
|
||||
if (a->bmin[2] > b->bmin[2])
|
||||
return 1;
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void calcExtends(BVItem* items, const int /*nitems*/, const int imin, const int imax,
|
||||
unsigned short* bmin, unsigned short* bmax)
|
||||
{
|
||||
bmin[0] = items[imin].bmin[0];
|
||||
bmin[1] = items[imin].bmin[1];
|
||||
bmin[2] = items[imin].bmin[2];
|
||||
|
||||
bmax[0] = items[imin].bmax[0];
|
||||
bmax[1] = items[imin].bmax[1];
|
||||
bmax[2] = items[imin].bmax[2];
|
||||
|
||||
for (int i = imin+1; i < imax; ++i)
|
||||
{
|
||||
const BVItem& it = items[i];
|
||||
if (it.bmin[0] < bmin[0]) bmin[0] = it.bmin[0];
|
||||
if (it.bmin[1] < bmin[1]) bmin[1] = it.bmin[1];
|
||||
if (it.bmin[2] < bmin[2]) bmin[2] = it.bmin[2];
|
||||
|
||||
if (it.bmax[0] > bmax[0]) bmax[0] = it.bmax[0];
|
||||
if (it.bmax[1] > bmax[1]) bmax[1] = it.bmax[1];
|
||||
if (it.bmax[2] > bmax[2]) bmax[2] = it.bmax[2];
|
||||
}
|
||||
}
|
||||
|
||||
inline int longestAxis(unsigned short x, unsigned short y, unsigned short z)
|
||||
{
|
||||
int axis = 0;
|
||||
unsigned short maxVal = x;
|
||||
if (y > maxVal)
|
||||
{
|
||||
axis = 1;
|
||||
maxVal = y;
|
||||
}
|
||||
if (z > maxVal)
|
||||
{
|
||||
axis = 2;
|
||||
}
|
||||
return axis;
|
||||
}
|
||||
|
||||
static void subdivide(BVItem* items, int nitems, int imin, int imax, int& curNode, dtBVNode* nodes)
|
||||
{
|
||||
int inum = imax - imin;
|
||||
int icur = curNode;
|
||||
|
||||
dtBVNode& node = nodes[curNode++];
|
||||
|
||||
if (inum == 1)
|
||||
{
|
||||
// Leaf
|
||||
node.bmin[0] = items[imin].bmin[0];
|
||||
node.bmin[1] = items[imin].bmin[1];
|
||||
node.bmin[2] = items[imin].bmin[2];
|
||||
|
||||
node.bmax[0] = items[imin].bmax[0];
|
||||
node.bmax[1] = items[imin].bmax[1];
|
||||
node.bmax[2] = items[imin].bmax[2];
|
||||
|
||||
node.i = items[imin].i;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Split
|
||||
calcExtends(items, nitems, imin, imax, node.bmin, node.bmax);
|
||||
|
||||
int axis = longestAxis(node.bmax[0] - node.bmin[0],
|
||||
node.bmax[1] - node.bmin[1],
|
||||
node.bmax[2] - node.bmin[2]);
|
||||
|
||||
if (axis == 0)
|
||||
{
|
||||
// Sort along x-axis
|
||||
qsort(items+imin, inum, sizeof(BVItem), compareItemX);
|
||||
}
|
||||
else if (axis == 1)
|
||||
{
|
||||
// Sort along y-axis
|
||||
qsort(items+imin, inum, sizeof(BVItem), compareItemY);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Sort along z-axis
|
||||
qsort(items+imin, inum, sizeof(BVItem), compareItemZ);
|
||||
}
|
||||
|
||||
int isplit = imin+inum/2;
|
||||
|
||||
// Left
|
||||
subdivide(items, nitems, imin, isplit, curNode, nodes);
|
||||
// Right
|
||||
subdivide(items, nitems, isplit, imax, curNode, nodes);
|
||||
|
||||
int iescape = curNode - icur;
|
||||
// Negative index means escape.
|
||||
node.i = -iescape;
|
||||
}
|
||||
}
|
||||
|
||||
static int createBVTree(dtNavMeshCreateParams* params, dtBVNode* nodes, int /*nnodes*/)
|
||||
{
|
||||
// Build tree
|
||||
float quantFactor = 1 / params->cs;
|
||||
BVItem* items = (BVItem*)dtAlloc(sizeof(BVItem)*params->polyCount, DT_ALLOC_TEMP);
|
||||
for (int i = 0; i < params->polyCount; i++)
|
||||
{
|
||||
BVItem& it = items[i];
|
||||
it.i = i;
|
||||
// Calc polygon bounds. Use detail meshes if available.
|
||||
if (params->detailMeshes)
|
||||
{
|
||||
int vb = (int)params->detailMeshes[i*4+0];
|
||||
int ndv = (int)params->detailMeshes[i*4+1];
|
||||
float bmin[3];
|
||||
float bmax[3];
|
||||
|
||||
const float* dv = ¶ms->detailVerts[vb*3];
|
||||
dtVcopy(bmin, dv);
|
||||
dtVcopy(bmax, dv);
|
||||
|
||||
for (int j = 1; j < ndv; j++)
|
||||
{
|
||||
dtVmin(bmin, &dv[j * 3]);
|
||||
dtVmax(bmax, &dv[j * 3]);
|
||||
}
|
||||
|
||||
// BV-tree uses cs for all dimensions
|
||||
it.bmin[0] = (unsigned short)dtClamp((int)((bmin[0] - params->bmin[0])*quantFactor), 0, 0xffff);
|
||||
it.bmin[1] = (unsigned short)dtClamp((int)((bmin[1] - params->bmin[1])*quantFactor), 0, 0xffff);
|
||||
it.bmin[2] = (unsigned short)dtClamp((int)((bmin[2] - params->bmin[2])*quantFactor), 0, 0xffff);
|
||||
|
||||
it.bmax[0] = (unsigned short)dtClamp((int)((bmax[0] - params->bmin[0])*quantFactor), 0, 0xffff);
|
||||
it.bmax[1] = (unsigned short)dtClamp((int)((bmax[1] - params->bmin[1])*quantFactor), 0, 0xffff);
|
||||
it.bmax[2] = (unsigned short)dtClamp((int)((bmax[2] - params->bmin[2])*quantFactor), 0, 0xffff);
|
||||
}
|
||||
else
|
||||
{
|
||||
const unsigned short* p = ¶ms->polys[i*params->nvp * 2];
|
||||
it.bmin[0] = it.bmax[0] = params->verts[p[0] * 3 + 0];
|
||||
it.bmin[1] = it.bmax[1] = params->verts[p[0] * 3 + 1];
|
||||
it.bmin[2] = it.bmax[2] = params->verts[p[0] * 3 + 2];
|
||||
|
||||
for (int j = 1; j < params->nvp; ++j)
|
||||
{
|
||||
if (p[j] == MESH_NULL_IDX) break;
|
||||
unsigned short x = params->verts[p[j] * 3 + 0];
|
||||
unsigned short y = params->verts[p[j] * 3 + 1];
|
||||
unsigned short z = params->verts[p[j] * 3 + 2];
|
||||
|
||||
if (x < it.bmin[0]) it.bmin[0] = x;
|
||||
if (y < it.bmin[1]) it.bmin[1] = y;
|
||||
if (z < it.bmin[2]) it.bmin[2] = z;
|
||||
|
||||
if (x > it.bmax[0]) it.bmax[0] = x;
|
||||
if (y > it.bmax[1]) it.bmax[1] = y;
|
||||
if (z > it.bmax[2]) it.bmax[2] = z;
|
||||
}
|
||||
// Remap y
|
||||
it.bmin[1] = (unsigned short)dtMathFloorf((float)it.bmin[1] * params->ch / params->cs);
|
||||
it.bmax[1] = (unsigned short)dtMathCeilf((float)it.bmax[1] * params->ch / params->cs);
|
||||
}
|
||||
}
|
||||
|
||||
int curNode = 0;
|
||||
subdivide(items, params->polyCount, 0, params->polyCount, curNode, nodes);
|
||||
|
||||
dtFree(items);
|
||||
|
||||
return curNode;
|
||||
}
|
||||
|
||||
static unsigned char classifyOffMeshPoint(const float* pt, const float* bmin, const float* bmax)
|
||||
{
|
||||
static const unsigned char XP = 1<<0;
|
||||
static const unsigned char ZP = 1<<1;
|
||||
static const unsigned char XM = 1<<2;
|
||||
static const unsigned char ZM = 1<<3;
|
||||
|
||||
unsigned char outcode = 0;
|
||||
outcode |= (pt[0] >= bmax[0]) ? XP : 0;
|
||||
outcode |= (pt[2] >= bmax[2]) ? ZP : 0;
|
||||
outcode |= (pt[0] < bmin[0]) ? XM : 0;
|
||||
outcode |= (pt[2] < bmin[2]) ? ZM : 0;
|
||||
|
||||
switch (outcode)
|
||||
{
|
||||
case XP: return 0;
|
||||
case XP|ZP: return 1;
|
||||
case ZP: return 2;
|
||||
case XM|ZP: return 3;
|
||||
case XM: return 4;
|
||||
case XM|ZM: return 5;
|
||||
case ZM: return 6;
|
||||
case XP|ZM: return 7;
|
||||
};
|
||||
|
||||
return 0xff;
|
||||
}
|
||||
|
||||
// TODO: Better error handling.
|
||||
|
||||
/// @par
|
||||
///
|
||||
/// The output data array is allocated using the detour allocator (dtAlloc()). The method
|
||||
/// used to free the memory will be determined by how the tile is added to the navigation
|
||||
/// mesh.
|
||||
///
|
||||
/// @see dtNavMesh, dtNavMesh::addTile()
|
||||
bool dtCreateNavMeshData(dtNavMeshCreateParams* params, unsigned char** outData, int* outDataSize)
|
||||
{
|
||||
if (params->nvp > DT_VERTS_PER_POLYGON)
|
||||
return false;
|
||||
if (params->vertCount >= 0xffff)
|
||||
return false;
|
||||
if (!params->vertCount || !params->verts)
|
||||
return false;
|
||||
if (!params->polyCount || !params->polys)
|
||||
return false;
|
||||
|
||||
const int nvp = params->nvp;
|
||||
|
||||
// Classify off-mesh connection points. We store only the connections
|
||||
// whose start point is inside the tile.
|
||||
unsigned char* offMeshConClass = 0;
|
||||
int storedOffMeshConCount = 0;
|
||||
int offMeshConLinkCount = 0;
|
||||
|
||||
if (params->offMeshConCount > 0)
|
||||
{
|
||||
offMeshConClass = (unsigned char*)dtAlloc(sizeof(unsigned char)*params->offMeshConCount*2, DT_ALLOC_TEMP);
|
||||
if (!offMeshConClass)
|
||||
return false;
|
||||
|
||||
// Find tight heigh bounds, used for culling out off-mesh start locations.
|
||||
float hmin = FLT_MAX;
|
||||
float hmax = -FLT_MAX;
|
||||
|
||||
if (params->detailVerts && params->detailVertsCount)
|
||||
{
|
||||
for (int i = 0; i < params->detailVertsCount; ++i)
|
||||
{
|
||||
const float h = params->detailVerts[i*3+1];
|
||||
hmin = dtMin(hmin,h);
|
||||
hmax = dtMax(hmax,h);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < params->vertCount; ++i)
|
||||
{
|
||||
const unsigned short* iv = ¶ms->verts[i*3];
|
||||
const float h = params->bmin[1] + iv[1] * params->ch;
|
||||
hmin = dtMin(hmin,h);
|
||||
hmax = dtMax(hmax,h);
|
||||
}
|
||||
}
|
||||
hmin -= params->walkableClimb;
|
||||
hmax += params->walkableClimb;
|
||||
float bmin[3], bmax[3];
|
||||
dtVcopy(bmin, params->bmin);
|
||||
dtVcopy(bmax, params->bmax);
|
||||
bmin[1] = hmin;
|
||||
bmax[1] = hmax;
|
||||
|
||||
for (int i = 0; i < params->offMeshConCount; ++i)
|
||||
{
|
||||
const float* p0 = ¶ms->offMeshConVerts[(i*2+0)*3];
|
||||
const float* p1 = ¶ms->offMeshConVerts[(i*2+1)*3];
|
||||
offMeshConClass[i*2+0] = classifyOffMeshPoint(p0, bmin, bmax);
|
||||
offMeshConClass[i*2+1] = classifyOffMeshPoint(p1, bmin, bmax);
|
||||
|
||||
// Zero out off-mesh start positions which are not even potentially touching the mesh.
|
||||
if (offMeshConClass[i*2+0] == 0xff)
|
||||
{
|
||||
if (p0[1] < bmin[1] || p0[1] > bmax[1])
|
||||
offMeshConClass[i*2+0] = 0;
|
||||
}
|
||||
|
||||
// Cound how many links should be allocated for off-mesh connections.
|
||||
if (offMeshConClass[i*2+0] == 0xff)
|
||||
offMeshConLinkCount++;
|
||||
if (offMeshConClass[i*2+1] == 0xff)
|
||||
offMeshConLinkCount++;
|
||||
|
||||
if (offMeshConClass[i*2+0] == 0xff)
|
||||
storedOffMeshConCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// Off-mesh connections are stored as polygons, adjust values.
|
||||
const int totPolyCount = params->polyCount + storedOffMeshConCount;
|
||||
const int totVertCount = params->vertCount + storedOffMeshConCount*2;
|
||||
|
||||
// Find portal edges which are at tile borders.
|
||||
int edgeCount = 0;
|
||||
int portalCount = 0;
|
||||
for (int i = 0; i < params->polyCount; ++i)
|
||||
{
|
||||
const unsigned short* p = ¶ms->polys[i*2*nvp];
|
||||
for (int j = 0; j < nvp; ++j)
|
||||
{
|
||||
if (p[j] == MESH_NULL_IDX) break;
|
||||
edgeCount++;
|
||||
|
||||
if (p[nvp+j] & 0x8000)
|
||||
{
|
||||
unsigned short dir = p[nvp+j] & 0xf;
|
||||
if (dir != 0xf)
|
||||
portalCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const int maxLinkCount = edgeCount + portalCount*2 + offMeshConLinkCount*2;
|
||||
|
||||
// Find unique detail vertices.
|
||||
int uniqueDetailVertCount = 0;
|
||||
int detailTriCount = 0;
|
||||
if (params->detailMeshes)
|
||||
{
|
||||
// Has detail mesh, count unique detail vertex count and use input detail tri count.
|
||||
detailTriCount = params->detailTriCount;
|
||||
for (int i = 0; i < params->polyCount; ++i)
|
||||
{
|
||||
const unsigned short* p = ¶ms->polys[i*nvp*2];
|
||||
int ndv = params->detailMeshes[i*4+1];
|
||||
int nv = 0;
|
||||
for (int j = 0; j < nvp; ++j)
|
||||
{
|
||||
if (p[j] == MESH_NULL_IDX) break;
|
||||
nv++;
|
||||
}
|
||||
ndv -= nv;
|
||||
uniqueDetailVertCount += ndv;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// No input detail mesh, build detail mesh from nav polys.
|
||||
uniqueDetailVertCount = 0; // No extra detail verts.
|
||||
detailTriCount = 0;
|
||||
for (int i = 0; i < params->polyCount; ++i)
|
||||
{
|
||||
const unsigned short* p = ¶ms->polys[i*nvp*2];
|
||||
int nv = 0;
|
||||
for (int j = 0; j < nvp; ++j)
|
||||
{
|
||||
if (p[j] == MESH_NULL_IDX) break;
|
||||
nv++;
|
||||
}
|
||||
detailTriCount += nv-2;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate data size
|
||||
const int headerSize = dtAlign4(sizeof(dtMeshHeader));
|
||||
const int vertsSize = dtAlign4(sizeof(float)*3*totVertCount);
|
||||
const int polysSize = dtAlign4(sizeof(dtPoly)*totPolyCount);
|
||||
const int linksSize = dtAlign4(sizeof(dtLink)*maxLinkCount);
|
||||
const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*params->polyCount);
|
||||
const int detailVertsSize = dtAlign4(sizeof(float)*3*uniqueDetailVertCount);
|
||||
const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*detailTriCount);
|
||||
const int bvTreeSize = params->buildBvTree ? dtAlign4(sizeof(dtBVNode)*params->polyCount*2) : 0;
|
||||
const int offMeshConsSize = dtAlign4(sizeof(dtOffMeshConnection)*storedOffMeshConCount);
|
||||
|
||||
const int dataSize = headerSize + vertsSize + polysSize + linksSize +
|
||||
detailMeshesSize + detailVertsSize + detailTrisSize +
|
||||
bvTreeSize + offMeshConsSize;
|
||||
|
||||
unsigned char* data = (unsigned char*)dtAlloc(sizeof(unsigned char)*dataSize, DT_ALLOC_PERM);
|
||||
if (!data)
|
||||
{
|
||||
dtFree(offMeshConClass);
|
||||
return false;
|
||||
}
|
||||
memset(data, 0, dataSize);
|
||||
|
||||
unsigned char* d = data;
|
||||
|
||||
dtMeshHeader* header = dtGetThenAdvanceBufferPointer<dtMeshHeader>(d, headerSize);
|
||||
float* navVerts = dtGetThenAdvanceBufferPointer<float>(d, vertsSize);
|
||||
dtPoly* navPolys = dtGetThenAdvanceBufferPointer<dtPoly>(d, polysSize);
|
||||
d += linksSize; // Ignore links; just leave enough space for them. They'll be created on load.
|
||||
dtPolyDetail* navDMeshes = dtGetThenAdvanceBufferPointer<dtPolyDetail>(d, detailMeshesSize);
|
||||
float* navDVerts = dtGetThenAdvanceBufferPointer<float>(d, detailVertsSize);
|
||||
unsigned char* navDTris = dtGetThenAdvanceBufferPointer<unsigned char>(d, detailTrisSize);
|
||||
dtBVNode* navBvtree = dtGetThenAdvanceBufferPointer<dtBVNode>(d, bvTreeSize);
|
||||
dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer<dtOffMeshConnection>(d, offMeshConsSize);
|
||||
|
||||
|
||||
// Store header
|
||||
header->magic = DT_NAVMESH_MAGIC;
|
||||
header->version = DT_NAVMESH_VERSION;
|
||||
header->x = params->tileX;
|
||||
header->y = params->tileY;
|
||||
header->layer = params->tileLayer;
|
||||
header->userId = params->userId;
|
||||
header->polyCount = totPolyCount;
|
||||
header->vertCount = totVertCount;
|
||||
header->maxLinkCount = maxLinkCount;
|
||||
dtVcopy(header->bmin, params->bmin);
|
||||
dtVcopy(header->bmax, params->bmax);
|
||||
header->detailMeshCount = params->polyCount;
|
||||
header->detailVertCount = uniqueDetailVertCount;
|
||||
header->detailTriCount = detailTriCount;
|
||||
header->bvQuantFactor = 1.0f / params->cs;
|
||||
header->offMeshBase = params->polyCount;
|
||||
header->walkableHeight = params->walkableHeight;
|
||||
header->walkableRadius = params->walkableRadius;
|
||||
header->walkableClimb = params->walkableClimb;
|
||||
header->offMeshConCount = storedOffMeshConCount;
|
||||
header->bvNodeCount = params->buildBvTree ? params->polyCount*2 : 0;
|
||||
|
||||
const int offMeshVertsBase = params->vertCount;
|
||||
const int offMeshPolyBase = params->polyCount;
|
||||
|
||||
// Store vertices
|
||||
// Mesh vertices
|
||||
for (int i = 0; i < params->vertCount; ++i)
|
||||
{
|
||||
const unsigned short* iv = ¶ms->verts[i*3];
|
||||
float* v = &navVerts[i*3];
|
||||
v[0] = params->bmin[0] + iv[0] * params->cs;
|
||||
v[1] = params->bmin[1] + iv[1] * params->ch;
|
||||
v[2] = params->bmin[2] + iv[2] * params->cs;
|
||||
}
|
||||
// Off-mesh link vertices.
|
||||
int n = 0;
|
||||
for (int i = 0; i < params->offMeshConCount; ++i)
|
||||
{
|
||||
// Only store connections which start from this tile.
|
||||
if (offMeshConClass[i*2+0] == 0xff)
|
||||
{
|
||||
const float* linkv = ¶ms->offMeshConVerts[i*2*3];
|
||||
float* v = &navVerts[(offMeshVertsBase + n*2)*3];
|
||||
dtVcopy(&v[0], &linkv[0]);
|
||||
dtVcopy(&v[3], &linkv[3]);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
|
||||
// Store polygons
|
||||
// Mesh polys
|
||||
const unsigned short* src = params->polys;
|
||||
for (int i = 0; i < params->polyCount; ++i)
|
||||
{
|
||||
dtPoly* p = &navPolys[i];
|
||||
p->vertCount = 0;
|
||||
p->flags = params->polyFlags[i];
|
||||
p->setArea(params->polyAreas[i]);
|
||||
p->setType(DT_POLYTYPE_GROUND);
|
||||
for (int j = 0; j < nvp; ++j)
|
||||
{
|
||||
if (src[j] == MESH_NULL_IDX) break;
|
||||
p->verts[j] = src[j];
|
||||
if (src[nvp+j] & 0x8000)
|
||||
{
|
||||
// Border or portal edge.
|
||||
unsigned short dir = src[nvp+j] & 0xf;
|
||||
if (dir == 0xf) // Border
|
||||
p->neis[j] = 0;
|
||||
else if (dir == 0) // Portal x-
|
||||
p->neis[j] = DT_EXT_LINK | 4;
|
||||
else if (dir == 1) // Portal z+
|
||||
p->neis[j] = DT_EXT_LINK | 2;
|
||||
else if (dir == 2) // Portal x+
|
||||
p->neis[j] = DT_EXT_LINK | 0;
|
||||
else if (dir == 3) // Portal z-
|
||||
p->neis[j] = DT_EXT_LINK | 6;
|
||||
}
|
||||
else
|
||||
{
|
||||
// Normal connection
|
||||
p->neis[j] = src[nvp+j]+1;
|
||||
}
|
||||
|
||||
p->vertCount++;
|
||||
}
|
||||
src += nvp*2;
|
||||
}
|
||||
// Off-mesh connection vertices.
|
||||
n = 0;
|
||||
for (int i = 0; i < params->offMeshConCount; ++i)
|
||||
{
|
||||
// Only store connections which start from this tile.
|
||||
if (offMeshConClass[i*2+0] == 0xff)
|
||||
{
|
||||
dtPoly* p = &navPolys[offMeshPolyBase+n];
|
||||
p->vertCount = 2;
|
||||
p->verts[0] = (unsigned short)(offMeshVertsBase + n*2+0);
|
||||
p->verts[1] = (unsigned short)(offMeshVertsBase + n*2+1);
|
||||
p->flags = params->offMeshConFlags[i];
|
||||
p->setArea(params->offMeshConAreas[i]);
|
||||
p->setType(DT_POLYTYPE_OFFMESH_CONNECTION);
|
||||
n++;
|
||||
}
|
||||
}
|
||||
|
||||
// Store detail meshes and vertices.
|
||||
// The nav polygon vertices are stored as the first vertices on each mesh.
|
||||
// We compress the mesh data by skipping them and using the navmesh coordinates.
|
||||
if (params->detailMeshes)
|
||||
{
|
||||
unsigned short vbase = 0;
|
||||
for (int i = 0; i < params->polyCount; ++i)
|
||||
{
|
||||
dtPolyDetail& dtl = navDMeshes[i];
|
||||
const int vb = (int)params->detailMeshes[i*4+0];
|
||||
const int ndv = (int)params->detailMeshes[i*4+1];
|
||||
const int nv = navPolys[i].vertCount;
|
||||
dtl.vertBase = (unsigned int)vbase;
|
||||
dtl.vertCount = (unsigned char)(ndv-nv);
|
||||
dtl.triBase = (unsigned int)params->detailMeshes[i*4+2];
|
||||
dtl.triCount = (unsigned char)params->detailMeshes[i*4+3];
|
||||
// Copy vertices except the first 'nv' verts which are equal to nav poly verts.
|
||||
if (ndv-nv)
|
||||
{
|
||||
memcpy(&navDVerts[vbase*3], ¶ms->detailVerts[(vb+nv)*3], sizeof(float)*3*(ndv-nv));
|
||||
vbase += (unsigned short)(ndv-nv);
|
||||
}
|
||||
}
|
||||
// Store triangles.
|
||||
memcpy(navDTris, params->detailTris, sizeof(unsigned char)*4*params->detailTriCount);
|
||||
}
|
||||
else
|
||||
{
|
||||
// Create dummy detail mesh by triangulating polys.
|
||||
int tbase = 0;
|
||||
for (int i = 0; i < params->polyCount; ++i)
|
||||
{
|
||||
dtPolyDetail& dtl = navDMeshes[i];
|
||||
const int nv = navPolys[i].vertCount;
|
||||
dtl.vertBase = 0;
|
||||
dtl.vertCount = 0;
|
||||
dtl.triBase = (unsigned int)tbase;
|
||||
dtl.triCount = (unsigned char)(nv-2);
|
||||
// Triangulate polygon (local indices).
|
||||
for (int j = 2; j < nv; ++j)
|
||||
{
|
||||
unsigned char* t = &navDTris[tbase*4];
|
||||
t[0] = 0;
|
||||
t[1] = (unsigned char)(j-1);
|
||||
t[2] = (unsigned char)j;
|
||||
// Bit for each edge that belongs to poly boundary.
|
||||
t[3] = (1<<2);
|
||||
if (j == 2) t[3] |= (1<<0);
|
||||
if (j == nv-1) t[3] |= (1<<4);
|
||||
tbase++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Store and create BVtree.
|
||||
if (params->buildBvTree)
|
||||
{
|
||||
createBVTree(params, navBvtree, 2*params->polyCount);
|
||||
}
|
||||
|
||||
// Store Off-Mesh connections.
|
||||
n = 0;
|
||||
for (int i = 0; i < params->offMeshConCount; ++i)
|
||||
{
|
||||
// Only store connections which start from this tile.
|
||||
if (offMeshConClass[i*2+0] == 0xff)
|
||||
{
|
||||
dtOffMeshConnection* con = &offMeshCons[n];
|
||||
con->poly = (unsigned short)(offMeshPolyBase + n);
|
||||
// Copy connection end-points.
|
||||
const float* endPts = ¶ms->offMeshConVerts[i*2*3];
|
||||
dtVcopy(&con->pos[0], &endPts[0]);
|
||||
dtVcopy(&con->pos[3], &endPts[3]);
|
||||
con->rad = params->offMeshConRad[i];
|
||||
con->flags = params->offMeshConDir[i] ? DT_OFFMESH_CON_BIDIR : 0;
|
||||
con->side = offMeshConClass[i*2+1];
|
||||
if (params->offMeshConUserID)
|
||||
con->userId = params->offMeshConUserID[i];
|
||||
n++;
|
||||
}
|
||||
}
|
||||
|
||||
dtFree(offMeshConClass);
|
||||
|
||||
*outData = data;
|
||||
*outDataSize = dataSize;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool dtNavMeshHeaderSwapEndian(unsigned char* data, const int /*dataSize*/)
|
||||
{
|
||||
dtMeshHeader* header = (dtMeshHeader*)data;
|
||||
|
||||
int swappedMagic = DT_NAVMESH_MAGIC;
|
||||
int swappedVersion = DT_NAVMESH_VERSION;
|
||||
dtSwapEndian(&swappedMagic);
|
||||
dtSwapEndian(&swappedVersion);
|
||||
|
||||
if ((header->magic != DT_NAVMESH_MAGIC || header->version != DT_NAVMESH_VERSION) &&
|
||||
(header->magic != swappedMagic || header->version != swappedVersion))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
dtSwapEndian(&header->magic);
|
||||
dtSwapEndian(&header->version);
|
||||
dtSwapEndian(&header->x);
|
||||
dtSwapEndian(&header->y);
|
||||
dtSwapEndian(&header->layer);
|
||||
dtSwapEndian(&header->userId);
|
||||
dtSwapEndian(&header->polyCount);
|
||||
dtSwapEndian(&header->vertCount);
|
||||
dtSwapEndian(&header->maxLinkCount);
|
||||
dtSwapEndian(&header->detailMeshCount);
|
||||
dtSwapEndian(&header->detailVertCount);
|
||||
dtSwapEndian(&header->detailTriCount);
|
||||
dtSwapEndian(&header->bvNodeCount);
|
||||
dtSwapEndian(&header->offMeshConCount);
|
||||
dtSwapEndian(&header->offMeshBase);
|
||||
dtSwapEndian(&header->walkableHeight);
|
||||
dtSwapEndian(&header->walkableRadius);
|
||||
dtSwapEndian(&header->walkableClimb);
|
||||
dtSwapEndian(&header->bmin[0]);
|
||||
dtSwapEndian(&header->bmin[1]);
|
||||
dtSwapEndian(&header->bmin[2]);
|
||||
dtSwapEndian(&header->bmax[0]);
|
||||
dtSwapEndian(&header->bmax[1]);
|
||||
dtSwapEndian(&header->bmax[2]);
|
||||
dtSwapEndian(&header->bvQuantFactor);
|
||||
|
||||
// Freelist index and pointers are updated when tile is added, no need to swap.
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// @par
|
||||
///
|
||||
/// @warning This function assumes that the header is in the correct endianness already.
|
||||
/// Call #dtNavMeshHeaderSwapEndian() first on the data if the data is expected to be in wrong endianness
|
||||
/// to start with. Call #dtNavMeshHeaderSwapEndian() after the data has been swapped if converting from
|
||||
/// native to foreign endianness.
|
||||
bool dtNavMeshDataSwapEndian(unsigned char* data, const int /*dataSize*/)
|
||||
{
|
||||
// Make sure the data is in right format.
|
||||
dtMeshHeader* header = (dtMeshHeader*)data;
|
||||
if (header->magic != DT_NAVMESH_MAGIC)
|
||||
return false;
|
||||
if (header->version != DT_NAVMESH_VERSION)
|
||||
return false;
|
||||
|
||||
// Patch header pointers.
|
||||
const int headerSize = dtAlign4(sizeof(dtMeshHeader));
|
||||
const int vertsSize = dtAlign4(sizeof(float)*3*header->vertCount);
|
||||
const int polysSize = dtAlign4(sizeof(dtPoly)*header->polyCount);
|
||||
const int linksSize = dtAlign4(sizeof(dtLink)*(header->maxLinkCount));
|
||||
const int detailMeshesSize = dtAlign4(sizeof(dtPolyDetail)*header->detailMeshCount);
|
||||
const int detailVertsSize = dtAlign4(sizeof(float)*3*header->detailVertCount);
|
||||
const int detailTrisSize = dtAlign4(sizeof(unsigned char)*4*header->detailTriCount);
|
||||
const int bvtreeSize = dtAlign4(sizeof(dtBVNode)*header->bvNodeCount);
|
||||
const int offMeshLinksSize = dtAlign4(sizeof(dtOffMeshConnection)*header->offMeshConCount);
|
||||
|
||||
unsigned char* d = data + headerSize;
|
||||
float* verts = dtGetThenAdvanceBufferPointer<float>(d, vertsSize);
|
||||
dtPoly* polys = dtGetThenAdvanceBufferPointer<dtPoly>(d, polysSize);
|
||||
d += linksSize; // Ignore links; they technically should be endian-swapped but all their data is overwritten on load anyway.
|
||||
//dtLink* links = dtGetThenAdvanceBufferPointer<dtLink>(d, linksSize);
|
||||
dtPolyDetail* detailMeshes = dtGetThenAdvanceBufferPointer<dtPolyDetail>(d, detailMeshesSize);
|
||||
float* detailVerts = dtGetThenAdvanceBufferPointer<float>(d, detailVertsSize);
|
||||
d += detailTrisSize; // Ignore detail tris; single bytes can't be endian-swapped.
|
||||
//unsigned char* detailTris = dtGetThenAdvanceBufferPointer<unsigned char>(d, detailTrisSize);
|
||||
dtBVNode* bvTree = dtGetThenAdvanceBufferPointer<dtBVNode>(d, bvtreeSize);
|
||||
dtOffMeshConnection* offMeshCons = dtGetThenAdvanceBufferPointer<dtOffMeshConnection>(d, offMeshLinksSize);
|
||||
|
||||
// Vertices
|
||||
for (int i = 0; i < header->vertCount*3; ++i)
|
||||
{
|
||||
dtSwapEndian(&verts[i]);
|
||||
}
|
||||
|
||||
// Polys
|
||||
for (int i = 0; i < header->polyCount; ++i)
|
||||
{
|
||||
dtPoly* p = &polys[i];
|
||||
// poly->firstLink is update when tile is added, no need to swap.
|
||||
for (int j = 0; j < DT_VERTS_PER_POLYGON; ++j)
|
||||
{
|
||||
dtSwapEndian(&p->verts[j]);
|
||||
dtSwapEndian(&p->neis[j]);
|
||||
}
|
||||
dtSwapEndian(&p->flags);
|
||||
}
|
||||
|
||||
// Links are rebuild when tile is added, no need to swap.
|
||||
|
||||
// Detail meshes
|
||||
for (int i = 0; i < header->detailMeshCount; ++i)
|
||||
{
|
||||
dtPolyDetail* pd = &detailMeshes[i];
|
||||
dtSwapEndian(&pd->vertBase);
|
||||
dtSwapEndian(&pd->triBase);
|
||||
}
|
||||
|
||||
// Detail verts
|
||||
for (int i = 0; i < header->detailVertCount*3; ++i)
|
||||
{
|
||||
dtSwapEndian(&detailVerts[i]);
|
||||
}
|
||||
|
||||
// BV-tree
|
||||
for (int i = 0; i < header->bvNodeCount; ++i)
|
||||
{
|
||||
dtBVNode* node = &bvTree[i];
|
||||
for (int j = 0; j < 3; ++j)
|
||||
{
|
||||
dtSwapEndian(&node->bmin[j]);
|
||||
dtSwapEndian(&node->bmax[j]);
|
||||
}
|
||||
dtSwapEndian(&node->i);
|
||||
}
|
||||
|
||||
// Off-mesh Connections.
|
||||
for (int i = 0; i < header->offMeshConCount; ++i)
|
||||
{
|
||||
dtOffMeshConnection* con = &offMeshCons[i];
|
||||
for (int j = 0; j < 6; ++j)
|
||||
dtSwapEndian(&con->pos[j]);
|
||||
dtSwapEndian(&con->rad);
|
||||
dtSwapEndian(&con->poly);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,200 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include "DetourNode.h"
|
||||
#include "DetourAlloc.h"
|
||||
#include "DetourAssert.h"
|
||||
#include "DetourCommon.h"
|
||||
#include <string.h>
|
||||
|
||||
#ifdef DT_POLYREF64
|
||||
// From Thomas Wang, https://gist.github.com/badboy/6267743
|
||||
inline unsigned int dtHashRef(dtPolyRef a)
|
||||
{
|
||||
a = (~a) + (a << 18); // a = (a << 18) - a - 1;
|
||||
a = a ^ (a >> 31);
|
||||
a = a * 21; // a = (a + (a << 2)) + (a << 4);
|
||||
a = a ^ (a >> 11);
|
||||
a = a + (a << 6);
|
||||
a = a ^ (a >> 22);
|
||||
return (unsigned int)a;
|
||||
}
|
||||
#else
|
||||
inline unsigned int dtHashRef(dtPolyRef a)
|
||||
{
|
||||
a += ~(a<<15);
|
||||
a ^= (a>>10);
|
||||
a += (a<<3);
|
||||
a ^= (a>>6);
|
||||
a += ~(a<<11);
|
||||
a ^= (a>>16);
|
||||
return (unsigned int)a;
|
||||
}
|
||||
#endif
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
dtNodePool::dtNodePool(int maxNodes, int hashSize) :
|
||||
m_nodes(0),
|
||||
m_first(0),
|
||||
m_next(0),
|
||||
m_maxNodes(maxNodes),
|
||||
m_hashSize(hashSize),
|
||||
m_nodeCount(0)
|
||||
{
|
||||
dtAssert(dtNextPow2(m_hashSize) == (unsigned int)m_hashSize);
|
||||
// pidx is special as 0 means "none" and 1 is the first node. For that reason
|
||||
// we have 1 fewer nodes available than the number of values it can contain.
|
||||
dtAssert(m_maxNodes > 0 && m_maxNodes <= DT_NULL_IDX && m_maxNodes <= (1 << DT_NODE_PARENT_BITS) - 1);
|
||||
|
||||
m_nodes = (dtNode*)dtAlloc(sizeof(dtNode)*m_maxNodes, DT_ALLOC_PERM);
|
||||
m_next = (dtNodeIndex*)dtAlloc(sizeof(dtNodeIndex)*m_maxNodes, DT_ALLOC_PERM);
|
||||
m_first = (dtNodeIndex*)dtAlloc(sizeof(dtNodeIndex)*hashSize, DT_ALLOC_PERM);
|
||||
|
||||
dtAssert(m_nodes);
|
||||
dtAssert(m_next);
|
||||
dtAssert(m_first);
|
||||
|
||||
memset(m_first, 0xff, sizeof(dtNodeIndex)*m_hashSize);
|
||||
memset(m_next, 0xff, sizeof(dtNodeIndex)*m_maxNodes);
|
||||
}
|
||||
|
||||
dtNodePool::~dtNodePool()
|
||||
{
|
||||
dtFree(m_nodes);
|
||||
dtFree(m_next);
|
||||
dtFree(m_first);
|
||||
}
|
||||
|
||||
void dtNodePool::clear()
|
||||
{
|
||||
memset(m_first, 0xff, sizeof(dtNodeIndex)*m_hashSize);
|
||||
m_nodeCount = 0;
|
||||
}
|
||||
|
||||
unsigned int dtNodePool::findNodes(dtPolyRef id, dtNode** nodes, const int maxNodes)
|
||||
{
|
||||
int n = 0;
|
||||
unsigned int bucket = dtHashRef(id) & (m_hashSize-1);
|
||||
dtNodeIndex i = m_first[bucket];
|
||||
while (i != DT_NULL_IDX)
|
||||
{
|
||||
if (m_nodes[i].id == id)
|
||||
{
|
||||
if (n >= maxNodes)
|
||||
return n;
|
||||
nodes[n++] = &m_nodes[i];
|
||||
}
|
||||
i = m_next[i];
|
||||
}
|
||||
|
||||
return n;
|
||||
}
|
||||
|
||||
dtNode* dtNodePool::findNode(dtPolyRef id, unsigned char state)
|
||||
{
|
||||
unsigned int bucket = dtHashRef(id) & (m_hashSize-1);
|
||||
dtNodeIndex i = m_first[bucket];
|
||||
while (i != DT_NULL_IDX)
|
||||
{
|
||||
if (m_nodes[i].id == id && m_nodes[i].state == state)
|
||||
return &m_nodes[i];
|
||||
i = m_next[i];
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
dtNode* dtNodePool::getNode(dtPolyRef id, unsigned char state)
|
||||
{
|
||||
unsigned int bucket = dtHashRef(id) & (m_hashSize-1);
|
||||
dtNodeIndex i = m_first[bucket];
|
||||
dtNode* node = 0;
|
||||
while (i != DT_NULL_IDX)
|
||||
{
|
||||
if (m_nodes[i].id == id && m_nodes[i].state == state)
|
||||
return &m_nodes[i];
|
||||
i = m_next[i];
|
||||
}
|
||||
|
||||
if (m_nodeCount >= m_maxNodes)
|
||||
return 0;
|
||||
|
||||
i = (dtNodeIndex)m_nodeCount;
|
||||
m_nodeCount++;
|
||||
|
||||
// Init node
|
||||
node = &m_nodes[i];
|
||||
node->pidx = 0;
|
||||
node->cost = 0;
|
||||
node->total = 0;
|
||||
node->id = id;
|
||||
node->state = state;
|
||||
node->flags = 0;
|
||||
|
||||
m_next[i] = m_first[bucket];
|
||||
m_first[bucket] = i;
|
||||
|
||||
return node;
|
||||
}
|
||||
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////////////////
|
||||
dtNodeQueue::dtNodeQueue(int n) :
|
||||
m_heap(0),
|
||||
m_capacity(n),
|
||||
m_size(0)
|
||||
{
|
||||
dtAssert(m_capacity > 0);
|
||||
|
||||
m_heap = (dtNode**)dtAlloc(sizeof(dtNode*)*(m_capacity+1), DT_ALLOC_PERM);
|
||||
dtAssert(m_heap);
|
||||
}
|
||||
|
||||
dtNodeQueue::~dtNodeQueue()
|
||||
{
|
||||
dtFree(m_heap);
|
||||
}
|
||||
|
||||
void dtNodeQueue::bubbleUp(int i, dtNode* node)
|
||||
{
|
||||
int parent = (i-1)/2;
|
||||
// note: (index > 0) means there is a parent
|
||||
while ((i > 0) && (m_heap[parent]->total > node->total))
|
||||
{
|
||||
m_heap[i] = m_heap[parent];
|
||||
i = parent;
|
||||
parent = (i-1)/2;
|
||||
}
|
||||
m_heap[i] = node;
|
||||
}
|
||||
|
||||
void dtNodeQueue::trickleDown(int i, dtNode* node)
|
||||
{
|
||||
int child = (i*2)+1;
|
||||
while (child < m_size)
|
||||
{
|
||||
if (((child+1) < m_size) &&
|
||||
(m_heap[child]->total > m_heap[child+1]->total))
|
||||
{
|
||||
child++;
|
||||
}
|
||||
m_heap[i] = m_heap[child];
|
||||
i = child;
|
||||
child = (i*2)+1;
|
||||
}
|
||||
bubbleUp(i, node);
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
Copyright (c) 2009 Mikko Mononen [email protected]
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must not
|
||||
claim that you wrote the original software. If you use this software
|
||||
in a product, an acknowledgment in the product documentation would be
|
||||
appreciated but is not required.
|
||||
2. Altered source versions must be plainly marked as such, and must not be
|
||||
misrepresented as being the original software.
|
||||
3. This notice may not be removed or altered from any source distribution.
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,391 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef RECASTALLOC_H
|
||||
#define RECASTALLOC_H
|
||||
|
||||
#include "RecastAssert.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/// Provides hint values to the memory allocator on how long the
|
||||
/// memory is expected to be used.
|
||||
enum rcAllocHint
|
||||
{
|
||||
RC_ALLOC_PERM, ///< Memory will persist after a function call.
|
||||
RC_ALLOC_TEMP ///< Memory used temporarily within a function.
|
||||
};
|
||||
|
||||
/// A memory allocation function.
|
||||
/// @param[in] size The size, in bytes of memory, to allocate.
|
||||
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
|
||||
/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
|
||||
/// @see rcAllocSetCustom
|
||||
typedef void* (rcAllocFunc)(size_t size, rcAllocHint hint);
|
||||
|
||||
/// A memory deallocation function.
|
||||
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAllocFunc.
|
||||
/// @see rcAllocSetCustom
|
||||
typedef void (rcFreeFunc)(void* ptr);
|
||||
|
||||
/// Sets the base custom allocation functions to be used by Recast.
|
||||
/// @param[in] allocFunc The memory allocation function to be used by #rcAlloc
|
||||
/// @param[in] freeFunc The memory de-allocation function to be used by #rcFree
|
||||
/// @see rcAlloc, rcFree
|
||||
void rcAllocSetCustom(rcAllocFunc *allocFunc, rcFreeFunc *freeFunc);
|
||||
|
||||
/// Allocates a memory block.
|
||||
/// @param[in] size The size, in bytes of memory, to allocate.
|
||||
/// @param[in] hint A hint to the allocator on how long the memory is expected to be in use.
|
||||
/// @return A pointer to the beginning of the allocated memory block, or null if the allocation failed.
|
||||
/// @see rcFree, rcAllocSetCustom
|
||||
void* rcAlloc(size_t size, rcAllocHint hint);
|
||||
|
||||
/// Deallocates a memory block. If @p ptr is NULL, this does nothing.
|
||||
/// @warning This function leaves the value of @p ptr unchanged. So it still
|
||||
/// points to the same (now invalid) location, and not to null.
|
||||
/// @param[in] ptr A pointer to a memory block previously allocated using #rcAlloc.
|
||||
/// @see rcAlloc, rcAllocSetCustom
|
||||
void rcFree(void* ptr);
|
||||
|
||||
/// An implementation of operator new usable for placement new. The default one is part of STL (which we don't use).
|
||||
/// rcNewTag is a dummy type used to differentiate our operator from the STL one, in case users import both Recast
|
||||
/// and STL.
|
||||
struct rcNewTag {};
|
||||
inline void* operator new(size_t, const rcNewTag&, void* p) { return p; }
|
||||
inline void operator delete(void*, const rcNewTag&, void*) {}
|
||||
|
||||
/// Signed to avoid warnings when comparing to int loop indexes, and common error with comparing to zero.
|
||||
/// MSVC2010 has a bug where ssize_t is unsigned (!!!).
|
||||
typedef intptr_t rcSizeType;
|
||||
#define RC_SIZE_MAX INTPTR_MAX
|
||||
|
||||
/// Macros to hint to the compiler about the likeliest branch. Please add a benchmark that demonstrates a performance
|
||||
/// improvement before introducing use cases.
|
||||
#if defined(__GNUC__) || defined(__clang__)
|
||||
#define rcLikely(x) __builtin_expect((x), true)
|
||||
#define rcUnlikely(x) __builtin_expect((x), false)
|
||||
#else
|
||||
#define rcLikely(x) (x)
|
||||
#define rcUnlikely(x) (x)
|
||||
#endif
|
||||
|
||||
/// Variable-sized storage type. Mimics the interface of std::vector<T> with some notable differences:
|
||||
/// * Uses rcAlloc()/rcFree() to handle storage.
|
||||
/// * No support for a custom allocator.
|
||||
/// * Uses signed size instead of size_t to avoid warnings in for loops: "for (int i = 0; i < foo.size(); i++)"
|
||||
/// * Omits methods of limited utility: insert/erase, (bad performance), at (we don't use exceptions), operator=.
|
||||
/// * assign() and the pre-sizing constructor follow C++11 semantics -- they don't construct a temporary if no value is provided.
|
||||
/// * push_back() and resize() support adding values from the current vector. Range-based constructors and assign(begin, end) do not.
|
||||
/// * No specialization for bool.
|
||||
template <typename T, rcAllocHint H>
|
||||
class rcVectorBase
|
||||
{
|
||||
rcSizeType m_size;
|
||||
rcSizeType m_cap;
|
||||
T* m_data;
|
||||
// Constructs a T at the give address with either the copy constructor or the default.
|
||||
static void construct(T* p, const T& v) { ::new(rcNewTag(), (void*)p) T(v); }
|
||||
static void construct(T* p) { ::new(rcNewTag(), (void*)p) T; }
|
||||
static void construct_range(T* begin, T* end);
|
||||
static void construct_range(T* begin, T* end, const T& value);
|
||||
static void copy_range(T* dst, const T* begin, const T* end);
|
||||
void destroy_range(rcSizeType begin, rcSizeType end);
|
||||
// Creates an array of the given size, copies all of this vector's data into it, and returns it.
|
||||
T* allocate_and_copy(rcSizeType size);
|
||||
void resize_impl(rcSizeType size, const T* value);
|
||||
// Requires: min_capacity > m_cap.
|
||||
rcSizeType get_new_capacity(rcSizeType min_capacity);
|
||||
public:
|
||||
typedef rcSizeType size_type;
|
||||
typedef T value_type;
|
||||
|
||||
rcVectorBase() : m_size(0), m_cap(0), m_data(0) {}
|
||||
rcVectorBase(const rcVectorBase<T, H>& other) : m_size(0), m_cap(0), m_data(0) { assign(other.begin(), other.end()); }
|
||||
explicit rcVectorBase(rcSizeType count) : m_size(0), m_cap(0), m_data(0) { resize(count); }
|
||||
rcVectorBase(rcSizeType count, const T& value) : m_size(0), m_cap(0), m_data(0) { resize(count, value); }
|
||||
rcVectorBase(const T* begin, const T* end) : m_size(0), m_cap(0), m_data(0) { assign(begin, end); }
|
||||
~rcVectorBase() { destroy_range(0, m_size); rcFree(m_data); }
|
||||
|
||||
// Unlike in std::vector, we return a bool to indicate whether the alloc was successful.
|
||||
bool reserve(rcSizeType size);
|
||||
|
||||
void assign(rcSizeType count, const T& value) { clear(); resize(count, value); }
|
||||
void assign(const T* begin, const T* end);
|
||||
|
||||
void resize(rcSizeType size) { resize_impl(size, NULL); }
|
||||
void resize(rcSizeType size, const T& value) { resize_impl(size, &value); }
|
||||
// Not implemented as resize(0) because resize requires T to be default-constructible.
|
||||
void clear() { destroy_range(0, m_size); m_size = 0; }
|
||||
|
||||
void push_back(const T& value);
|
||||
void pop_back() { rcAssert(m_size > 0); back().~T(); m_size--; }
|
||||
|
||||
rcSizeType size() const { return m_size; }
|
||||
rcSizeType capacity() const { return m_cap; }
|
||||
bool empty() const { return size() == 0; }
|
||||
|
||||
const T& operator[](rcSizeType i) const { rcAssert(i >= 0 && i < m_size); return m_data[i]; }
|
||||
T& operator[](rcSizeType i) { rcAssert(i >= 0 && i < m_size); return m_data[i]; }
|
||||
|
||||
const T& front() const { rcAssert(m_size); return m_data[0]; }
|
||||
T& front() { rcAssert(m_size); return m_data[0]; }
|
||||
const T& back() const { rcAssert(m_size); return m_data[m_size - 1]; }
|
||||
T& back() { rcAssert(m_size); return m_data[m_size - 1]; }
|
||||
const T* data() const { return m_data; }
|
||||
T* data() { return m_data; }
|
||||
|
||||
T* begin() { return m_data; }
|
||||
T* end() { return m_data + m_size; }
|
||||
const T* begin() const { return m_data; }
|
||||
const T* end() const { return m_data + m_size; }
|
||||
|
||||
void swap(rcVectorBase<T, H>& other);
|
||||
|
||||
// Explicitly deleted.
|
||||
rcVectorBase& operator=(const rcVectorBase<T, H>& other);
|
||||
};
|
||||
|
||||
template<typename T, rcAllocHint H>
|
||||
bool rcVectorBase<T, H>::reserve(rcSizeType count)
|
||||
{
|
||||
if (count <= m_cap)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
T* new_data = allocate_and_copy(count);
|
||||
if (!new_data)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
destroy_range(0, m_size);
|
||||
rcFree(m_data);
|
||||
m_data = new_data;
|
||||
m_cap = count;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T, rcAllocHint H>
|
||||
T* rcVectorBase<T, H>::allocate_and_copy(rcSizeType size)
|
||||
{
|
||||
rcAssert(RC_SIZE_MAX / static_cast<rcSizeType>(sizeof(T)) >= size);
|
||||
T* new_data = static_cast<T*>(rcAlloc(sizeof(T) * size, H));
|
||||
if (new_data)
|
||||
{
|
||||
copy_range(new_data, m_data, m_data + m_size);
|
||||
}
|
||||
return new_data;
|
||||
}
|
||||
|
||||
template <typename T, rcAllocHint H>
|
||||
void rcVectorBase<T, H>::assign(const T* begin, const T* end)
|
||||
{
|
||||
clear();
|
||||
reserve(end - begin);
|
||||
m_size = end - begin;
|
||||
copy_range(m_data, begin, end);
|
||||
}
|
||||
|
||||
template <typename T, rcAllocHint H>
|
||||
void rcVectorBase<T, H>::push_back(const T& value)
|
||||
{
|
||||
// rcLikely increases performance by ~50% on BM_rcVector_PushPreallocated,
|
||||
// and by ~2-5% on BM_rcVector_Push.
|
||||
if (rcLikely(m_size < m_cap))
|
||||
{
|
||||
construct(m_data + m_size++, value);
|
||||
return;
|
||||
}
|
||||
|
||||
const rcSizeType new_cap = get_new_capacity(m_cap + 1);
|
||||
T* data = allocate_and_copy(new_cap);
|
||||
// construct between allocate and destroy+free in case value is
|
||||
// in this vector.
|
||||
construct(data + m_size, value);
|
||||
destroy_range(0, m_size);
|
||||
m_size++;
|
||||
m_cap = new_cap;
|
||||
rcFree(m_data);
|
||||
m_data = data;
|
||||
}
|
||||
|
||||
template <typename T, rcAllocHint H>
|
||||
rcSizeType rcVectorBase<T, H>::get_new_capacity(rcSizeType min_capacity)
|
||||
{
|
||||
rcAssert(min_capacity <= RC_SIZE_MAX);
|
||||
if (rcUnlikely(m_cap >= RC_SIZE_MAX / 2))
|
||||
{
|
||||
return RC_SIZE_MAX;
|
||||
}
|
||||
return 2 * m_cap > min_capacity ? 2 * m_cap : min_capacity;
|
||||
}
|
||||
|
||||
template <typename T, rcAllocHint H>
|
||||
void rcVectorBase<T, H>::resize_impl(rcSizeType size, const T* value)
|
||||
{
|
||||
if (size < m_size)
|
||||
{
|
||||
destroy_range(size, m_size);
|
||||
m_size = size;
|
||||
}
|
||||
else if (size > m_size)
|
||||
{
|
||||
if (size <= m_cap)
|
||||
{
|
||||
if (value)
|
||||
{
|
||||
construct_range(m_data + m_size, m_data + size, *value);
|
||||
}
|
||||
else
|
||||
{
|
||||
construct_range(m_data + m_size, m_data + size);
|
||||
}
|
||||
m_size = size;
|
||||
}
|
||||
else
|
||||
{
|
||||
const rcSizeType new_cap = get_new_capacity(size);
|
||||
T* new_data = allocate_and_copy(new_cap);
|
||||
// We defer deconstructing/freeing old data until after constructing
|
||||
// new elements in case "value" is there.
|
||||
if (value)
|
||||
{
|
||||
construct_range(new_data + m_size, new_data + size, *value);
|
||||
}
|
||||
else
|
||||
{
|
||||
construct_range(new_data + m_size, new_data + size);
|
||||
}
|
||||
destroy_range(0, m_size);
|
||||
rcFree(m_data);
|
||||
m_data = new_data;
|
||||
m_cap = new_cap;
|
||||
m_size = size;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T, rcAllocHint H>
|
||||
void rcVectorBase<T, H>::swap(rcVectorBase<T, H>& other)
|
||||
{
|
||||
// TODO: Reorganize headers so we can use rcSwap here.
|
||||
rcSizeType tmp_cap = other.m_cap;
|
||||
rcSizeType tmp_size = other.m_size;
|
||||
T* tmp_data = other.m_data;
|
||||
|
||||
other.m_cap = m_cap;
|
||||
other.m_size = m_size;
|
||||
other.m_data = m_data;
|
||||
|
||||
m_cap = tmp_cap;
|
||||
m_size = tmp_size;
|
||||
m_data = tmp_data;
|
||||
}
|
||||
|
||||
// static
|
||||
template <typename T, rcAllocHint H>
|
||||
void rcVectorBase<T, H>::construct_range(T* begin, T* end)
|
||||
{
|
||||
for (T* p = begin; p < end; p++)
|
||||
{
|
||||
construct(p);
|
||||
}
|
||||
}
|
||||
|
||||
// static
|
||||
template <typename T, rcAllocHint H>
|
||||
void rcVectorBase<T, H>::construct_range(T* begin, T* end, const T& value)
|
||||
{
|
||||
for (T* p = begin; p < end; p++)
|
||||
{
|
||||
construct(p, value);
|
||||
}
|
||||
}
|
||||
|
||||
// static
|
||||
template <typename T, rcAllocHint H>
|
||||
void rcVectorBase<T, H>::copy_range(T* dst, const T* begin, const T* end)
|
||||
{
|
||||
for (rcSizeType i = 0 ; i < end - begin; i++)
|
||||
{
|
||||
construct(dst + i, begin[i]);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T, rcAllocHint H>
|
||||
void rcVectorBase<T, H>::destroy_range(rcSizeType begin, rcSizeType end)
|
||||
{
|
||||
for (rcSizeType i = begin; i < end; i++)
|
||||
{
|
||||
m_data[i].~T();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class rcTempVector : public rcVectorBase<T, RC_ALLOC_TEMP>
|
||||
{
|
||||
typedef rcVectorBase<T, RC_ALLOC_TEMP> Base;
|
||||
public:
|
||||
rcTempVector() : Base() {}
|
||||
explicit rcTempVector(rcSizeType size) : Base(size) {}
|
||||
rcTempVector(rcSizeType size, const T& value) : Base(size, value) {}
|
||||
rcTempVector(const rcTempVector<T>& other) : Base(other) {}
|
||||
rcTempVector(const T* begin, const T* end) : Base(begin, end) {}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class rcPermVector : public rcVectorBase<T, RC_ALLOC_PERM>
|
||||
{
|
||||
typedef rcVectorBase<T, RC_ALLOC_PERM> Base;
|
||||
public:
|
||||
rcPermVector() : Base() {}
|
||||
explicit rcPermVector(rcSizeType size) : Base(size) {}
|
||||
rcPermVector(rcSizeType size, const T& value) : Base(size, value) {}
|
||||
rcPermVector(const rcPermVector<T>& other) : Base(other) {}
|
||||
rcPermVector(const T* begin, const T* end) : Base(begin, end) {}
|
||||
};
|
||||
|
||||
/// A simple helper class used to delete an array when it goes out of scope.
|
||||
/// @note This class is rarely if ever used by the end user.
|
||||
template<class T> class rcScopedDelete
|
||||
{
|
||||
T* ptr;
|
||||
public:
|
||||
|
||||
/// Constructs an instance with a null pointer.
|
||||
inline rcScopedDelete() : ptr(0) {}
|
||||
|
||||
/// Constructs an instance with the specified pointer.
|
||||
/// @param[in] p An pointer to an allocated array.
|
||||
inline rcScopedDelete(T* p) : ptr(p) {}
|
||||
inline ~rcScopedDelete() { rcFree(ptr); }
|
||||
|
||||
/// The root array pointer.
|
||||
/// @return The root array pointer.
|
||||
inline operator T*() { return ptr; }
|
||||
|
||||
private:
|
||||
// Explicitly disabled copy constructor and copy assignment operator.
|
||||
rcScopedDelete(const rcScopedDelete&);
|
||||
rcScopedDelete& operator=(const rcScopedDelete&);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,49 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#ifndef RECASTASSERT_H
|
||||
#define RECASTASSERT_H
|
||||
|
||||
/// An assertion failure callback function.
|
||||
/// @param[in] expression Asserted expression.
|
||||
/// @param[in] file Filename of the failed assertion.
|
||||
/// @param[in] line Line number of the failed assertion.
|
||||
/// @see rcAssertFailSetCustom
|
||||
typedef void (rcAssertFailFunc)(const char* expression, const char* file, int line);
|
||||
|
||||
/// Sets the base custom assertion failure callback function to be used by Recast.
|
||||
/// @param[in] assertFailFunc The function to be used in case of failure of #dtAssert
|
||||
void rcAssertFailSetCustom(rcAssertFailFunc* assertFailFunc);
|
||||
|
||||
/// Gets the base custom assertion failure function to be used by Recast.
|
||||
rcAssertFailFunc* rcAssertFailGetCustom();
|
||||
|
||||
#ifdef RC_DISABLE_ASSERTS
|
||||
// From https://web.archive.org/web/20210117002833/http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/
|
||||
# define rcAssert(x) do { (void)sizeof(x); } while ((void)(__LINE__==-1), false)
|
||||
#else
|
||||
# include <assert.h>
|
||||
# define rcAssert(expression) \
|
||||
{ \
|
||||
rcAssertFailFunc* failFunc = rcAssertFailGetCustom(); \
|
||||
if (failFunc == NULL) { assert(expression); } \
|
||||
else if (!(expression)) { (*failFunc)(#expression, __FILE__, __LINE__); } \
|
||||
}
|
||||
#endif // !defined(RC_DISABLE_ASSERTS)
|
||||
|
||||
#endif // RECASTASSERT_H
|
||||
@@ -0,0 +1,542 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include "Recast.h"
|
||||
#include "RecastAlloc.h"
|
||||
#include "RecastAssert.h"
|
||||
|
||||
#include <math.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
/// Allocates and constructs an object of the given type, returning a pointer.
|
||||
/// @param[in] allocLifetime Allocation lifetime hint
|
||||
template<typename T>
|
||||
T* rcNew(const rcAllocHint allocLifetime)
|
||||
{
|
||||
T* ptr = (T*)rcAlloc(sizeof(T), allocLifetime);
|
||||
::new(rcNewTag(), (void*)ptr) T();
|
||||
return ptr;
|
||||
}
|
||||
|
||||
/// Destroys and frees an object allocated with rcNew.
|
||||
/// @param[in] ptr The object pointer to delete.
|
||||
template<typename T>
|
||||
void rcDelete(T* ptr)
|
||||
{
|
||||
if (ptr)
|
||||
{
|
||||
ptr->~T();
|
||||
rcFree((void*)ptr);
|
||||
}
|
||||
}
|
||||
} // anonymous namespace
|
||||
|
||||
float rcSqrt(float x)
|
||||
{
|
||||
return sqrtf(x);
|
||||
}
|
||||
|
||||
void rcContext::log(const rcLogCategory category, const char* format, ...)
|
||||
{
|
||||
if (!m_logEnabled)
|
||||
{
|
||||
return;
|
||||
}
|
||||
static const int MSG_SIZE = 512;
|
||||
char msg[MSG_SIZE];
|
||||
va_list argList;
|
||||
va_start(argList, format);
|
||||
int len = vsnprintf(msg, MSG_SIZE, format, argList);
|
||||
if (len >= MSG_SIZE)
|
||||
{
|
||||
len = MSG_SIZE - 1;
|
||||
msg[MSG_SIZE - 1] = '\0';
|
||||
|
||||
const char* errorMessage = "Log message was truncated";
|
||||
doLog(RC_LOG_ERROR, errorMessage, (int)strlen(errorMessage));
|
||||
}
|
||||
va_end(argList);
|
||||
doLog(category, msg, len);
|
||||
}
|
||||
|
||||
void rcContext::doResetLog()
|
||||
{
|
||||
// Defined out of line to fix the weak v-tables warning
|
||||
}
|
||||
|
||||
rcHeightfield* rcAllocHeightfield()
|
||||
{
|
||||
return rcNew<rcHeightfield>(RC_ALLOC_PERM);
|
||||
}
|
||||
|
||||
void rcFreeHeightField(rcHeightfield* heightfield)
|
||||
{
|
||||
rcDelete(heightfield);
|
||||
}
|
||||
|
||||
rcHeightfield::rcHeightfield()
|
||||
: width()
|
||||
, height()
|
||||
, bmin()
|
||||
, bmax()
|
||||
, cs()
|
||||
, ch()
|
||||
, spans()
|
||||
, pools()
|
||||
, freelist()
|
||||
{
|
||||
}
|
||||
|
||||
rcHeightfield::~rcHeightfield()
|
||||
{
|
||||
// Delete span array.
|
||||
rcFree(spans);
|
||||
// Delete span pools.
|
||||
while (pools)
|
||||
{
|
||||
rcSpanPool* next = pools->next;
|
||||
rcFree(pools);
|
||||
pools = next;
|
||||
}
|
||||
}
|
||||
|
||||
rcCompactHeightfield* rcAllocCompactHeightfield()
|
||||
{
|
||||
return rcNew<rcCompactHeightfield>(RC_ALLOC_PERM);
|
||||
}
|
||||
|
||||
void rcFreeCompactHeightfield(rcCompactHeightfield* compactHeightfield)
|
||||
{
|
||||
rcDelete(compactHeightfield);
|
||||
}
|
||||
|
||||
rcCompactHeightfield::rcCompactHeightfield()
|
||||
: width()
|
||||
, height()
|
||||
, spanCount()
|
||||
, walkableHeight()
|
||||
, walkableClimb()
|
||||
, borderSize()
|
||||
, maxDistance()
|
||||
, maxRegions()
|
||||
, bmin()
|
||||
, bmax()
|
||||
, cs()
|
||||
, ch()
|
||||
, cells()
|
||||
, spans()
|
||||
, dist()
|
||||
, areas()
|
||||
{
|
||||
}
|
||||
|
||||
rcCompactHeightfield::~rcCompactHeightfield()
|
||||
{
|
||||
rcFree(cells);
|
||||
rcFree(spans);
|
||||
rcFree(dist);
|
||||
rcFree(areas);
|
||||
}
|
||||
|
||||
rcHeightfieldLayerSet* rcAllocHeightfieldLayerSet()
|
||||
{
|
||||
return rcNew<rcHeightfieldLayerSet>(RC_ALLOC_PERM);
|
||||
}
|
||||
|
||||
void rcFreeHeightfieldLayerSet(rcHeightfieldLayerSet* layerSet)
|
||||
{
|
||||
rcDelete(layerSet);
|
||||
}
|
||||
|
||||
rcHeightfieldLayerSet::rcHeightfieldLayerSet()
|
||||
: layers()
|
||||
, nlayers()
|
||||
{
|
||||
}
|
||||
|
||||
rcHeightfieldLayerSet::~rcHeightfieldLayerSet()
|
||||
{
|
||||
for (int i = 0; i < nlayers; ++i)
|
||||
{
|
||||
rcFree(layers[i].heights);
|
||||
rcFree(layers[i].areas);
|
||||
rcFree(layers[i].cons);
|
||||
}
|
||||
rcFree(layers);
|
||||
}
|
||||
|
||||
|
||||
rcContourSet* rcAllocContourSet()
|
||||
{
|
||||
return rcNew<rcContourSet>(RC_ALLOC_PERM);
|
||||
}
|
||||
|
||||
void rcFreeContourSet(rcContourSet* contourSet)
|
||||
{
|
||||
rcDelete(contourSet);
|
||||
}
|
||||
|
||||
rcContourSet::rcContourSet()
|
||||
: conts()
|
||||
, nconts()
|
||||
, bmin()
|
||||
, bmax()
|
||||
, cs()
|
||||
, ch()
|
||||
, width()
|
||||
, height()
|
||||
, borderSize()
|
||||
, maxError()
|
||||
{
|
||||
}
|
||||
|
||||
rcContourSet::~rcContourSet()
|
||||
{
|
||||
for (int i = 0; i < nconts; ++i)
|
||||
{
|
||||
rcFree(conts[i].verts);
|
||||
rcFree(conts[i].rverts);
|
||||
}
|
||||
rcFree(conts);
|
||||
}
|
||||
|
||||
rcPolyMesh* rcAllocPolyMesh()
|
||||
{
|
||||
return rcNew<rcPolyMesh>(RC_ALLOC_PERM);
|
||||
}
|
||||
|
||||
void rcFreePolyMesh(rcPolyMesh* polyMesh)
|
||||
{
|
||||
rcDelete(polyMesh);
|
||||
}
|
||||
|
||||
rcPolyMesh::rcPolyMesh()
|
||||
: verts()
|
||||
, polys()
|
||||
, regs()
|
||||
, flags()
|
||||
, areas()
|
||||
, nverts()
|
||||
, npolys()
|
||||
, maxpolys()
|
||||
, nvp()
|
||||
, bmin()
|
||||
, bmax()
|
||||
, cs()
|
||||
, ch()
|
||||
, borderSize()
|
||||
, maxEdgeError()
|
||||
{
|
||||
}
|
||||
|
||||
rcPolyMesh::~rcPolyMesh()
|
||||
{
|
||||
rcFree(verts);
|
||||
rcFree(polys);
|
||||
rcFree(regs);
|
||||
rcFree(flags);
|
||||
rcFree(areas);
|
||||
}
|
||||
|
||||
rcPolyMeshDetail* rcAllocPolyMeshDetail()
|
||||
{
|
||||
return rcNew<rcPolyMeshDetail>(RC_ALLOC_PERM);
|
||||
}
|
||||
|
||||
void rcFreePolyMeshDetail(rcPolyMeshDetail* detailMesh)
|
||||
{
|
||||
if (detailMesh == NULL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
rcFree(detailMesh->meshes);
|
||||
rcFree(detailMesh->verts);
|
||||
rcFree(detailMesh->tris);
|
||||
rcFree(detailMesh);
|
||||
}
|
||||
|
||||
rcPolyMeshDetail::rcPolyMeshDetail()
|
||||
: meshes()
|
||||
, verts()
|
||||
, tris()
|
||||
, nmeshes()
|
||||
, nverts()
|
||||
, ntris()
|
||||
{
|
||||
}
|
||||
|
||||
void rcCalcBounds(const float* verts, int numVerts, float* minBounds, float* maxBounds)
|
||||
{
|
||||
// Calculate bounding box.
|
||||
rcVcopy(minBounds, verts);
|
||||
rcVcopy(maxBounds, verts);
|
||||
for (int i = 1; i < numVerts; ++i)
|
||||
{
|
||||
const float* v = &verts[i * 3];
|
||||
rcVmin(minBounds, v);
|
||||
rcVmax(maxBounds, v);
|
||||
}
|
||||
}
|
||||
|
||||
void rcCalcGridSize(const float* minBounds, const float* maxBounds, const float cellSize, int* sizeX, int* sizeZ)
|
||||
{
|
||||
*sizeX = (int)((maxBounds[0] - minBounds[0]) / cellSize + 0.5f);
|
||||
*sizeZ = (int)((maxBounds[2] - minBounds[2]) / cellSize + 0.5f);
|
||||
}
|
||||
|
||||
bool rcCreateHeightfield(rcContext* context, rcHeightfield& heightfield, int sizeX, int sizeZ,
|
||||
const float* minBounds, const float* maxBounds,
|
||||
float cellSize, float cellHeight)
|
||||
{
|
||||
rcIgnoreUnused(context);
|
||||
|
||||
heightfield.width = sizeX;
|
||||
heightfield.height = sizeZ;
|
||||
rcVcopy(heightfield.bmin, minBounds);
|
||||
rcVcopy(heightfield.bmax, maxBounds);
|
||||
heightfield.cs = cellSize;
|
||||
heightfield.ch = cellHeight;
|
||||
heightfield.spans = (rcSpan**)rcAlloc(sizeof(rcSpan*) * heightfield.width * heightfield.height, RC_ALLOC_PERM);
|
||||
if (!heightfield.spans)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
memset(heightfield.spans, 0, sizeof(rcSpan*) * heightfield.width * heightfield.height);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void calcTriNormal(const float* v0, const float* v1, const float* v2, float* faceNormal)
|
||||
{
|
||||
float e0[3], e1[3];
|
||||
rcVsub(e0, v1, v0);
|
||||
rcVsub(e1, v2, v0);
|
||||
rcVcross(faceNormal, e0, e1);
|
||||
rcVnormalize(faceNormal);
|
||||
}
|
||||
|
||||
void rcMarkWalkableTriangles(rcContext* context, const float walkableSlopeAngle,
|
||||
const float* verts, const int numVerts,
|
||||
const int* tris, const int numTris,
|
||||
unsigned char* triAreaIDs)
|
||||
{
|
||||
rcIgnoreUnused(context);
|
||||
rcIgnoreUnused(numVerts);
|
||||
|
||||
const float walkableThr = cosf(walkableSlopeAngle / 180.0f * RC_PI);
|
||||
|
||||
float norm[3];
|
||||
|
||||
for (int i = 0; i < numTris; ++i)
|
||||
{
|
||||
const int* tri = &tris[i * 3];
|
||||
calcTriNormal(&verts[tri[0] * 3], &verts[tri[1] * 3], &verts[tri[2] * 3], norm);
|
||||
// Check if the face is walkable.
|
||||
if (norm[1] > walkableThr)
|
||||
{
|
||||
triAreaIDs[i] = RC_WALKABLE_AREA;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void rcClearUnwalkableTriangles(rcContext* context, const float walkableSlopeAngle,
|
||||
const float* verts, int numVerts,
|
||||
const int* tris, int numTris,
|
||||
unsigned char* triAreaIDs)
|
||||
{
|
||||
rcIgnoreUnused(context);
|
||||
rcIgnoreUnused(numVerts);
|
||||
|
||||
// The minimum Y value for a face normal of a triangle with a walkable slope.
|
||||
const float walkableLimitY = cosf(walkableSlopeAngle / 180.0f * RC_PI);
|
||||
|
||||
float faceNormal[3];
|
||||
for (int i = 0; i < numTris; ++i)
|
||||
{
|
||||
const int* tri = &tris[i * 3];
|
||||
calcTriNormal(&verts[tri[0] * 3], &verts[tri[1] * 3], &verts[tri[2] * 3], faceNormal);
|
||||
// Check if the face is walkable.
|
||||
if (faceNormal[1] <= walkableLimitY)
|
||||
{
|
||||
triAreaIDs[i] = RC_NULL_AREA;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int rcGetHeightFieldSpanCount(rcContext* context, const rcHeightfield& heightfield)
|
||||
{
|
||||
rcIgnoreUnused(context);
|
||||
|
||||
const int numCols = heightfield.width * heightfield.height;
|
||||
int spanCount = 0;
|
||||
for (int columnIndex = 0; columnIndex < numCols; ++columnIndex)
|
||||
{
|
||||
for (rcSpan* span = heightfield.spans[columnIndex]; span != NULL; span = span->next)
|
||||
{
|
||||
if (span->area != RC_NULL_AREA)
|
||||
{
|
||||
spanCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
return spanCount;
|
||||
}
|
||||
|
||||
bool rcBuildCompactHeightfield(rcContext* context, const int walkableHeight, const int walkableClimb,
|
||||
const rcHeightfield& heightfield, rcCompactHeightfield& compactHeightfield)
|
||||
{
|
||||
rcAssert(context);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_BUILD_COMPACTHEIGHTFIELD);
|
||||
|
||||
const int xSize = heightfield.width;
|
||||
const int zSize = heightfield.height;
|
||||
const int spanCount = rcGetHeightFieldSpanCount(context, heightfield);
|
||||
|
||||
// Fill in header.
|
||||
compactHeightfield.width = xSize;
|
||||
compactHeightfield.height = zSize;
|
||||
compactHeightfield.spanCount = spanCount;
|
||||
compactHeightfield.walkableHeight = walkableHeight;
|
||||
compactHeightfield.walkableClimb = walkableClimb;
|
||||
compactHeightfield.maxRegions = 0;
|
||||
rcVcopy(compactHeightfield.bmin, heightfield.bmin);
|
||||
rcVcopy(compactHeightfield.bmax, heightfield.bmax);
|
||||
compactHeightfield.bmax[1] += walkableHeight * heightfield.ch;
|
||||
compactHeightfield.cs = heightfield.cs;
|
||||
compactHeightfield.ch = heightfield.ch;
|
||||
compactHeightfield.cells = (rcCompactCell*)rcAlloc(sizeof(rcCompactCell) * xSize * zSize, RC_ALLOC_PERM);
|
||||
if (!compactHeightfield.cells)
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.cells' (%d)", xSize * zSize);
|
||||
return false;
|
||||
}
|
||||
memset(compactHeightfield.cells, 0, sizeof(rcCompactCell) * xSize * zSize);
|
||||
compactHeightfield.spans = (rcCompactSpan*)rcAlloc(sizeof(rcCompactSpan) * spanCount, RC_ALLOC_PERM);
|
||||
if (!compactHeightfield.spans)
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.spans' (%d)", spanCount);
|
||||
return false;
|
||||
}
|
||||
memset(compactHeightfield.spans, 0, sizeof(rcCompactSpan) * spanCount);
|
||||
compactHeightfield.areas = (unsigned char*)rcAlloc(sizeof(unsigned char) * spanCount, RC_ALLOC_PERM);
|
||||
if (!compactHeightfield.areas)
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Out of memory 'chf.areas' (%d)", spanCount);
|
||||
return false;
|
||||
}
|
||||
memset(compactHeightfield.areas, RC_NULL_AREA, sizeof(unsigned char) * spanCount);
|
||||
|
||||
const int MAX_HEIGHT = 0xffff;
|
||||
|
||||
// Fill in cells and spans.
|
||||
int currentCellIndex = 0;
|
||||
const int numColumns = xSize * zSize;
|
||||
for (int columnIndex = 0; columnIndex < numColumns; ++columnIndex)
|
||||
{
|
||||
const rcSpan* span = heightfield.spans[columnIndex];
|
||||
|
||||
// If there are no spans at this cell, just leave the data to index=0, count=0.
|
||||
if (span == NULL)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
rcCompactCell& cell = compactHeightfield.cells[columnIndex];
|
||||
cell.index = currentCellIndex;
|
||||
cell.count = 0;
|
||||
|
||||
for (; span != NULL; span = span->next)
|
||||
{
|
||||
if (span->area != RC_NULL_AREA)
|
||||
{
|
||||
const int bot = (int)span->smax;
|
||||
const int top = span->next ? (int)span->next->smin : MAX_HEIGHT;
|
||||
compactHeightfield.spans[currentCellIndex].y = (unsigned short)rcClamp(bot, 0, 0xffff);
|
||||
compactHeightfield.spans[currentCellIndex].h = (unsigned char)rcClamp(top - bot, 0, 0xff);
|
||||
compactHeightfield.areas[currentCellIndex] = span->area;
|
||||
currentCellIndex++;
|
||||
cell.count++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Find neighbour connections.
|
||||
const int MAX_LAYERS = RC_NOT_CONNECTED - 1;
|
||||
int maxLayerIndex = 0;
|
||||
const int zStride = xSize; // for readability
|
||||
for (int z = 0; z < zSize; ++z)
|
||||
{
|
||||
for (int x = 0; x < xSize; ++x)
|
||||
{
|
||||
const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
|
||||
for (int i = (int)cell.index, ni = (int)(cell.index + cell.count); i < ni; ++i)
|
||||
{
|
||||
rcCompactSpan& span = compactHeightfield.spans[i];
|
||||
|
||||
for (int dir = 0; dir < 4; ++dir)
|
||||
{
|
||||
rcSetCon(span, dir, RC_NOT_CONNECTED);
|
||||
const int neighborX = x + rcGetDirOffsetX(dir);
|
||||
const int neighborZ = z + rcGetDirOffsetY(dir);
|
||||
// First check that the neighbour cell is in bounds.
|
||||
if (neighborX < 0 || neighborZ < 0 || neighborX >= xSize || neighborZ >= zSize)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Iterate over all neighbour spans and check if any of the is
|
||||
// accessible from current cell.
|
||||
const rcCompactCell& neighborCell = compactHeightfield.cells[neighborX + neighborZ * zStride];
|
||||
for (int k = (int)neighborCell.index, nk = (int)(neighborCell.index + neighborCell.count); k < nk; ++k)
|
||||
{
|
||||
const rcCompactSpan& neighborSpan = compactHeightfield.spans[k];
|
||||
const int bot = rcMax(span.y, neighborSpan.y);
|
||||
const int top = rcMin(span.y + span.h, neighborSpan.y + neighborSpan.h);
|
||||
|
||||
// Check that the gap between the spans is walkable,
|
||||
// and that the climb height between the gaps is not too high.
|
||||
if ((top - bot) >= walkableHeight && rcAbs((int)neighborSpan.y - (int)span.y) <= walkableClimb)
|
||||
{
|
||||
// Mark direction as walkable.
|
||||
const int layerIndex = k - (int)neighborCell.index;
|
||||
if (layerIndex < 0 || layerIndex > MAX_LAYERS)
|
||||
{
|
||||
maxLayerIndex = rcMax(maxLayerIndex, layerIndex);
|
||||
continue;
|
||||
}
|
||||
rcSetCon(span, dir, layerIndex);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (maxLayerIndex > MAX_LAYERS)
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcBuildCompactHeightfield: Heightfield has too many layers %d (max: %d)",
|
||||
maxLayerIndex, MAX_LAYERS);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include "RecastAlloc.h"
|
||||
|
||||
static void* rcAllocDefault(size_t size, rcAllocHint)
|
||||
{
|
||||
return malloc(size);
|
||||
}
|
||||
|
||||
static void rcFreeDefault(void *ptr)
|
||||
{
|
||||
free(ptr);
|
||||
}
|
||||
|
||||
static rcAllocFunc* sRecastAllocFunc = rcAllocDefault;
|
||||
static rcFreeFunc* sRecastFreeFunc = rcFreeDefault;
|
||||
|
||||
void rcAllocSetCustom(rcAllocFunc* allocFunc, rcFreeFunc* freeFunc)
|
||||
{
|
||||
sRecastAllocFunc = allocFunc ? allocFunc : rcAllocDefault;
|
||||
sRecastFreeFunc = freeFunc ? freeFunc : rcFreeDefault;
|
||||
}
|
||||
|
||||
void* rcAlloc(size_t size, rcAllocHint hint)
|
||||
{
|
||||
return sRecastAllocFunc(size, hint);
|
||||
}
|
||||
|
||||
void rcFree(void* ptr)
|
||||
{
|
||||
if (ptr != NULL)
|
||||
{
|
||||
sRecastFreeFunc(ptr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,717 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include "Recast.h"
|
||||
#include "RecastAlloc.h"
|
||||
#include "RecastAssert.h"
|
||||
|
||||
#include <string.h> // for memcpy and memset
|
||||
|
||||
/// Sorts the given data in-place using insertion sort.
|
||||
///
|
||||
/// @param data The data to sort
|
||||
/// @param dataLength The number of elements in @p data
|
||||
static void insertSort(unsigned char* data, const int dataLength)
|
||||
{
|
||||
for (int valueIndex = 1; valueIndex < dataLength; valueIndex++)
|
||||
{
|
||||
const unsigned char value = data[valueIndex];
|
||||
int insertionIndex;
|
||||
for (insertionIndex = valueIndex - 1; insertionIndex >= 0 && data[insertionIndex] > value; insertionIndex--)
|
||||
{
|
||||
// Shift over values
|
||||
data[insertionIndex + 1] = data[insertionIndex];
|
||||
}
|
||||
|
||||
// Insert the value in sorted order.
|
||||
data[insertionIndex + 1] = value;
|
||||
}
|
||||
}
|
||||
|
||||
// TODO (graham): This is duplicated in the ConvexVolumeTool in RecastDemo
|
||||
/// Checks if a point is contained within a polygon
|
||||
///
|
||||
/// @param[in] numVerts Number of vertices in the polygon
|
||||
/// @param[in] verts The polygon vertices
|
||||
/// @param[in] point The point to check
|
||||
/// @returns true if the point lies within the polygon, false otherwise.
|
||||
static bool pointInPoly(int numVerts, const float* verts, const float* point)
|
||||
{
|
||||
bool inPoly = false;
|
||||
for (int i = 0, j = numVerts - 1; i < numVerts; j = i++)
|
||||
{
|
||||
const float* vi = &verts[i * 3];
|
||||
const float* vj = &verts[j * 3];
|
||||
|
||||
if ((vi[2] > point[2]) == (vj[2] > point[2]))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (point[0] >= (vj[0] - vi[0]) * (point[2] - vi[2]) / (vj[2] - vi[2]) + vi[0])
|
||||
{
|
||||
continue;
|
||||
}
|
||||
inPoly = !inPoly;
|
||||
}
|
||||
return inPoly;
|
||||
}
|
||||
|
||||
bool rcErodeWalkableArea(rcContext* context, const int erosionRadius, rcCompactHeightfield& compactHeightfield)
|
||||
{
|
||||
rcAssert(context != NULL);
|
||||
|
||||
const int xSize = compactHeightfield.width;
|
||||
const int zSize = compactHeightfield.height;
|
||||
const int& zStride = xSize; // For readability
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_ERODE_AREA);
|
||||
|
||||
unsigned char* distanceToBoundary = (unsigned char*)rcAlloc(sizeof(unsigned char) * compactHeightfield.spanCount,
|
||||
RC_ALLOC_TEMP);
|
||||
if (!distanceToBoundary)
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "erodeWalkableArea: Out of memory 'dist' (%d).", compactHeightfield.spanCount);
|
||||
return false;
|
||||
}
|
||||
memset(distanceToBoundary, 0xff, sizeof(unsigned char) * compactHeightfield.spanCount);
|
||||
|
||||
// Mark boundary cells.
|
||||
for (int z = 0; z < zSize; ++z)
|
||||
{
|
||||
for (int x = 0; x < xSize; ++x)
|
||||
{
|
||||
const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
|
||||
for (int spanIndex = (int)cell.index, maxSpanIndex = (int)(cell.index + cell.count); spanIndex < maxSpanIndex; ++spanIndex)
|
||||
{
|
||||
if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
|
||||
{
|
||||
distanceToBoundary[spanIndex] = 0;
|
||||
continue;
|
||||
}
|
||||
const rcCompactSpan& span = compactHeightfield.spans[spanIndex];
|
||||
|
||||
// Check that there is a non-null adjacent span in each of the 4 cardinal directions.
|
||||
int neighborCount = 0;
|
||||
for (int direction = 0; direction < 4; ++direction)
|
||||
{
|
||||
const int neighborConnection = rcGetCon(span, direction);
|
||||
if (neighborConnection == RC_NOT_CONNECTED)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
const int neighborX = x + rcGetDirOffsetX(direction);
|
||||
const int neighborZ = z + rcGetDirOffsetY(direction);
|
||||
const int neighborSpanIndex = (int)compactHeightfield.cells[neighborX + neighborZ * zStride].index + neighborConnection;
|
||||
|
||||
if (compactHeightfield.areas[neighborSpanIndex] == RC_NULL_AREA)
|
||||
{
|
||||
break;
|
||||
}
|
||||
neighborCount++;
|
||||
}
|
||||
|
||||
// At least one missing neighbour, so this is a boundary cell.
|
||||
if (neighborCount != 4)
|
||||
{
|
||||
distanceToBoundary[spanIndex] = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsigned char newDistance;
|
||||
|
||||
// Pass 1
|
||||
for (int z = 0; z < zSize; ++z)
|
||||
{
|
||||
for (int x = 0; x < xSize; ++x)
|
||||
{
|
||||
const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
|
||||
const int maxSpanIndex = (int)(cell.index + cell.count);
|
||||
for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
|
||||
{
|
||||
const rcCompactSpan& span = compactHeightfield.spans[spanIndex];
|
||||
|
||||
if (rcGetCon(span, 0) != RC_NOT_CONNECTED)
|
||||
{
|
||||
// (-1,0)
|
||||
const int aX = x + rcGetDirOffsetX(0);
|
||||
const int aY = z + rcGetDirOffsetY(0);
|
||||
const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 0);
|
||||
const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
|
||||
newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255);
|
||||
if (newDistance < distanceToBoundary[spanIndex])
|
||||
{
|
||||
distanceToBoundary[spanIndex] = newDistance;
|
||||
}
|
||||
|
||||
// (-1,-1)
|
||||
if (rcGetCon(aSpan, 3) != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int bX = aX + rcGetDirOffsetX(3);
|
||||
const int bY = aY + rcGetDirOffsetY(3);
|
||||
const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 3);
|
||||
newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255);
|
||||
if (newDistance < distanceToBoundary[spanIndex])
|
||||
{
|
||||
distanceToBoundary[spanIndex] = newDistance;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rcGetCon(span, 3) != RC_NOT_CONNECTED)
|
||||
{
|
||||
// (0,-1)
|
||||
const int aX = x + rcGetDirOffsetX(3);
|
||||
const int aY = z + rcGetDirOffsetY(3);
|
||||
const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 3);
|
||||
const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
|
||||
newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255);
|
||||
if (newDistance < distanceToBoundary[spanIndex])
|
||||
{
|
||||
distanceToBoundary[spanIndex] = newDistance;
|
||||
}
|
||||
|
||||
// (1,-1)
|
||||
if (rcGetCon(aSpan, 2) != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int bX = aX + rcGetDirOffsetX(2);
|
||||
const int bY = aY + rcGetDirOffsetY(2);
|
||||
const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 2);
|
||||
newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255);
|
||||
if (newDistance < distanceToBoundary[spanIndex])
|
||||
{
|
||||
distanceToBoundary[spanIndex] = newDistance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Pass 2
|
||||
for (int z = zSize - 1; z >= 0; --z)
|
||||
{
|
||||
for (int x = xSize - 1; x >= 0; --x)
|
||||
{
|
||||
const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
|
||||
const int maxSpanIndex = (int)(cell.index + cell.count);
|
||||
for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
|
||||
{
|
||||
const rcCompactSpan& span = compactHeightfield.spans[spanIndex];
|
||||
|
||||
if (rcGetCon(span, 2) != RC_NOT_CONNECTED)
|
||||
{
|
||||
// (1,0)
|
||||
const int aX = x + rcGetDirOffsetX(2);
|
||||
const int aY = z + rcGetDirOffsetY(2);
|
||||
const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 2);
|
||||
const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
|
||||
newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255);
|
||||
if (newDistance < distanceToBoundary[spanIndex])
|
||||
{
|
||||
distanceToBoundary[spanIndex] = newDistance;
|
||||
}
|
||||
|
||||
// (1,1)
|
||||
if (rcGetCon(aSpan, 1) != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int bX = aX + rcGetDirOffsetX(1);
|
||||
const int bY = aY + rcGetDirOffsetY(1);
|
||||
const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 1);
|
||||
newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255);
|
||||
if (newDistance < distanceToBoundary[spanIndex])
|
||||
{
|
||||
distanceToBoundary[spanIndex] = newDistance;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (rcGetCon(span, 1) != RC_NOT_CONNECTED)
|
||||
{
|
||||
// (0,1)
|
||||
const int aX = x + rcGetDirOffsetX(1);
|
||||
const int aY = z + rcGetDirOffsetY(1);
|
||||
const int aIndex = (int)compactHeightfield.cells[aX + aY * xSize].index + rcGetCon(span, 1);
|
||||
const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
|
||||
newDistance = (unsigned char)rcMin((int)distanceToBoundary[aIndex] + 2, 255);
|
||||
if (newDistance < distanceToBoundary[spanIndex])
|
||||
{
|
||||
distanceToBoundary[spanIndex] = newDistance;
|
||||
}
|
||||
|
||||
// (-1,1)
|
||||
if (rcGetCon(aSpan, 0) != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int bX = aX + rcGetDirOffsetX(0);
|
||||
const int bY = aY + rcGetDirOffsetY(0);
|
||||
const int bIndex = (int)compactHeightfield.cells[bX + bY * xSize].index + rcGetCon(aSpan, 0);
|
||||
newDistance = (unsigned char)rcMin((int)distanceToBoundary[bIndex] + 3, 255);
|
||||
if (newDistance < distanceToBoundary[spanIndex])
|
||||
{
|
||||
distanceToBoundary[spanIndex] = newDistance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const unsigned char minBoundaryDistance = (unsigned char)(erosionRadius * 2);
|
||||
for (int spanIndex = 0; spanIndex < compactHeightfield.spanCount; ++spanIndex)
|
||||
{
|
||||
if (distanceToBoundary[spanIndex] < minBoundaryDistance)
|
||||
{
|
||||
compactHeightfield.areas[spanIndex] = RC_NULL_AREA;
|
||||
}
|
||||
}
|
||||
|
||||
rcFree(distanceToBoundary);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool rcMedianFilterWalkableArea(rcContext* context, rcCompactHeightfield& compactHeightfield)
|
||||
{
|
||||
rcAssert(context);
|
||||
|
||||
const int xSize = compactHeightfield.width;
|
||||
const int zSize = compactHeightfield.height;
|
||||
const int zStride = xSize; // For readability
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_MEDIAN_AREA);
|
||||
|
||||
unsigned char* areas = (unsigned char*)rcAlloc(sizeof(unsigned char) * compactHeightfield.spanCount, RC_ALLOC_TEMP);
|
||||
if (!areas)
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "medianFilterWalkableArea: Out of memory 'areas' (%d).",
|
||||
compactHeightfield.spanCount);
|
||||
return false;
|
||||
}
|
||||
memset(areas, 0xff, sizeof(unsigned char) * compactHeightfield.spanCount);
|
||||
|
||||
for (int z = 0; z < zSize; ++z)
|
||||
{
|
||||
for (int x = 0; x < xSize; ++x)
|
||||
{
|
||||
const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
|
||||
const int maxSpanIndex = (int)(cell.index + cell.count);
|
||||
for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
|
||||
{
|
||||
const rcCompactSpan& span = compactHeightfield.spans[spanIndex];
|
||||
if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
|
||||
{
|
||||
areas[spanIndex] = compactHeightfield.areas[spanIndex];
|
||||
continue;
|
||||
}
|
||||
|
||||
unsigned char neighborAreas[9];
|
||||
for (int neighborIndex = 0; neighborIndex < 9; ++neighborIndex)
|
||||
{
|
||||
neighborAreas[neighborIndex] = compactHeightfield.areas[spanIndex];
|
||||
}
|
||||
|
||||
for (int dir = 0; dir < 4; ++dir)
|
||||
{
|
||||
if (rcGetCon(span, dir) == RC_NOT_CONNECTED)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const int aX = x + rcGetDirOffsetX(dir);
|
||||
const int aZ = z + rcGetDirOffsetY(dir);
|
||||
const int aIndex = (int)compactHeightfield.cells[aX + aZ * zStride].index + rcGetCon(span, dir);
|
||||
if (compactHeightfield.areas[aIndex] != RC_NULL_AREA)
|
||||
{
|
||||
neighborAreas[dir * 2 + 0] = compactHeightfield.areas[aIndex];
|
||||
}
|
||||
|
||||
const rcCompactSpan& aSpan = compactHeightfield.spans[aIndex];
|
||||
const int dir2 = (dir + 1) & 0x3;
|
||||
const int neighborConnection2 = rcGetCon(aSpan, dir2);
|
||||
if (neighborConnection2 != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int bX = aX + rcGetDirOffsetX(dir2);
|
||||
const int bZ = aZ + rcGetDirOffsetY(dir2);
|
||||
const int bIndex = (int)compactHeightfield.cells[bX + bZ * zStride].index + neighborConnection2;
|
||||
if (compactHeightfield.areas[bIndex] != RC_NULL_AREA)
|
||||
{
|
||||
neighborAreas[dir * 2 + 1] = compactHeightfield.areas[bIndex];
|
||||
}
|
||||
}
|
||||
}
|
||||
insertSort(neighborAreas, 9);
|
||||
areas[spanIndex] = neighborAreas[4];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
memcpy(compactHeightfield.areas, areas, sizeof(unsigned char) * compactHeightfield.spanCount);
|
||||
|
||||
rcFree(areas);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void rcMarkBoxArea(rcContext* context, const float* boxMinBounds, const float* boxMaxBounds, unsigned char areaId,
|
||||
rcCompactHeightfield& compactHeightfield)
|
||||
{
|
||||
rcAssert(context);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_MARK_BOX_AREA);
|
||||
|
||||
const int xSize = compactHeightfield.width;
|
||||
const int zSize = compactHeightfield.height;
|
||||
const int zStride = xSize; // For readability
|
||||
|
||||
// Find the footprint of the box area in grid cell coordinates.
|
||||
int minX = (int)((boxMinBounds[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
|
||||
int minY = (int)((boxMinBounds[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
|
||||
int minZ = (int)((boxMinBounds[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
|
||||
int maxX = (int)((boxMaxBounds[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
|
||||
int maxY = (int)((boxMaxBounds[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
|
||||
int maxZ = (int)((boxMaxBounds[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
|
||||
|
||||
// Early-out if the box is outside the bounds of the grid.
|
||||
if (maxX < 0) { return; }
|
||||
if (minX >= xSize) { return; }
|
||||
if (maxZ < 0) { return; }
|
||||
if (minZ >= zSize) { return; }
|
||||
|
||||
// Clamp relevant bound coordinates to the grid.
|
||||
if (minX < 0) { minX = 0; }
|
||||
if (maxX >= xSize) { maxX = xSize - 1; }
|
||||
if (minZ < 0) { minZ = 0; }
|
||||
if (maxZ >= zSize) { maxZ = zSize - 1; }
|
||||
|
||||
// Mark relevant cells.
|
||||
for (int z = minZ; z <= maxZ; ++z)
|
||||
{
|
||||
for (int x = minX; x <= maxX; ++x)
|
||||
{
|
||||
const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
|
||||
const int maxSpanIndex = (int)(cell.index + cell.count);
|
||||
for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
|
||||
{
|
||||
rcCompactSpan& span = compactHeightfield.spans[spanIndex];
|
||||
|
||||
// Skip if the span is outside the box extents.
|
||||
if ((int)span.y < minY || (int)span.y > maxY)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if the span has been removed.
|
||||
if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Mark the span.
|
||||
compactHeightfield.areas[spanIndex] = areaId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void rcMarkConvexPolyArea(rcContext* context, const float* verts, const int numVerts,
|
||||
const float minY, const float maxY, unsigned char areaId,
|
||||
rcCompactHeightfield& compactHeightfield)
|
||||
{
|
||||
rcAssert(context);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_MARK_CONVEXPOLY_AREA);
|
||||
|
||||
const int xSize = compactHeightfield.width;
|
||||
const int zSize = compactHeightfield.height;
|
||||
const int zStride = xSize; // For readability
|
||||
|
||||
// Compute the bounding box of the polygon
|
||||
float bmin[3];
|
||||
float bmax[3];
|
||||
rcVcopy(bmin, verts);
|
||||
rcVcopy(bmax, verts);
|
||||
for (int i = 1; i < numVerts; ++i)
|
||||
{
|
||||
rcVmin(bmin, &verts[i * 3]);
|
||||
rcVmax(bmax, &verts[i * 3]);
|
||||
}
|
||||
bmin[1] = minY;
|
||||
bmax[1] = maxY;
|
||||
|
||||
// Compute the grid footprint of the polygon
|
||||
int minx = (int)((bmin[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
|
||||
int miny = (int)((bmin[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
|
||||
int minz = (int)((bmin[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
|
||||
int maxx = (int)((bmax[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
|
||||
int maxy = (int)((bmax[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
|
||||
int maxz = (int)((bmax[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
|
||||
|
||||
// Early-out if the polygon lies entirely outside the grid.
|
||||
if (maxx < 0) { return; }
|
||||
if (minx >= xSize) { return; }
|
||||
if (maxz < 0) { return; }
|
||||
if (minz >= zSize) { return; }
|
||||
|
||||
// Clamp the polygon footprint to the grid
|
||||
if (minx < 0) { minx = 0; }
|
||||
if (maxx >= xSize) { maxx = xSize - 1; }
|
||||
if (minz < 0) { minz = 0; }
|
||||
if (maxz >= zSize) { maxz = zSize - 1; }
|
||||
|
||||
// TODO: Optimize.
|
||||
for (int z = minz; z <= maxz; ++z)
|
||||
{
|
||||
for (int x = minx; x <= maxx; ++x)
|
||||
{
|
||||
const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
|
||||
const int maxSpanIndex = (int)(cell.index + cell.count);
|
||||
for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
|
||||
{
|
||||
rcCompactSpan& span = compactHeightfield.spans[spanIndex];
|
||||
|
||||
// Skip if span is removed.
|
||||
if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip if y extents don't overlap.
|
||||
if ((int)span.y < miny || (int)span.y > maxy)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const float point[] = {
|
||||
compactHeightfield.bmin[0] + ((float)x + 0.5f) * compactHeightfield.cs,
|
||||
0,
|
||||
compactHeightfield.bmin[2] + ((float)z + 0.5f) * compactHeightfield.cs
|
||||
};
|
||||
|
||||
if (pointInPoly(numVerts, verts, point))
|
||||
{
|
||||
compactHeightfield.areas[spanIndex] = areaId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static const float EPSILON = 1e-6f;
|
||||
|
||||
/// Normalizes the vector if the length is greater than zero.
|
||||
/// If the magnitude is zero, the vector is unchanged.
|
||||
/// @param[in,out] v The vector to normalize. [(x, y, z)]
|
||||
static void rcVsafeNormalize(float* v)
|
||||
{
|
||||
const float sqMag = rcSqr(v[0]) + rcSqr(v[1]) + rcSqr(v[2]);
|
||||
if (sqMag > EPSILON)
|
||||
{
|
||||
const float inverseMag = 1.0f / rcSqrt(sqMag);
|
||||
v[0] *= inverseMag;
|
||||
v[1] *= inverseMag;
|
||||
v[2] *= inverseMag;
|
||||
}
|
||||
}
|
||||
|
||||
int rcOffsetPoly(const float* verts, const int numVerts, const float offset, float* outVerts, const int maxOutVerts)
|
||||
{
|
||||
// Defines the limit at which a miter becomes a bevel.
|
||||
// Similar in behavior to https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-miterlimit
|
||||
const float MITER_LIMIT = 1.20f;
|
||||
|
||||
int numOutVerts = 0;
|
||||
|
||||
for (int vertIndex = 0; vertIndex < numVerts; vertIndex++)
|
||||
{
|
||||
// Grab three vertices of the polygon.
|
||||
const int vertIndexA = (vertIndex + numVerts - 1) % numVerts;
|
||||
const int vertIndexB = vertIndex;
|
||||
const int vertIndexC = (vertIndex + 1) % numVerts;
|
||||
const float* vertA = &verts[vertIndexA * 3];
|
||||
const float* vertB = &verts[vertIndexB * 3];
|
||||
const float* vertC = &verts[vertIndexC * 3];
|
||||
|
||||
// From A to B on the x/z plane
|
||||
float prevSegmentDir[3];
|
||||
rcVsub(prevSegmentDir, vertB, vertA);
|
||||
prevSegmentDir[1] = 0; // Squash onto x/z plane
|
||||
rcVsafeNormalize(prevSegmentDir);
|
||||
|
||||
// From B to C on the x/z plane
|
||||
float currSegmentDir[3];
|
||||
rcVsub(currSegmentDir, vertC, vertB);
|
||||
currSegmentDir[1] = 0; // Squash onto x/z plane
|
||||
rcVsafeNormalize(currSegmentDir);
|
||||
|
||||
// The y component of the cross product of the two normalized segment directions.
|
||||
// The X and Z components of the cross product are both zero because the two
|
||||
// segment direction vectors fall within the x/z plane.
|
||||
float cross = currSegmentDir[0] * prevSegmentDir[2] - prevSegmentDir[0] * currSegmentDir[2];
|
||||
|
||||
// CCW perpendicular vector to AB. The segment normal.
|
||||
const float prevSegmentNormX = -prevSegmentDir[2];
|
||||
const float prevSegmentNormZ = prevSegmentDir[0];
|
||||
|
||||
// CCW perpendicular vector to BC. The segment normal.
|
||||
const float currSegmentNormX = -currSegmentDir[2];
|
||||
const float currSegmentNormZ = currSegmentDir[0];
|
||||
|
||||
// Average the two segment normals to get the proportional miter offset for B.
|
||||
// This isn't normalized because it's defining the distance and direction the corner will need to be
|
||||
// adjusted proportionally to the edge offsets to properly miter the adjoining edges.
|
||||
float cornerMiterX = (prevSegmentNormX + currSegmentNormX) * 0.5f;
|
||||
float cornerMiterZ = (prevSegmentNormZ + currSegmentNormZ) * 0.5f;
|
||||
const float cornerMiterSqMag = rcSqr(cornerMiterX) + rcSqr(cornerMiterZ);
|
||||
|
||||
// If the magnitude of the segment normal average is less than about .69444,
|
||||
// the corner is an acute enough angle that the result should be beveled.
|
||||
const bool bevel = cornerMiterSqMag * MITER_LIMIT * MITER_LIMIT < 1.0f;
|
||||
|
||||
// Scale the corner miter so it's proportional to how much the corner should be offset compared to the edges.
|
||||
if (cornerMiterSqMag > EPSILON)
|
||||
{
|
||||
const float scale = 1.0f / cornerMiterSqMag;
|
||||
cornerMiterX *= scale;
|
||||
cornerMiterZ *= scale;
|
||||
}
|
||||
|
||||
if (bevel && cross < 0.0f) // If the corner is convex and an acute enough angle, generate a bevel.
|
||||
{
|
||||
if (numOutVerts + 2 > maxOutVerts)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Generate two bevel vertices at a distances from B proportional to the angle between the two segments.
|
||||
// Move each bevel vertex out proportional to the given offset.
|
||||
float d = (1.0f - (prevSegmentDir[0] * currSegmentDir[0] + prevSegmentDir[2] * currSegmentDir[2])) * 0.5f;
|
||||
|
||||
outVerts[numOutVerts * 3 + 0] = vertB[0] + (-prevSegmentNormX + prevSegmentDir[0] * d) * offset;
|
||||
outVerts[numOutVerts * 3 + 1] = vertB[1];
|
||||
outVerts[numOutVerts * 3 + 2] = vertB[2] + (-prevSegmentNormZ + prevSegmentDir[2] * d) * offset;
|
||||
numOutVerts++;
|
||||
|
||||
outVerts[numOutVerts * 3 + 0] = vertB[0] + (-currSegmentNormX - currSegmentDir[0] * d) * offset;
|
||||
outVerts[numOutVerts * 3 + 1] = vertB[1];
|
||||
outVerts[numOutVerts * 3 + 2] = vertB[2] + (-currSegmentNormZ - currSegmentDir[2] * d) * offset;
|
||||
numOutVerts++;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (numOutVerts + 1 > maxOutVerts)
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Move B along the miter direction by the specified offset.
|
||||
outVerts[numOutVerts * 3 + 0] = vertB[0] - cornerMiterX * offset;
|
||||
outVerts[numOutVerts * 3 + 1] = vertB[1];
|
||||
outVerts[numOutVerts * 3 + 2] = vertB[2] - cornerMiterZ * offset;
|
||||
numOutVerts++;
|
||||
}
|
||||
}
|
||||
|
||||
return numOutVerts;
|
||||
}
|
||||
|
||||
void rcMarkCylinderArea(rcContext* context, const float* position, const float radius, const float height,
|
||||
unsigned char areaId, rcCompactHeightfield& compactHeightfield)
|
||||
{
|
||||
rcAssert(context);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_MARK_CYLINDER_AREA);
|
||||
|
||||
const int xSize = compactHeightfield.width;
|
||||
const int zSize = compactHeightfield.height;
|
||||
const int zStride = xSize; // For readability
|
||||
|
||||
// Compute the bounding box of the cylinder
|
||||
const float cylinderBBMin[] =
|
||||
{
|
||||
position[0] - radius,
|
||||
position[1],
|
||||
position[2] - radius
|
||||
};
|
||||
const float cylinderBBMax[] =
|
||||
{
|
||||
position[0] + radius,
|
||||
position[1] + height,
|
||||
position[2] + radius
|
||||
};
|
||||
|
||||
// Compute the grid footprint of the cylinder
|
||||
int minx = (int)((cylinderBBMin[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
|
||||
int miny = (int)((cylinderBBMin[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
|
||||
int minz = (int)((cylinderBBMin[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
|
||||
int maxx = (int)((cylinderBBMax[0] - compactHeightfield.bmin[0]) / compactHeightfield.cs);
|
||||
int maxy = (int)((cylinderBBMax[1] - compactHeightfield.bmin[1]) / compactHeightfield.ch);
|
||||
int maxz = (int)((cylinderBBMax[2] - compactHeightfield.bmin[2]) / compactHeightfield.cs);
|
||||
|
||||
// Early-out if the cylinder is completely outside the grid bounds.
|
||||
if (maxx < 0) { return; }
|
||||
if (minx >= xSize) { return; }
|
||||
if (maxz < 0) { return; }
|
||||
if (minz >= zSize) { return; }
|
||||
|
||||
// Clamp the cylinder bounds to the grid.
|
||||
if (minx < 0) { minx = 0; }
|
||||
if (maxx >= xSize) { maxx = xSize - 1; }
|
||||
if (minz < 0) { minz = 0; }
|
||||
if (maxz >= zSize) { maxz = zSize - 1; }
|
||||
|
||||
const float radiusSq = radius * radius;
|
||||
|
||||
for (int z = minz; z <= maxz; ++z)
|
||||
{
|
||||
for (int x = minx; x <= maxx; ++x)
|
||||
{
|
||||
const rcCompactCell& cell = compactHeightfield.cells[x + z * zStride];
|
||||
const int maxSpanIndex = (int)(cell.index + cell.count);
|
||||
|
||||
const float cellX = compactHeightfield.bmin[0] + ((float)x + 0.5f) * compactHeightfield.cs;
|
||||
const float cellZ = compactHeightfield.bmin[2] + ((float)z + 0.5f) * compactHeightfield.cs;
|
||||
const float deltaX = cellX - position[0];
|
||||
const float deltaZ = cellZ - position[2];
|
||||
|
||||
// Skip this column if it's too far from the center point of the cylinder.
|
||||
if (rcSqr(deltaX) + rcSqr(deltaZ) >= radiusSq)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Mark all overlapping spans
|
||||
for (int spanIndex = (int)cell.index; spanIndex < maxSpanIndex; ++spanIndex)
|
||||
{
|
||||
rcCompactSpan& span = compactHeightfield.spans[spanIndex];
|
||||
|
||||
// Skip if span is removed.
|
||||
if (compactHeightfield.areas[spanIndex] == RC_NULL_AREA)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Mark if y extents overlap.
|
||||
if ((int)span.y >= miny && (int)span.y <= maxy)
|
||||
{
|
||||
compactHeightfield.areas[spanIndex] = areaId;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include "RecastAssert.h"
|
||||
|
||||
static rcAssertFailFunc* sRecastAssertFailFunc = 0;
|
||||
|
||||
void rcAssertFailSetCustom(rcAssertFailFunc* assertFailFunc)
|
||||
{
|
||||
sRecastAssertFailFunc = assertFailFunc;
|
||||
}
|
||||
|
||||
rcAssertFailFunc* rcAssertFailGetCustom()
|
||||
{
|
||||
return sRecastAssertFailFunc;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,201 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include "Recast.h"
|
||||
#include "RecastAssert.h"
|
||||
|
||||
#include <stdlib.h>
|
||||
|
||||
namespace
|
||||
{
|
||||
const int MAX_HEIGHTFIELD_HEIGHT = 0xffff; // TODO (graham): Move this to a more visible constant and update usages.
|
||||
}
|
||||
|
||||
void rcFilterLowHangingWalkableObstacles(rcContext* context, const int walkableClimb, rcHeightfield& heightfield)
|
||||
{
|
||||
rcAssert(context);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_FILTER_LOW_OBSTACLES);
|
||||
|
||||
const int xSize = heightfield.width;
|
||||
const int zSize = heightfield.height;
|
||||
|
||||
for (int z = 0; z < zSize; ++z)
|
||||
{
|
||||
for (int x = 0; x < xSize; ++x)
|
||||
{
|
||||
rcSpan* previousSpan = NULL;
|
||||
bool previousWasWalkable = false;
|
||||
unsigned char previousAreaID = RC_NULL_AREA;
|
||||
|
||||
// For each span in the column...
|
||||
for (rcSpan* span = heightfield.spans[x + z * xSize]; span != NULL; previousSpan = span, span = span->next)
|
||||
{
|
||||
const bool walkable = span->area != RC_NULL_AREA;
|
||||
|
||||
// If current span is not walkable, but there is walkable span just below it and the height difference
|
||||
// is small enough for the agent to walk over, mark the current span as walkable too.
|
||||
if (!walkable && previousWasWalkable && (int)span->smax - (int)previousSpan->smax <= walkableClimb)
|
||||
{
|
||||
span->area = previousAreaID;
|
||||
}
|
||||
|
||||
// Copy the original walkable value regardless of whether we changed it.
|
||||
// This prevents multiple consecutive non-walkable spans from being erroneously marked as walkable.
|
||||
previousWasWalkable = walkable;
|
||||
previousAreaID = span->area;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void rcFilterLedgeSpans(rcContext* context, const int walkableHeight, const int walkableClimb, rcHeightfield& heightfield)
|
||||
{
|
||||
rcAssert(context);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_FILTER_BORDER);
|
||||
|
||||
const int xSize = heightfield.width;
|
||||
const int zSize = heightfield.height;
|
||||
|
||||
// Mark spans that are adjacent to a ledge as unwalkable..
|
||||
for (int z = 0; z < zSize; ++z)
|
||||
{
|
||||
for (int x = 0; x < xSize; ++x)
|
||||
{
|
||||
for (rcSpan* span = heightfield.spans[x + z * xSize]; span; span = span->next)
|
||||
{
|
||||
// Skip non-walkable spans.
|
||||
if (span->area == RC_NULL_AREA)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
const int floor = (int)(span->smax);
|
||||
const int ceiling = span->next ? (int)(span->next->smin) : MAX_HEIGHTFIELD_HEIGHT;
|
||||
|
||||
// The difference between this walkable area and the lowest neighbor walkable area.
|
||||
// This is the difference between the current span and all neighbor spans that have
|
||||
// enough space for an agent to move between, but not accounting at all for surface slope.
|
||||
int lowestNeighborFloorDifference = MAX_HEIGHTFIELD_HEIGHT;
|
||||
|
||||
// Min and max height of accessible neighbours.
|
||||
int lowestTraversableNeighborFloor = span->smax;
|
||||
int highestTraversableNeighborFloor = span->smax;
|
||||
|
||||
for (int direction = 0; direction < 4; ++direction)
|
||||
{
|
||||
const int neighborX = x + rcGetDirOffsetX(direction);
|
||||
const int neighborZ = z + rcGetDirOffsetY(direction);
|
||||
|
||||
// Skip neighbours which are out of bounds.
|
||||
if (neighborX < 0 || neighborZ < 0 || neighborX >= xSize || neighborZ >= zSize)
|
||||
{
|
||||
lowestNeighborFloorDifference = -walkableClimb - 1;
|
||||
break;
|
||||
}
|
||||
|
||||
const rcSpan* neighborSpan = heightfield.spans[neighborX + neighborZ * xSize];
|
||||
|
||||
// The most we can step down to the neighbor is the walkableClimb distance.
|
||||
// Start with the area under the neighbor span
|
||||
int neighborCeiling = neighborSpan ? (int)neighborSpan->smin : MAX_HEIGHTFIELD_HEIGHT;
|
||||
|
||||
// Skip neighbour if the gap between the spans is too small.
|
||||
if (rcMin(ceiling, neighborCeiling) - floor >= walkableHeight)
|
||||
{
|
||||
lowestNeighborFloorDifference = (-walkableClimb - 1);
|
||||
break;
|
||||
}
|
||||
|
||||
// For each span in the neighboring column...
|
||||
for (; neighborSpan != NULL; neighborSpan = neighborSpan->next)
|
||||
{
|
||||
const int neighborFloor = (int)neighborSpan->smax;
|
||||
neighborCeiling = neighborSpan->next ? (int)neighborSpan->next->smin : MAX_HEIGHTFIELD_HEIGHT;
|
||||
|
||||
// Only consider neighboring areas that have enough overlap to be potentially traversable.
|
||||
if (rcMin(ceiling, neighborCeiling) - rcMax(floor, neighborFloor) < walkableHeight)
|
||||
{
|
||||
// No space to traverse between them.
|
||||
continue;
|
||||
}
|
||||
|
||||
const int neighborFloorDifference = neighborFloor - floor;
|
||||
lowestNeighborFloorDifference = rcMin(lowestNeighborFloorDifference, neighborFloorDifference);
|
||||
|
||||
// Find min/max accessible neighbor height.
|
||||
// Only consider neighbors that are at most walkableClimb away.
|
||||
if (rcAbs(neighborFloorDifference) <= walkableClimb)
|
||||
{
|
||||
// There is space to move to the neighbor cell and the slope isn't too much.
|
||||
lowestTraversableNeighborFloor = rcMin(lowestTraversableNeighborFloor, neighborFloor);
|
||||
highestTraversableNeighborFloor = rcMax(highestTraversableNeighborFloor, neighborFloor);
|
||||
}
|
||||
else if (neighborFloorDifference < -walkableClimb)
|
||||
{
|
||||
// We already know this will be considered a ledge span so we can early-out
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The current span is close to a ledge if the magnitude of the drop to any neighbour span is greater than the walkableClimb distance.
|
||||
// That is, there is a gap that is large enough to let an agent move between them, but the drop (surface slope) is too large to allow it.
|
||||
// (If this is the case, then biggestNeighborStepDown will be negative, so compare against the negative walkableClimb as a means of checking
|
||||
// the magnitude of the delta)
|
||||
if (lowestNeighborFloorDifference < -walkableClimb)
|
||||
{
|
||||
span->area = RC_NULL_AREA;
|
||||
}
|
||||
// If the difference between all neighbor floors is too large, this is a steep slope, so mark the span as an unwalkable ledge.
|
||||
else if (highestTraversableNeighborFloor - lowestTraversableNeighborFloor > walkableClimb)
|
||||
{
|
||||
span->area = RC_NULL_AREA;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void rcFilterWalkableLowHeightSpans(rcContext* context, const int walkableHeight, rcHeightfield& heightfield)
|
||||
{
|
||||
rcAssert(context);
|
||||
rcScopedTimer timer(context, RC_TIMER_FILTER_WALKABLE);
|
||||
|
||||
const int xSize = heightfield.width;
|
||||
const int zSize = heightfield.height;
|
||||
|
||||
// Remove walkable flag from spans which do not have enough
|
||||
// space above them for the agent to stand there.
|
||||
for (int z = 0; z < zSize; ++z)
|
||||
{
|
||||
for (int x = 0; x < xSize; ++x)
|
||||
{
|
||||
for (rcSpan* span = heightfield.spans[x + z*xSize]; span; span = span->next)
|
||||
{
|
||||
const int floor = (int)(span->smax);
|
||||
const int ceiling = span->next ? (int)(span->next->smin) : MAX_HEIGHTFIELD_HEIGHT;
|
||||
if (ceiling - floor < walkableHeight)
|
||||
{
|
||||
span->area = RC_NULL_AREA;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,656 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include <float.h>
|
||||
#include <math.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <stdio.h>
|
||||
#include "Recast.h"
|
||||
#include "RecastAlloc.h"
|
||||
#include "RecastAssert.h"
|
||||
|
||||
|
||||
// Must be 255 or smaller (not 256) because layer IDs are stored as
|
||||
// a byte where 255 is a special value.
|
||||
#ifndef RC_MAX_LAYERS_DEF
|
||||
#define RC_MAX_LAYERS_DEF 63
|
||||
#endif
|
||||
|
||||
#if RC_MAX_LAYERS_DEF > 255
|
||||
#error RC_MAX_LAYERS_DEF must be 255 or smaller
|
||||
#endif
|
||||
|
||||
#ifndef RC_MAX_NEIS_DEF
|
||||
#define RC_MAX_NEIS_DEF 16
|
||||
#endif
|
||||
|
||||
// Keep type checking.
|
||||
static const int RC_MAX_LAYERS = RC_MAX_LAYERS_DEF;
|
||||
static const int RC_MAX_NEIS = RC_MAX_NEIS_DEF;
|
||||
|
||||
struct rcLayerRegion
|
||||
{
|
||||
unsigned char layers[RC_MAX_LAYERS];
|
||||
unsigned char neis[RC_MAX_NEIS];
|
||||
unsigned short ymin, ymax;
|
||||
unsigned char layerId; // Layer ID
|
||||
unsigned char nlayers; // Layer count
|
||||
unsigned char nneis; // Neighbour count
|
||||
unsigned char base; // Flag indicating if the region is the base of merged regions.
|
||||
};
|
||||
|
||||
|
||||
static bool contains(const unsigned char* a, const unsigned char an, const unsigned char v)
|
||||
{
|
||||
const int n = (int)an;
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
if (a[i] == v)
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool addUnique(unsigned char* a, unsigned char& an, int anMax, unsigned char v)
|
||||
{
|
||||
if (contains(a, an, v))
|
||||
return true;
|
||||
|
||||
if ((int)an >= anMax)
|
||||
return false;
|
||||
|
||||
a[an] = v;
|
||||
an++;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
inline bool overlapRange(const unsigned short amin, const unsigned short amax,
|
||||
const unsigned short bmin, const unsigned short bmax)
|
||||
{
|
||||
return (amin > bmax || amax < bmin) ? false : true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
struct rcLayerSweepSpan
|
||||
{
|
||||
unsigned short ns; // number samples
|
||||
unsigned char id; // region id
|
||||
unsigned char nei; // neighbour id
|
||||
};
|
||||
|
||||
/// @par
|
||||
///
|
||||
/// See the #rcConfig documentation for more information on the configuration parameters.
|
||||
///
|
||||
/// @see rcAllocHeightfieldLayerSet, rcCompactHeightfield, rcHeightfieldLayerSet, rcConfig
|
||||
bool rcBuildHeightfieldLayers(rcContext* ctx, const rcCompactHeightfield& chf,
|
||||
const int borderSize, const int walkableHeight,
|
||||
rcHeightfieldLayerSet& lset)
|
||||
{
|
||||
rcAssert(ctx);
|
||||
|
||||
rcScopedTimer timer(ctx, RC_TIMER_BUILD_LAYERS);
|
||||
|
||||
const int w = chf.width;
|
||||
const int h = chf.height;
|
||||
|
||||
rcScopedDelete<unsigned char> srcReg((unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP));
|
||||
if (!srcReg)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'srcReg' (%d).", chf.spanCount);
|
||||
return false;
|
||||
}
|
||||
memset(srcReg,0xff,sizeof(unsigned char)*chf.spanCount);
|
||||
|
||||
const int nsweeps = chf.width;
|
||||
rcScopedDelete<rcLayerSweepSpan> sweeps((rcLayerSweepSpan*)rcAlloc(sizeof(rcLayerSweepSpan)*nsweeps, RC_ALLOC_TEMP));
|
||||
if (!sweeps)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'sweeps' (%d).", nsweeps);
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
// Partition walkable area into monotone regions.
|
||||
int prevCount[256];
|
||||
unsigned char regId = 0;
|
||||
|
||||
for (int y = borderSize; y < h-borderSize; ++y)
|
||||
{
|
||||
memset(prevCount,0,sizeof(int)*regId);
|
||||
unsigned char sweepId = 0;
|
||||
|
||||
for (int x = borderSize; x < w-borderSize; ++x)
|
||||
{
|
||||
const rcCompactCell& c = chf.cells[x+y*w];
|
||||
|
||||
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
|
||||
{
|
||||
const rcCompactSpan& s = chf.spans[i];
|
||||
if (chf.areas[i] == RC_NULL_AREA) continue;
|
||||
|
||||
unsigned char sid = 0xff;
|
||||
|
||||
// -x
|
||||
if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int ax = x + rcGetDirOffsetX(0);
|
||||
const int ay = y + rcGetDirOffsetY(0);
|
||||
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 0);
|
||||
if (chf.areas[ai] != RC_NULL_AREA && srcReg[ai] != 0xff)
|
||||
sid = srcReg[ai];
|
||||
}
|
||||
|
||||
if (sid == 0xff)
|
||||
{
|
||||
sid = sweepId++;
|
||||
sweeps[sid].nei = 0xff;
|
||||
sweeps[sid].ns = 0;
|
||||
}
|
||||
|
||||
// -y
|
||||
if (rcGetCon(s,3) != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int ax = x + rcGetDirOffsetX(3);
|
||||
const int ay = y + rcGetDirOffsetY(3);
|
||||
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, 3);
|
||||
const unsigned char nr = srcReg[ai];
|
||||
if (nr != 0xff)
|
||||
{
|
||||
// Set neighbour when first valid neighbour is encoutered.
|
||||
if (sweeps[sid].ns == 0)
|
||||
sweeps[sid].nei = nr;
|
||||
|
||||
if (sweeps[sid].nei == nr)
|
||||
{
|
||||
// Update existing neighbour
|
||||
sweeps[sid].ns++;
|
||||
prevCount[nr]++;
|
||||
}
|
||||
else
|
||||
{
|
||||
// This is hit if there is nore than one neighbour.
|
||||
// Invalidate the neighbour.
|
||||
sweeps[sid].nei = 0xff;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
srcReg[i] = sid;
|
||||
}
|
||||
}
|
||||
|
||||
// Create unique ID.
|
||||
for (int i = 0; i < sweepId; ++i)
|
||||
{
|
||||
// If the neighbour is set and there is only one continuous connection to it,
|
||||
// the sweep will be merged with the previous one, else new region is created.
|
||||
if (sweeps[i].nei != 0xff && prevCount[sweeps[i].nei] == (int)sweeps[i].ns)
|
||||
{
|
||||
sweeps[i].id = sweeps[i].nei;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (regId == 255)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Region ID overflow.");
|
||||
return false;
|
||||
}
|
||||
sweeps[i].id = regId++;
|
||||
}
|
||||
}
|
||||
|
||||
// Remap local sweep ids to region ids.
|
||||
for (int x = borderSize; x < w-borderSize; ++x)
|
||||
{
|
||||
const rcCompactCell& c = chf.cells[x+y*w];
|
||||
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
|
||||
{
|
||||
if (srcReg[i] != 0xff)
|
||||
srcReg[i] = sweeps[srcReg[i]].id;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Allocate and init layer regions.
|
||||
const int nregs = (int)regId;
|
||||
rcScopedDelete<rcLayerRegion> regs((rcLayerRegion*)rcAlloc(sizeof(rcLayerRegion)*nregs, RC_ALLOC_TEMP));
|
||||
if (!regs)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'regs' (%d).", nregs);
|
||||
return false;
|
||||
}
|
||||
memset(regs, 0, sizeof(rcLayerRegion)*nregs);
|
||||
for (int i = 0; i < nregs; ++i)
|
||||
{
|
||||
regs[i].layerId = 0xff;
|
||||
regs[i].ymin = 0xffff;
|
||||
regs[i].ymax = 0;
|
||||
}
|
||||
|
||||
// Find region neighbours and overlapping regions.
|
||||
for (int y = 0; y < h; ++y)
|
||||
{
|
||||
for (int x = 0; x < w; ++x)
|
||||
{
|
||||
const rcCompactCell& c = chf.cells[x+y*w];
|
||||
|
||||
unsigned char lregs[RC_MAX_LAYERS];
|
||||
int nlregs = 0;
|
||||
|
||||
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
|
||||
{
|
||||
const rcCompactSpan& s = chf.spans[i];
|
||||
const unsigned char ri = srcReg[i];
|
||||
if (ri == 0xff) continue;
|
||||
|
||||
regs[ri].ymin = rcMin(regs[ri].ymin, s.y);
|
||||
regs[ri].ymax = rcMax(regs[ri].ymax, s.y);
|
||||
|
||||
// Collect all region layers.
|
||||
if (nlregs < RC_MAX_LAYERS)
|
||||
lregs[nlregs++] = ri;
|
||||
|
||||
// Update neighbours
|
||||
for (int dir = 0; dir < 4; ++dir)
|
||||
{
|
||||
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int ax = x + rcGetDirOffsetX(dir);
|
||||
const int ay = y + rcGetDirOffsetY(dir);
|
||||
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
|
||||
const unsigned char rai = srcReg[ai];
|
||||
if (rai != 0xff && rai != ri)
|
||||
{
|
||||
// Don't check return value -- if we cannot add the neighbor
|
||||
// it will just cause a few more regions to be created, which
|
||||
// is fine.
|
||||
addUnique(regs[ri].neis, regs[ri].nneis, RC_MAX_NEIS, rai);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Update overlapping regions.
|
||||
for (int i = 0; i < nlregs-1; ++i)
|
||||
{
|
||||
for (int j = i+1; j < nlregs; ++j)
|
||||
{
|
||||
if (lregs[i] != lregs[j])
|
||||
{
|
||||
rcLayerRegion& ri = regs[lregs[i]];
|
||||
rcLayerRegion& rj = regs[lregs[j]];
|
||||
|
||||
if (!addUnique(ri.layers, ri.nlayers, RC_MAX_LAYERS, lregs[j]) ||
|
||||
!addUnique(rj.layers, rj.nlayers, RC_MAX_LAYERS, lregs[i]))
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// Create 2D layers from regions.
|
||||
unsigned char layerId = 0;
|
||||
|
||||
static const int MAX_STACK = 64;
|
||||
unsigned char stack[MAX_STACK];
|
||||
int nstack = 0;
|
||||
|
||||
for (int i = 0; i < nregs; ++i)
|
||||
{
|
||||
rcLayerRegion& root = regs[i];
|
||||
// Skip already visited.
|
||||
if (root.layerId != 0xff)
|
||||
continue;
|
||||
|
||||
// Start search.
|
||||
root.layerId = layerId;
|
||||
root.base = 1;
|
||||
|
||||
nstack = 0;
|
||||
stack[nstack++] = (unsigned char)i;
|
||||
|
||||
while (nstack)
|
||||
{
|
||||
// Pop front
|
||||
rcLayerRegion& reg = regs[stack[0]];
|
||||
nstack--;
|
||||
for (int j = 0; j < nstack; ++j)
|
||||
stack[j] = stack[j+1];
|
||||
|
||||
const int nneis = (int)reg.nneis;
|
||||
for (int j = 0; j < nneis; ++j)
|
||||
{
|
||||
const unsigned char nei = reg.neis[j];
|
||||
rcLayerRegion& regn = regs[nei];
|
||||
// Skip already visited.
|
||||
if (regn.layerId != 0xff)
|
||||
continue;
|
||||
// Skip if the neighbour is overlapping root region.
|
||||
if (contains(root.layers, root.nlayers, nei))
|
||||
continue;
|
||||
// Skip if the height range would become too large.
|
||||
const int ymin = rcMin(root.ymin, regn.ymin);
|
||||
const int ymax = rcMax(root.ymax, regn.ymax);
|
||||
if ((ymax - ymin) >= 255)
|
||||
continue;
|
||||
|
||||
if (nstack < MAX_STACK)
|
||||
{
|
||||
// Deepen
|
||||
stack[nstack++] = (unsigned char)nei;
|
||||
|
||||
// Mark layer id
|
||||
regn.layerId = layerId;
|
||||
// Merge current layers to root.
|
||||
for (int k = 0; k < regn.nlayers; ++k)
|
||||
{
|
||||
if (!addUnique(root.layers, root.nlayers, RC_MAX_LAYERS, regn.layers[k]))
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
root.ymin = rcMin(root.ymin, regn.ymin);
|
||||
root.ymax = rcMax(root.ymax, regn.ymax);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
layerId++;
|
||||
}
|
||||
|
||||
// Merge non-overlapping regions that are close in height.
|
||||
const unsigned short mergeHeight = (unsigned short)walkableHeight * 4;
|
||||
|
||||
for (int i = 0; i < nregs; ++i)
|
||||
{
|
||||
rcLayerRegion& ri = regs[i];
|
||||
if (!ri.base) continue;
|
||||
|
||||
unsigned char newId = ri.layerId;
|
||||
|
||||
for (;;)
|
||||
{
|
||||
unsigned char oldId = 0xff;
|
||||
|
||||
for (int j = 0; j < nregs; ++j)
|
||||
{
|
||||
if (i == j) continue;
|
||||
rcLayerRegion& rj = regs[j];
|
||||
if (!rj.base) continue;
|
||||
|
||||
// Skip if the regions are not close to each other.
|
||||
if (!overlapRange(ri.ymin,ri.ymax+mergeHeight, rj.ymin,rj.ymax+mergeHeight))
|
||||
continue;
|
||||
// Skip if the height range would become too large.
|
||||
const int ymin = rcMin(ri.ymin, rj.ymin);
|
||||
const int ymax = rcMax(ri.ymax, rj.ymax);
|
||||
if ((ymax - ymin) >= 255)
|
||||
continue;
|
||||
|
||||
// Make sure that there is no overlap when merging 'ri' and 'rj'.
|
||||
bool overlap = false;
|
||||
// Iterate over all regions which have the same layerId as 'rj'
|
||||
for (int k = 0; k < nregs; ++k)
|
||||
{
|
||||
if (regs[k].layerId != rj.layerId)
|
||||
continue;
|
||||
// Check if region 'k' is overlapping region 'ri'
|
||||
// Index to 'regs' is the same as region id.
|
||||
if (contains(ri.layers,ri.nlayers, (unsigned char)k))
|
||||
{
|
||||
overlap = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Cannot merge of regions overlap.
|
||||
if (overlap)
|
||||
continue;
|
||||
|
||||
// Can merge i and j.
|
||||
oldId = rj.layerId;
|
||||
break;
|
||||
}
|
||||
|
||||
// Could not find anything to merge with, stop.
|
||||
if (oldId == 0xff)
|
||||
break;
|
||||
|
||||
// Merge
|
||||
for (int j = 0; j < nregs; ++j)
|
||||
{
|
||||
rcLayerRegion& rj = regs[j];
|
||||
if (rj.layerId == oldId)
|
||||
{
|
||||
rj.base = 0;
|
||||
// Remap layerIds.
|
||||
rj.layerId = newId;
|
||||
// Add overlaid layers from 'rj' to 'ri'.
|
||||
for (int k = 0; k < rj.nlayers; ++k)
|
||||
{
|
||||
if (!addUnique(ri.layers, ri.nlayers, RC_MAX_LAYERS, rj.layers[k]))
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: layer overflow (too many overlapping walkable platforms). Try increasing RC_MAX_LAYERS.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Update height bounds.
|
||||
ri.ymin = rcMin(ri.ymin, rj.ymin);
|
||||
ri.ymax = rcMax(ri.ymax, rj.ymax);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Compact layerIds
|
||||
unsigned char remap[256];
|
||||
memset(remap, 0, 256);
|
||||
|
||||
// Find number of unique layers.
|
||||
layerId = 0;
|
||||
for (int i = 0; i < nregs; ++i)
|
||||
remap[regs[i].layerId] = 1;
|
||||
for (int i = 0; i < 256; ++i)
|
||||
{
|
||||
if (remap[i])
|
||||
remap[i] = layerId++;
|
||||
else
|
||||
remap[i] = 0xff;
|
||||
}
|
||||
// Remap ids.
|
||||
for (int i = 0; i < nregs; ++i)
|
||||
regs[i].layerId = remap[regs[i].layerId];
|
||||
|
||||
// No layers, return empty.
|
||||
if (layerId == 0)
|
||||
return true;
|
||||
|
||||
// Create layers.
|
||||
rcAssert(lset.layers == 0);
|
||||
|
||||
const int lw = w - borderSize*2;
|
||||
const int lh = h - borderSize*2;
|
||||
|
||||
// Build contracted bbox for layers.
|
||||
float bmin[3], bmax[3];
|
||||
rcVcopy(bmin, chf.bmin);
|
||||
rcVcopy(bmax, chf.bmax);
|
||||
bmin[0] += borderSize*chf.cs;
|
||||
bmin[2] += borderSize*chf.cs;
|
||||
bmax[0] -= borderSize*chf.cs;
|
||||
bmax[2] -= borderSize*chf.cs;
|
||||
|
||||
lset.nlayers = (int)layerId;
|
||||
|
||||
lset.layers = (rcHeightfieldLayer*)rcAlloc(sizeof(rcHeightfieldLayer)*lset.nlayers, RC_ALLOC_PERM);
|
||||
if (!lset.layers)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'layers' (%d).", lset.nlayers);
|
||||
return false;
|
||||
}
|
||||
memset(lset.layers, 0, sizeof(rcHeightfieldLayer)*lset.nlayers);
|
||||
|
||||
|
||||
// Store layers.
|
||||
for (int i = 0; i < lset.nlayers; ++i)
|
||||
{
|
||||
unsigned char curId = (unsigned char)i;
|
||||
|
||||
rcHeightfieldLayer* layer = &lset.layers[i];
|
||||
|
||||
const int gridSize = sizeof(unsigned char)*lw*lh;
|
||||
|
||||
layer->heights = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
|
||||
if (!layer->heights)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'heights' (%d).", gridSize);
|
||||
return false;
|
||||
}
|
||||
memset(layer->heights, 0xff, gridSize);
|
||||
|
||||
layer->areas = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
|
||||
if (!layer->areas)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'areas' (%d).", gridSize);
|
||||
return false;
|
||||
}
|
||||
memset(layer->areas, 0, gridSize);
|
||||
|
||||
layer->cons = (unsigned char*)rcAlloc(gridSize, RC_ALLOC_PERM);
|
||||
if (!layer->cons)
|
||||
{
|
||||
ctx->log(RC_LOG_ERROR, "rcBuildHeightfieldLayers: Out of memory 'cons' (%d).", gridSize);
|
||||
return false;
|
||||
}
|
||||
memset(layer->cons, 0, gridSize);
|
||||
|
||||
// Find layer height bounds.
|
||||
int hmin = 0, hmax = 0;
|
||||
for (int j = 0; j < nregs; ++j)
|
||||
{
|
||||
if (regs[j].base && regs[j].layerId == curId)
|
||||
{
|
||||
hmin = (int)regs[j].ymin;
|
||||
hmax = (int)regs[j].ymax;
|
||||
}
|
||||
}
|
||||
|
||||
layer->width = lw;
|
||||
layer->height = lh;
|
||||
layer->cs = chf.cs;
|
||||
layer->ch = chf.ch;
|
||||
|
||||
// Adjust the bbox to fit the heightfield.
|
||||
rcVcopy(layer->bmin, bmin);
|
||||
rcVcopy(layer->bmax, bmax);
|
||||
layer->bmin[1] = bmin[1] + hmin*chf.ch;
|
||||
layer->bmax[1] = bmin[1] + hmax*chf.ch;
|
||||
layer->hmin = hmin;
|
||||
layer->hmax = hmax;
|
||||
|
||||
// Update usable data region.
|
||||
layer->minx = layer->width;
|
||||
layer->maxx = 0;
|
||||
layer->miny = layer->height;
|
||||
layer->maxy = 0;
|
||||
|
||||
// Copy height and area from compact heightfield.
|
||||
for (int y = 0; y < lh; ++y)
|
||||
{
|
||||
for (int x = 0; x < lw; ++x)
|
||||
{
|
||||
const int cx = borderSize+x;
|
||||
const int cy = borderSize+y;
|
||||
const rcCompactCell& c = chf.cells[cx+cy*w];
|
||||
for (int j = (int)c.index, nj = (int)(c.index+c.count); j < nj; ++j)
|
||||
{
|
||||
const rcCompactSpan& s = chf.spans[j];
|
||||
// Skip unassigned regions.
|
||||
if (srcReg[j] == 0xff)
|
||||
continue;
|
||||
// Skip of does nto belong to current layer.
|
||||
unsigned char lid = regs[srcReg[j]].layerId;
|
||||
if (lid != curId)
|
||||
continue;
|
||||
|
||||
// Update data bounds.
|
||||
layer->minx = rcMin(layer->minx, x);
|
||||
layer->maxx = rcMax(layer->maxx, x);
|
||||
layer->miny = rcMin(layer->miny, y);
|
||||
layer->maxy = rcMax(layer->maxy, y);
|
||||
|
||||
// Store height and area type.
|
||||
const int idx = x+y*lw;
|
||||
layer->heights[idx] = (unsigned char)(s.y - hmin);
|
||||
layer->areas[idx] = chf.areas[j];
|
||||
|
||||
// Check connection.
|
||||
unsigned char portal = 0;
|
||||
unsigned char con = 0;
|
||||
for (int dir = 0; dir < 4; ++dir)
|
||||
{
|
||||
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
|
||||
{
|
||||
const int ax = cx + rcGetDirOffsetX(dir);
|
||||
const int ay = cy + rcGetDirOffsetY(dir);
|
||||
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
|
||||
unsigned char alid = srcReg[ai] != 0xff ? regs[srcReg[ai]].layerId : 0xff;
|
||||
// Portal mask
|
||||
if (chf.areas[ai] != RC_NULL_AREA && lid != alid)
|
||||
{
|
||||
portal |= (unsigned char)(1<<dir);
|
||||
// Update height so that it matches on both sides of the portal.
|
||||
const rcCompactSpan& as = chf.spans[ai];
|
||||
if (as.y > hmin)
|
||||
layer->heights[idx] = rcMax(layer->heights[idx], (unsigned char)(as.y - hmin));
|
||||
}
|
||||
// Valid connection mask
|
||||
if (chf.areas[ai] != RC_NULL_AREA && lid == alid)
|
||||
{
|
||||
const int nx = ax - borderSize;
|
||||
const int ny = ay - borderSize;
|
||||
if (nx >= 0 && ny >= 0 && nx < lw && ny < lh)
|
||||
con |= (unsigned char)(1<<dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
layer->cons[idx] = (portal << 4) | con;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (layer->minx > layer->maxx)
|
||||
layer->minx = layer->maxx = 0;
|
||||
if (layer->miny > layer->maxy)
|
||||
layer->miny = layer->maxy = 0;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,562 @@
|
||||
//
|
||||
// Copyright (c) 2009-2010 Mikko Mononen [email protected]
|
||||
//
|
||||
// This software is provided 'as-is', without any express or implied
|
||||
// warranty. In no event will the authors be held liable for any damages
|
||||
// arising from the use of this software.
|
||||
// Permission is granted to anyone to use this software for any purpose,
|
||||
// including commercial applications, and to alter it and redistribute it
|
||||
// freely, subject to the following restrictions:
|
||||
// 1. The origin of this software must not be misrepresented; you must not
|
||||
// claim that you wrote the original software. If you use this software
|
||||
// in a product, an acknowledgment in the product documentation would be
|
||||
// appreciated but is not required.
|
||||
// 2. Altered source versions must be plainly marked as such, and must not be
|
||||
// misrepresented as being the original software.
|
||||
// 3. This notice may not be removed or altered from any source distribution.
|
||||
//
|
||||
|
||||
#include <math.h>
|
||||
#include "Recast.h"
|
||||
#include "RecastAlloc.h"
|
||||
#include "RecastAssert.h"
|
||||
|
||||
/// Check whether two bounding boxes overlap
|
||||
///
|
||||
/// @param[in] aMin Min axis extents of bounding box A
|
||||
/// @param[in] aMax Max axis extents of bounding box A
|
||||
/// @param[in] bMin Min axis extents of bounding box B
|
||||
/// @param[in] bMax Max axis extents of bounding box B
|
||||
/// @returns true if the two bounding boxes overlap. False otherwise.
|
||||
static bool overlapBounds(const float* aMin, const float* aMax, const float* bMin, const float* bMax)
|
||||
{
|
||||
return
|
||||
aMin[0] <= bMax[0] && aMax[0] >= bMin[0] &&
|
||||
aMin[1] <= bMax[1] && aMax[1] >= bMin[1] &&
|
||||
aMin[2] <= bMax[2] && aMax[2] >= bMin[2];
|
||||
}
|
||||
|
||||
/// Allocates a new span in the heightfield.
|
||||
/// Use a memory pool and free list to minimize actual allocations.
|
||||
///
|
||||
/// @param[in] heightfield The heightfield
|
||||
/// @returns A pointer to the allocated or re-used span memory.
|
||||
static rcSpan* allocSpan(rcHeightfield& heightfield)
|
||||
{
|
||||
// If necessary, allocate new page and update the freelist.
|
||||
if (heightfield.freelist == NULL || heightfield.freelist->next == NULL)
|
||||
{
|
||||
// Create new page.
|
||||
// Allocate memory for the new pool.
|
||||
rcSpanPool* spanPool = (rcSpanPool*)rcAlloc(sizeof(rcSpanPool), RC_ALLOC_PERM);
|
||||
if (spanPool == NULL)
|
||||
{
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Add the pool into the list of pools.
|
||||
spanPool->next = heightfield.pools;
|
||||
heightfield.pools = spanPool;
|
||||
|
||||
// Add new spans to the free list.
|
||||
rcSpan* freeList = heightfield.freelist;
|
||||
rcSpan* head = &spanPool->items[0];
|
||||
rcSpan* it = &spanPool->items[RC_SPANS_PER_POOL];
|
||||
do
|
||||
{
|
||||
--it;
|
||||
it->next = freeList;
|
||||
freeList = it;
|
||||
}
|
||||
while (it != head);
|
||||
heightfield.freelist = it;
|
||||
}
|
||||
|
||||
// Pop item from the front of the free list.
|
||||
rcSpan* newSpan = heightfield.freelist;
|
||||
heightfield.freelist = heightfield.freelist->next;
|
||||
return newSpan;
|
||||
}
|
||||
|
||||
/// Releases the memory used by the span back to the heightfield, so it can be re-used for new spans.
|
||||
/// @param[in] heightfield The heightfield.
|
||||
/// @param[in] span A pointer to the span to free
|
||||
static void freeSpan(rcHeightfield& heightfield, rcSpan* span)
|
||||
{
|
||||
if (span == NULL)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Add the span to the front of the free list.
|
||||
span->next = heightfield.freelist;
|
||||
heightfield.freelist = span;
|
||||
}
|
||||
|
||||
/// Adds a span to the heightfield. If the new span overlaps existing spans,
|
||||
/// it will merge the new span with the existing ones.
|
||||
///
|
||||
/// @param[in] heightfield Heightfield to add spans to
|
||||
/// @param[in] x The new span's column cell x index
|
||||
/// @param[in] z The new span's column cell z index
|
||||
/// @param[in] min The new span's minimum cell index
|
||||
/// @param[in] max The new span's maximum cell index
|
||||
/// @param[in] areaID The new span's area type ID
|
||||
/// @param[in] flagMergeThreshold How close two spans maximum extents need to be to merge area type IDs
|
||||
static bool addSpan(rcHeightfield& heightfield,
|
||||
const int x, const int z,
|
||||
const unsigned short min, const unsigned short max,
|
||||
const unsigned char areaID, const int flagMergeThreshold)
|
||||
{
|
||||
// Create the new span.
|
||||
rcSpan* newSpan = allocSpan(heightfield);
|
||||
if (newSpan == NULL)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
newSpan->smin = min;
|
||||
newSpan->smax = max;
|
||||
newSpan->area = areaID;
|
||||
newSpan->next = NULL;
|
||||
|
||||
const int columnIndex = x + z * heightfield.width;
|
||||
rcSpan* previousSpan = NULL;
|
||||
rcSpan* currentSpan = heightfield.spans[columnIndex];
|
||||
|
||||
// Insert the new span, possibly merging it with existing spans.
|
||||
while (currentSpan != NULL)
|
||||
{
|
||||
if (currentSpan->smin > newSpan->smax)
|
||||
{
|
||||
// Current span is completely after the new span, break.
|
||||
break;
|
||||
}
|
||||
|
||||
if (currentSpan->smax < newSpan->smin)
|
||||
{
|
||||
// Current span is completely before the new span. Keep going.
|
||||
previousSpan = currentSpan;
|
||||
currentSpan = currentSpan->next;
|
||||
}
|
||||
else
|
||||
{
|
||||
// The new span overlaps with an existing span. Merge them.
|
||||
if (currentSpan->smin < newSpan->smin)
|
||||
{
|
||||
newSpan->smin = currentSpan->smin;
|
||||
}
|
||||
if (currentSpan->smax > newSpan->smax)
|
||||
{
|
||||
newSpan->smax = currentSpan->smax;
|
||||
}
|
||||
|
||||
// Merge flags.
|
||||
if (rcAbs((int)newSpan->smax - (int)currentSpan->smax) <= flagMergeThreshold)
|
||||
{
|
||||
// Higher area ID numbers indicate higher resolution priority.
|
||||
newSpan->area = rcMax(newSpan->area, currentSpan->area);
|
||||
}
|
||||
|
||||
// Remove the current span since it's now merged with newSpan.
|
||||
// Keep going because there might be other overlapping spans that also need to be merged.
|
||||
rcSpan* next = currentSpan->next;
|
||||
freeSpan(heightfield, currentSpan);
|
||||
if (previousSpan)
|
||||
{
|
||||
previousSpan->next = next;
|
||||
}
|
||||
else
|
||||
{
|
||||
heightfield.spans[columnIndex] = next;
|
||||
}
|
||||
currentSpan = next;
|
||||
}
|
||||
}
|
||||
|
||||
// Insert new span after prev
|
||||
if (previousSpan != NULL)
|
||||
{
|
||||
newSpan->next = previousSpan->next;
|
||||
previousSpan->next = newSpan;
|
||||
}
|
||||
else
|
||||
{
|
||||
// This span should go before the others in the list
|
||||
newSpan->next = heightfield.spans[columnIndex];
|
||||
heightfield.spans[columnIndex] = newSpan;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool rcAddSpan(rcContext* context, rcHeightfield& heightfield,
|
||||
const int x, const int z,
|
||||
const unsigned short spanMin, const unsigned short spanMax,
|
||||
const unsigned char areaID, const int flagMergeThreshold)
|
||||
{
|
||||
rcAssert(context);
|
||||
|
||||
// Span is zero size or inverted size. Ignore.
|
||||
if (spanMin >= spanMax)
|
||||
{
|
||||
context->log(RC_LOG_WARNING, "rcAddSpan: Adding a span with zero or negative size. Ignored.");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!addSpan(heightfield, x, z, spanMin, spanMax, areaID, flagMergeThreshold))
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcAddSpan: Out of memory.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
enum rcAxis
|
||||
{
|
||||
RC_AXIS_X = 0,
|
||||
RC_AXIS_Y = 1,
|
||||
RC_AXIS_Z = 2
|
||||
};
|
||||
|
||||
/// Divides a convex polygon of max 12 vertices into two convex polygons
|
||||
/// across a separating axis.
|
||||
///
|
||||
/// @param[in] inVerts The input polygon vertices
|
||||
/// @param[in] inVertsCount The number of input polygon vertices
|
||||
/// @param[out] outVerts1 Resulting polygon 1's vertices
|
||||
/// @param[out] outVerts1Count The number of resulting polygon 1 vertices
|
||||
/// @param[out] outVerts2 Resulting polygon 2's vertices
|
||||
/// @param[out] outVerts2Count The number of resulting polygon 2 vertices
|
||||
/// @param[in] axisOffset THe offset along the specified axis
|
||||
/// @param[in] axis The separating axis
|
||||
static void dividePoly(const float* inVerts, int inVertsCount,
|
||||
float* outVerts1, int* outVerts1Count,
|
||||
float* outVerts2, int* outVerts2Count,
|
||||
float axisOffset, rcAxis axis)
|
||||
{
|
||||
rcAssert(inVertsCount <= 12);
|
||||
|
||||
// How far positive or negative away from the separating axis is each vertex.
|
||||
float inVertAxisDelta[12];
|
||||
for (int inVert = 0; inVert < inVertsCount; ++inVert)
|
||||
{
|
||||
inVertAxisDelta[inVert] = axisOffset - inVerts[inVert * 3 + axis];
|
||||
}
|
||||
|
||||
int poly1Vert = 0;
|
||||
int poly2Vert = 0;
|
||||
for (int inVertA = 0, inVertB = inVertsCount - 1; inVertA < inVertsCount; inVertB = inVertA, ++inVertA)
|
||||
{
|
||||
// If the two vertices are on the same side of the separating axis
|
||||
bool sameSide = (inVertAxisDelta[inVertA] >= 0) == (inVertAxisDelta[inVertB] >= 0);
|
||||
|
||||
if (!sameSide)
|
||||
{
|
||||
float s = inVertAxisDelta[inVertB] / (inVertAxisDelta[inVertB] - inVertAxisDelta[inVertA]);
|
||||
outVerts1[poly1Vert * 3 + 0] = inVerts[inVertB * 3 + 0] + (inVerts[inVertA * 3 + 0] - inVerts[inVertB * 3 + 0]) * s;
|
||||
outVerts1[poly1Vert * 3 + 1] = inVerts[inVertB * 3 + 1] + (inVerts[inVertA * 3 + 1] - inVerts[inVertB * 3 + 1]) * s;
|
||||
outVerts1[poly1Vert * 3 + 2] = inVerts[inVertB * 3 + 2] + (inVerts[inVertA * 3 + 2] - inVerts[inVertB * 3 + 2]) * s;
|
||||
rcVcopy(&outVerts2[poly2Vert * 3], &outVerts1[poly1Vert * 3]);
|
||||
poly1Vert++;
|
||||
poly2Vert++;
|
||||
|
||||
// add the inVertA point to the right polygon. Do NOT add points that are on the dividing line
|
||||
// since these were already added above
|
||||
if (inVertAxisDelta[inVertA] > 0)
|
||||
{
|
||||
rcVcopy(&outVerts1[poly1Vert * 3], &inVerts[inVertA * 3]);
|
||||
poly1Vert++;
|
||||
}
|
||||
else if (inVertAxisDelta[inVertA] < 0)
|
||||
{
|
||||
rcVcopy(&outVerts2[poly2Vert * 3], &inVerts[inVertA * 3]);
|
||||
poly2Vert++;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
// add the inVertA point to the right polygon. Addition is done even for points on the dividing line
|
||||
if (inVertAxisDelta[inVertA] >= 0)
|
||||
{
|
||||
rcVcopy(&outVerts1[poly1Vert * 3], &inVerts[inVertA * 3]);
|
||||
poly1Vert++;
|
||||
if (inVertAxisDelta[inVertA] != 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
}
|
||||
rcVcopy(&outVerts2[poly2Vert * 3], &inVerts[inVertA * 3]);
|
||||
poly2Vert++;
|
||||
}
|
||||
}
|
||||
|
||||
*outVerts1Count = poly1Vert;
|
||||
*outVerts2Count = poly2Vert;
|
||||
}
|
||||
|
||||
/// Rasterize a single triangle to the heightfield.
|
||||
///
|
||||
/// This code is extremely hot, so much care should be given to maintaining maximum perf here.
|
||||
///
|
||||
/// @param[in] v0 Triangle vertex 0
|
||||
/// @param[in] v1 Triangle vertex 1
|
||||
/// @param[in] v2 Triangle vertex 2
|
||||
/// @param[in] areaID The area ID to assign to the rasterized spans
|
||||
/// @param[in] heightfield Heightfield to rasterize into
|
||||
/// @param[in] heightfieldBBMin The min extents of the heightfield bounding box
|
||||
/// @param[in] heightfieldBBMax The max extents of the heightfield bounding box
|
||||
/// @param[in] cellSize The x and z axis size of a voxel in the heightfield
|
||||
/// @param[in] inverseCellSize 1 / cellSize
|
||||
/// @param[in] inverseCellHeight 1 / cellHeight
|
||||
/// @param[in] flagMergeThreshold The threshold in which area flags will be merged
|
||||
/// @returns true if the operation completes successfully. false if there was an error adding spans to the heightfield.
|
||||
static bool rasterizeTri(const float* v0, const float* v1, const float* v2,
|
||||
const unsigned char areaID, rcHeightfield& heightfield,
|
||||
const float* heightfieldBBMin, const float* heightfieldBBMax,
|
||||
const float cellSize, const float inverseCellSize, const float inverseCellHeight,
|
||||
const int flagMergeThreshold)
|
||||
{
|
||||
// Calculate the bounding box of the triangle.
|
||||
float triBBMin[3];
|
||||
rcVcopy(triBBMin, v0);
|
||||
rcVmin(triBBMin, v1);
|
||||
rcVmin(triBBMin, v2);
|
||||
|
||||
float triBBMax[3];
|
||||
rcVcopy(triBBMax, v0);
|
||||
rcVmax(triBBMax, v1);
|
||||
rcVmax(triBBMax, v2);
|
||||
|
||||
// If the triangle does not touch the bounding box of the heightfield, skip the triangle.
|
||||
if (!overlapBounds(triBBMin, triBBMax, heightfieldBBMin, heightfieldBBMax))
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
const int w = heightfield.width;
|
||||
const int h = heightfield.height;
|
||||
const float by = heightfieldBBMax[1] - heightfieldBBMin[1];
|
||||
|
||||
// Calculate the footprint of the triangle on the grid's z-axis
|
||||
int z0 = (int)((triBBMin[2] - heightfieldBBMin[2]) * inverseCellSize);
|
||||
int z1 = (int)((triBBMax[2] - heightfieldBBMin[2]) * inverseCellSize);
|
||||
|
||||
// use -1 rather than 0 to cut the polygon properly at the start of the tile
|
||||
z0 = rcClamp(z0, -1, h - 1);
|
||||
z1 = rcClamp(z1, 0, h - 1);
|
||||
|
||||
// Clip the triangle into all grid cells it touches.
|
||||
float buf[7 * 3 * 4];
|
||||
float* in = buf;
|
||||
float* inRow = buf + 7 * 3;
|
||||
float* p1 = inRow + 7 * 3;
|
||||
float* p2 = p1 + 7 * 3;
|
||||
|
||||
rcVcopy(&in[0], v0);
|
||||
rcVcopy(&in[1 * 3], v1);
|
||||
rcVcopy(&in[2 * 3], v2);
|
||||
int nvRow;
|
||||
int nvIn = 3;
|
||||
|
||||
for (int z = z0; z <= z1; ++z)
|
||||
{
|
||||
// Clip polygon to row. Store the remaining polygon as well
|
||||
const float cellZ = heightfieldBBMin[2] + (float)z * cellSize;
|
||||
dividePoly(in, nvIn, inRow, &nvRow, p1, &nvIn, cellZ + cellSize, RC_AXIS_Z);
|
||||
rcSwap(in, p1);
|
||||
|
||||
if (nvRow < 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (z < 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// find X-axis bounds of the row
|
||||
float minX = inRow[0];
|
||||
float maxX = inRow[0];
|
||||
for (int vert = 1; vert < nvRow; ++vert)
|
||||
{
|
||||
if (minX > inRow[vert * 3])
|
||||
{
|
||||
minX = inRow[vert * 3];
|
||||
}
|
||||
if (maxX < inRow[vert * 3])
|
||||
{
|
||||
maxX = inRow[vert * 3];
|
||||
}
|
||||
}
|
||||
int x0 = (int)((minX - heightfieldBBMin[0]) * inverseCellSize);
|
||||
int x1 = (int)((maxX - heightfieldBBMin[0]) * inverseCellSize);
|
||||
if (x1 < 0 || x0 >= w)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
x0 = rcClamp(x0, -1, w - 1);
|
||||
x1 = rcClamp(x1, 0, w - 1);
|
||||
|
||||
int nv;
|
||||
int nv2 = nvRow;
|
||||
|
||||
for (int x = x0; x <= x1; ++x)
|
||||
{
|
||||
// Clip polygon to column. store the remaining polygon as well
|
||||
const float cx = heightfieldBBMin[0] + (float)x * cellSize;
|
||||
dividePoly(inRow, nv2, p1, &nv, p2, &nv2, cx + cellSize, RC_AXIS_X);
|
||||
rcSwap(inRow, p2);
|
||||
|
||||
if (nv < 3)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (x < 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Calculate min and max of the span.
|
||||
float spanMin = p1[1];
|
||||
float spanMax = p1[1];
|
||||
for (int vert = 1; vert < nv; ++vert)
|
||||
{
|
||||
spanMin = rcMin(spanMin, p1[vert * 3 + 1]);
|
||||
spanMax = rcMax(spanMax, p1[vert * 3 + 1]);
|
||||
}
|
||||
spanMin -= heightfieldBBMin[1];
|
||||
spanMax -= heightfieldBBMin[1];
|
||||
|
||||
// Skip the span if it's completely outside the heightfield bounding box
|
||||
if (spanMax < 0.0f)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if (spanMin > by)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
// Clamp the span to the heightfield bounding box.
|
||||
if (spanMin < 0.0f)
|
||||
{
|
||||
spanMin = 0;
|
||||
}
|
||||
if (spanMax > by)
|
||||
{
|
||||
spanMax = by;
|
||||
}
|
||||
|
||||
// Snap the span to the heightfield height grid.
|
||||
unsigned short spanMinCellIndex = (unsigned short)rcClamp((int)floorf(spanMin * inverseCellHeight), 0, RC_SPAN_MAX_HEIGHT);
|
||||
unsigned short spanMaxCellIndex = (unsigned short)rcClamp((int)ceilf(spanMax * inverseCellHeight), (int)spanMinCellIndex + 1, RC_SPAN_MAX_HEIGHT);
|
||||
|
||||
if (!addSpan(heightfield, x, z, spanMinCellIndex, spanMaxCellIndex, areaID, flagMergeThreshold))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool rcRasterizeTriangle(rcContext* context,
|
||||
const float* v0, const float* v1, const float* v2,
|
||||
const unsigned char areaID, rcHeightfield& heightfield, const int flagMergeThreshold)
|
||||
{
|
||||
rcAssert(context != NULL);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
|
||||
|
||||
// Rasterize the single triangle.
|
||||
const float inverseCellSize = 1.0f / heightfield.cs;
|
||||
const float inverseCellHeight = 1.0f / heightfield.ch;
|
||||
if (!rasterizeTri(v0, v1, v2, areaID, heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcRasterizeTriangle: Out of memory.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool rcRasterizeTriangles(rcContext* context,
|
||||
const float* verts, const int /*nv*/,
|
||||
const int* tris, const unsigned char* triAreaIDs, const int numTris,
|
||||
rcHeightfield& heightfield, const int flagMergeThreshold)
|
||||
{
|
||||
rcAssert(context != NULL);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
|
||||
|
||||
// Rasterize the triangles.
|
||||
const float inverseCellSize = 1.0f / heightfield.cs;
|
||||
const float inverseCellHeight = 1.0f / heightfield.ch;
|
||||
for (int triIndex = 0; triIndex < numTris; ++triIndex)
|
||||
{
|
||||
const float* v0 = &verts[tris[triIndex * 3 + 0] * 3];
|
||||
const float* v1 = &verts[tris[triIndex * 3 + 1] * 3];
|
||||
const float* v2 = &verts[tris[triIndex * 3 + 2] * 3];
|
||||
if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool rcRasterizeTriangles(rcContext* context,
|
||||
const float* verts, const int /*nv*/,
|
||||
const unsigned short* tris, const unsigned char* triAreaIDs, const int numTris,
|
||||
rcHeightfield& heightfield, const int flagMergeThreshold)
|
||||
{
|
||||
rcAssert(context != NULL);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
|
||||
|
||||
// Rasterize the triangles.
|
||||
const float inverseCellSize = 1.0f / heightfield.cs;
|
||||
const float inverseCellHeight = 1.0f / heightfield.ch;
|
||||
for (int triIndex = 0; triIndex < numTris; ++triIndex)
|
||||
{
|
||||
const float* v0 = &verts[tris[triIndex * 3 + 0] * 3];
|
||||
const float* v1 = &verts[tris[triIndex * 3 + 1] * 3];
|
||||
const float* v2 = &verts[tris[triIndex * 3 + 2] * 3];
|
||||
if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool rcRasterizeTriangles(rcContext* context,
|
||||
const float* verts, const unsigned char* triAreaIDs, const int numTris,
|
||||
rcHeightfield& heightfield, const int flagMergeThreshold)
|
||||
{
|
||||
rcAssert(context != NULL);
|
||||
|
||||
rcScopedTimer timer(context, RC_TIMER_RASTERIZE_TRIANGLES);
|
||||
|
||||
// Rasterize the triangles.
|
||||
const float inverseCellSize = 1.0f / heightfield.cs;
|
||||
const float inverseCellHeight = 1.0f / heightfield.ch;
|
||||
for (int triIndex = 0; triIndex < numTris; ++triIndex)
|
||||
{
|
||||
const float* v0 = &verts[(triIndex * 3 + 0) * 3];
|
||||
const float* v1 = &verts[(triIndex * 3 + 1) * 3];
|
||||
const float* v2 = &verts[(triIndex * 3 + 2) * 3];
|
||||
if (!rasterizeTri(v0, v1, v2, triAreaIDs[triIndex], heightfield, heightfield.bmin, heightfield.bmax, heightfield.cs, inverseCellSize, inverseCellHeight, flagMergeThreshold))
|
||||
{
|
||||
context->log(RC_LOG_ERROR, "rcRasterizeTriangles: Out of memory.");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,58 @@
|
||||
<#
|
||||
Build the ground AI simulator's runtime: the open-source daScript interpreter (daslang.exe) at a
|
||||
pinned commit, with this project's native module `wto_sim` (native\wto-ai-sim\module).
|
||||
|
||||
powershell -NoProfile -ExecutionPolicy Bypass -File native\wto-ai-sim\build.ps1
|
||||
|
||||
The daScript checkout goes to build\daslang (cloned when missing, about 420 MB), the build to
|
||||
build\daslang-build. Neither is part of the repository. The module folder is linked into the
|
||||
checkout as modules\wtoSim, so the daScript build compiles it with its own module rules and
|
||||
daslang loads it at start. Needs Visual Studio with the x64 C++ tools; CMake and Ninja are the
|
||||
ones Visual Studio bundles.
|
||||
#>
|
||||
param(
|
||||
[string]$DasRoot = (Join-Path $PSScriptRoot '..\..\build\daslang'),
|
||||
[string]$BuildDir = (Join-Path $PSScriptRoot '..\..\build\daslang-build')
|
||||
)
|
||||
$ErrorActionPreference = 'Stop'
|
||||
|
||||
# daScript 0.6.6, the version the simulator was verified with (docs: tank-ai-revision-plan 3.3.1).
|
||||
$pin = '7a51c4ef9927dbc92ecf4cab67ae41b41d239f4a'
|
||||
$repo = 'https://github.com/GaijinEntertainment/daScript.git'
|
||||
|
||||
if (-not (Test-Path (Join-Path $DasRoot '.git'))) {
|
||||
git clone --no-checkout $repo $DasRoot
|
||||
if ($LASTEXITCODE -ne 0) { throw 'git clone of daScript failed' }
|
||||
}
|
||||
$head = (git -C $DasRoot rev-parse HEAD 2>$null)
|
||||
if ($head -ne $pin) {
|
||||
git -C $DasRoot fetch origin $pin
|
||||
git -C $DasRoot checkout --detach $pin
|
||||
if ($LASTEXITCODE -ne 0) { throw "checkout of daScript $pin failed" }
|
||||
}
|
||||
|
||||
$moduleLink = Join-Path $DasRoot 'modules\wtoSim'
|
||||
if (-not (Test-Path $moduleLink)) {
|
||||
New-Item -ItemType Junction -Path $moduleLink -Target (Join-Path $PSScriptRoot 'module') | Out-Null
|
||||
}
|
||||
|
||||
$vswhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
|
||||
$vs = & $vswhere -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath
|
||||
if (-not $vs) { throw 'Visual Studio with the x64 C++ tools was not found' }
|
||||
$vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat'
|
||||
$cmakeDir = Join-Path $vs 'Common7\IDE\CommonExtensions\Microsoft\CMake'
|
||||
$cmake = Join-Path $cmakeDir 'CMake\bin\cmake.exe'
|
||||
$ninja = Join-Path $cmakeDir 'Ninja\ninja.exe'
|
||||
|
||||
# Only the interpreter and the core runtime; every optional module of daScript stays off.
|
||||
$off = @('ACCELERATE', 'AOT_EXAMPLES', 'AUDIO', 'CLANG_BIND', 'CLIPBOARD', 'CRYPTO', 'CUDA', 'FLEX_BISON', 'GLFW', 'HV',
|
||||
'IMGUI', 'LLVM', 'MESHOPTIMIZER', 'METAL', 'PUGIXML', 'SMT', 'SQLITE', 'STBIMAGE', 'STDDLG', 'TERMINAL', 'TESTS',
|
||||
'TREE_SITTER', 'TUTORIAL', 'VULKAN') | ForEach-Object { "-DDAS_$($_)_DISABLED=ON" }
|
||||
$native = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path -replace '\\', '/'
|
||||
$configure = "`"$cmake`" -S `"$DasRoot`" -B `"$BuildDir`" -G Ninja -DCMAKE_MAKE_PROGRAM=`"$ninja`" " +
|
||||
"-DCMAKE_BUILD_TYPE=Release -DDAS_TOOLS_DISABLED=OFF -DWTO_SIM_NATIVE_ROOT=`"$native`" $($off -join ' ')"
|
||||
cmd /c "`"$vcvars`" >nul && $configure"
|
||||
if ($LASTEXITCODE -ne 0) { throw "cmake configure failed with $LASTEXITCODE" }
|
||||
cmd /c "`"$vcvars`" >nul && `"$cmake`" --build `"$BuildDir`" --target daslang dasModuleWtoSim"
|
||||
if ($LASTEXITCODE -ne 0) { throw "cmake build failed with $LASTEXITCODE" }
|
||||
Write-Output (Join-Path $DasRoot 'bin\daslang.exe')
|
||||
@@ -0,0 +1,9 @@
|
||||
options gen2
|
||||
require daslib/fio
|
||||
|
||||
[export]
|
||||
def initialize(project_path : string) {
|
||||
if (das_is_dll_build()) {
|
||||
register_dynamic_module("{project_path}/dasModuleWtoSim.shared_module", "Module_WtoSim")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
# The daScript build writes the shared module next to its sources.
|
||||
*.shared_module
|
||||
*.pdb
|
||||
*.lib
|
||||
*.exp
|
||||
*.ilk
|
||||
@@ -0,0 +1,49 @@
|
||||
# Ground AI simulator module `wto_sim` for the open-source daScript build. native/wto-ai-sim/build.ps1
|
||||
# links this folder into the daScript checkout as modules/wtoSim, so its build includes it like its
|
||||
# own modules and daslang loads the shared module at start (.das_module).
|
||||
IF ((NOT DAS_WTOSIM_INCLUDED) AND ((NOT ${DAS_WTOSIM_DISABLED}) OR (NOT DEFINED DAS_WTOSIM_DISABLED)))
|
||||
SET(DAS_WTOSIM_INCLUDED TRUE)
|
||||
MESSAGE(STATUS "wtoSim module included.")
|
||||
|
||||
# The project's native folder: given by build.ps1, else found through the link.
|
||||
IF(DEFINED WTO_SIM_NATIVE_ROOT)
|
||||
SET(WTO_SIM_NATIVE ${WTO_SIM_NATIVE_ROOT})
|
||||
ELSE()
|
||||
FILE(REAL_PATH "${CMAKE_CURRENT_LIST_DIR}" _wto_sim_here)
|
||||
GET_FILENAME_COMPONENT(WTO_SIM_NATIVE "${_wto_sim_here}/../.." ABSOLUTE)
|
||||
ENDIF()
|
||||
SET(WTO_SIM_DIR ${CMAKE_CURRENT_LIST_DIR})
|
||||
SET(WTO_SIM_NAV_DIR ${WTO_SIM_NATIVE}/wto-nav)
|
||||
SET(WTO_SIM_DETOUR_DIR ${WTO_SIM_NATIVE}/third_party/recastnavigation/Detour)
|
||||
|
||||
# The game's navigation engine and request protocol with upstream Detour, at their own warning level.
|
||||
FILE(GLOB WTO_SIM_DETOUR_SRC ${WTO_SIM_DETOUR_DIR}/Source/*.cpp)
|
||||
ADD_LIBRARY(wtoSimNav STATIC
|
||||
${WTO_SIM_DETOUR_SRC}
|
||||
${WTO_SIM_NAV_DIR}/wto_nav_runtime.cpp
|
||||
${WTO_SIM_NAV_DIR}/wto_nav_paths.cpp
|
||||
${WTO_SIM_NAV_DIR}/wto_nav_queries.cpp
|
||||
${WTO_SIM_NAV_DIR}/wto_nav_protocol.c
|
||||
)
|
||||
TARGET_INCLUDE_DIRECTORIES(wtoSimNav PUBLIC
|
||||
$<BUILD_INTERFACE:${WTO_SIM_NAV_DIR}> $<BUILD_INTERFACE:${WTO_SIM_DETOUR_DIR}/Include>)
|
||||
# Every translation unit that sees dtQueryFilter must agree on its layout (wto_nav_runtime.cpp).
|
||||
TARGET_COMPILE_DEFINITIONS(wtoSimNav PUBLIC DT_VIRTUAL_QUERYFILTER PRIVATE _CRT_SECURE_NO_WARNINGS WIN32_LEAN_AND_MEAN)
|
||||
SET_TARGET_PROPERTIES(wtoSimNav PROPERTIES POSITION_INDEPENDENT_CODE ON)
|
||||
# The module's static library is in daScript's export set, so what it links must be too.
|
||||
INSTALL(TARGETS wtoSimNav EXPORT DASTargets ARCHIVE DESTINATION ${DAS_INSTALL_LIBDIR})
|
||||
|
||||
SET(WTO_SIM_MODULE_SRC
|
||||
${WTO_SIM_DIR}/src/wto_sim_module.cpp
|
||||
${WTO_SIM_DIR}/src/sim_geo.cpp
|
||||
${WTO_SIM_DIR}/src/sim_geo.h
|
||||
${WTO_SIM_DIR}/src/sim_nav.cpp
|
||||
${WTO_SIM_DIR}/src/sim_nav.h
|
||||
)
|
||||
ADD_MODULE_CPP(WtoSim)
|
||||
ADD_MODULE_LIB(libDasModuleWtoSim dasModuleWtoSim ${WTO_SIM_MODULE_SRC})
|
||||
TARGET_LINK_LIBRARIES(libDasModuleWtoSim PUBLIC wtoSimNav)
|
||||
TARGET_LINK_LIBRARIES(dasModuleWtoSim PUBLIC wtoSimNav)
|
||||
SETUP_CPP11(libDasModuleWtoSim)
|
||||
SETUP_CPP11(dasModuleWtoSim)
|
||||
ENDIF()
|
||||
@@ -0,0 +1,443 @@
|
||||
// Terrain and object geometry of the simulated level (see sim_geo.h). Objects are indexed on an
|
||||
// 8 m grid in XZ, with each cell's highest triangle and highest ground; a ray walks the cells it
|
||||
// crosses, tests their triangles and marches the terrain only where it dips low enough.
|
||||
#include "sim_geo.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstring>
|
||||
#include <fstream>
|
||||
#include <vector>
|
||||
|
||||
namespace wto_sim {
|
||||
|
||||
namespace {
|
||||
|
||||
const char GEO_MAGIC[8] = { 'W', 'T', 'O', 'G', 'E', 'O', '\0', '\x01' };
|
||||
const uint32_t GEO_MAX_VERSION = 3;
|
||||
const float CELL_M = 8.0f;
|
||||
const float BURIED_M = 0.3f;
|
||||
|
||||
#pragma pack(push, 1)
|
||||
struct GeoHeader {
|
||||
char magic[8];
|
||||
uint32_t version;
|
||||
uint32_t flags;
|
||||
uint8_t everSha1[20];
|
||||
float waterLevel;
|
||||
float boundsMin[2];
|
||||
float boundsMax[2];
|
||||
uint32_t hmWidth;
|
||||
uint32_t hmHeight;
|
||||
float hmCellSize;
|
||||
float hmOrigin[2];
|
||||
uint32_t obsVertCount;
|
||||
uint32_t obsTriCount;
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
// One triangle ready for the ray test: a corner, two edges, and the group it belongs to.
|
||||
struct Tri {
|
||||
float v0[3];
|
||||
float e1[3];
|
||||
float e2[3];
|
||||
int kind;
|
||||
};
|
||||
|
||||
// Obstacle class (WtoObstacleClass) to ray group.
|
||||
const int KIND_OF_CLASS[8] = { RAY_HARD, RAY_BRIDGE, RAY_CRUSHABLE, RAY_TREE, RAY_TREE, RAY_HARD, RAY_PLATFORM, RAY_PLATFORM };
|
||||
|
||||
struct Geo {
|
||||
bool loaded = false;
|
||||
float water = -1.0e6f;
|
||||
uint32_t hmW = 0;
|
||||
uint32_t hmH = 0;
|
||||
float hmCell = 1.0f;
|
||||
float hmOrigin[2] = { 0.0f, 0.0f };
|
||||
std::vector<float> heights;
|
||||
std::vector<Tri> tris;
|
||||
// Grid over the objects: cell (c, r) holds items[offsets[i] .. offsets[i + 1]).
|
||||
float gridOrigin[2] = { 0.0f, 0.0f };
|
||||
int gridCols = 0;
|
||||
int gridRows = 0;
|
||||
std::vector<uint32_t> offsets;
|
||||
std::vector<uint32_t> items;
|
||||
std::vector<float> cellTop;
|
||||
// Highest terrain sample in each cell (with its border), so a ray above it skips the march.
|
||||
std::vector<float> cellGround;
|
||||
// Ray id stamped on each triangle already tested by the current ray.
|
||||
std::vector<uint32_t> stamp;
|
||||
uint32_t rayId = 0;
|
||||
};
|
||||
|
||||
Geo g_geo;
|
||||
|
||||
float height_at(const Geo & g, float x, float z)
|
||||
{
|
||||
if (g.hmW < 2 || g.hmH < 2)
|
||||
return 0.0f;
|
||||
const float fx = std::min(float(g.hmW) - 1.001f, std::max(0.0f, (x - g.hmOrigin[0]) / g.hmCell));
|
||||
const float fz = std::min(float(g.hmH) - 1.001f, std::max(0.0f, (z - g.hmOrigin[1]) / g.hmCell));
|
||||
const uint32_t x0 = uint32_t(fx);
|
||||
const uint32_t z0 = uint32_t(fz);
|
||||
const float tx = fx - float(x0);
|
||||
const float tz = fz - float(z0);
|
||||
const float * row0 = &g.heights[size_t(z0) * g.hmW + x0];
|
||||
const float * row1 = row0 + g.hmW;
|
||||
const float a = row0[0] + (row0[1] - row0[0]) * tx;
|
||||
const float b = row1[0] + (row1[1] - row1[0]) * tx;
|
||||
return a + (b - a) * tz;
|
||||
}
|
||||
|
||||
void sub(const float a[3], const float b[3], float out[3])
|
||||
{
|
||||
out[0] = a[0] - b[0];
|
||||
out[1] = a[1] - b[1];
|
||||
out[2] = a[2] - b[2];
|
||||
}
|
||||
|
||||
void cross(const float a[3], const float b[3], float out[3])
|
||||
{
|
||||
out[0] = a[1] * b[2] - a[2] * b[1];
|
||||
out[1] = a[2] * b[0] - a[0] * b[2];
|
||||
out[2] = a[0] * b[1] - a[1] * b[0];
|
||||
}
|
||||
|
||||
float dot(const float a[3], const float b[3])
|
||||
{
|
||||
return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
}
|
||||
|
||||
bool read_bytes(std::ifstream & in, void * out, size_t size)
|
||||
{
|
||||
in.read(static_cast<char *>(out), std::streamsize(size));
|
||||
return bool(in);
|
||||
}
|
||||
|
||||
bool buried(const Geo & g, const float * v)
|
||||
{
|
||||
return v[1] < height_at(g, v[0], v[2]) - BURIED_M;
|
||||
}
|
||||
|
||||
// Keeps the triangles that are not wholly under the terrain, as ready-to-test records.
|
||||
void keep_triangles(Geo & g, const std::vector<float> & verts, const std::vector<uint8_t> & raw, uint32_t count)
|
||||
{
|
||||
g.tris.clear();
|
||||
g.tris.reserve(count);
|
||||
const uint32_t vertCount = uint32_t(verts.size() / 3);
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
const uint8_t * rec = &raw[size_t(i) * 13];
|
||||
uint32_t idx[3];
|
||||
std::memcpy(idx, rec, sizeof(idx));
|
||||
if (idx[0] >= vertCount || idx[1] >= vertCount || idx[2] >= vertCount)
|
||||
continue;
|
||||
const float * a = &verts[size_t(idx[0]) * 3];
|
||||
const float * b = &verts[size_t(idx[1]) * 3];
|
||||
const float * c = &verts[size_t(idx[2]) * 3];
|
||||
if (buried(g, a) && buried(g, b) && buried(g, c))
|
||||
continue;
|
||||
Tri t;
|
||||
std::memcpy(t.v0, a, sizeof(t.v0));
|
||||
sub(b, a, t.e1);
|
||||
sub(c, a, t.e2);
|
||||
t.kind = KIND_OF_CLASS[rec[12] & 7];
|
||||
g.tris.push_back(t);
|
||||
}
|
||||
}
|
||||
|
||||
void tri_bounds(const Tri & t, float lo[3], float hi[3])
|
||||
{
|
||||
for (int k = 0; k < 3; k++) {
|
||||
const float b = t.v0[k] + t.e1[k];
|
||||
const float c = t.v0[k] + t.e2[k];
|
||||
lo[k] = std::min(t.v0[k], std::min(b, c));
|
||||
hi[k] = std::max(t.v0[k], std::max(b, c));
|
||||
}
|
||||
}
|
||||
|
||||
void cell_span(const Geo & g, const float lo[3], const float hi[3], int & c0, int & c1, int & r0, int & r1)
|
||||
{
|
||||
c0 = std::clamp(int(std::floor((lo[0] - g.gridOrigin[0]) / CELL_M)), 0, g.gridCols - 1);
|
||||
c1 = std::clamp(int(std::floor((hi[0] - g.gridOrigin[0]) / CELL_M)), 0, g.gridCols - 1);
|
||||
r0 = std::clamp(int(std::floor((lo[2] - g.gridOrigin[1]) / CELL_M)), 0, g.gridRows - 1);
|
||||
r1 = std::clamp(int(std::floor((hi[2] - g.gridOrigin[1]) / CELL_M)), 0, g.gridRows - 1);
|
||||
}
|
||||
|
||||
// Two passes over the triangles: count per cell, then fill the cells' item lists.
|
||||
void build_grid(Geo & g, const float boundsMin[2], const float boundsMax[2])
|
||||
{
|
||||
g.gridOrigin[0] = boundsMin[0];
|
||||
g.gridOrigin[1] = boundsMin[1];
|
||||
g.gridCols = std::max(1, int(std::ceil((boundsMax[0] - boundsMin[0]) / CELL_M)));
|
||||
g.gridRows = std::max(1, int(std::ceil((boundsMax[1] - boundsMin[1]) / CELL_M)));
|
||||
const size_t cells = size_t(g.gridCols) * size_t(g.gridRows);
|
||||
std::vector<uint32_t> counts(cells, 0);
|
||||
g.cellTop.assign(cells, -1.0e9f);
|
||||
float lo[3], hi[3];
|
||||
int c0, c1, r0, r1;
|
||||
for (const Tri & t : g.tris) {
|
||||
tri_bounds(t, lo, hi);
|
||||
cell_span(g, lo, hi, c0, c1, r0, r1);
|
||||
for (int r = r0; r <= r1; r++) {
|
||||
for (int c = c0; c <= c1; c++) {
|
||||
const size_t i = size_t(r) * g.gridCols + c;
|
||||
counts[i]++;
|
||||
g.cellTop[i] = std::max(g.cellTop[i], hi[1]);
|
||||
}
|
||||
}
|
||||
}
|
||||
g.offsets.assign(cells + 1, 0);
|
||||
for (size_t i = 0; i < cells; i++)
|
||||
g.offsets[i + 1] = g.offsets[i] + counts[i];
|
||||
g.items.assign(g.offsets[cells], 0);
|
||||
std::fill(counts.begin(), counts.end(), 0);
|
||||
for (uint32_t ti = 0; ti < uint32_t(g.tris.size()); ti++) {
|
||||
tri_bounds(g.tris[ti], lo, hi);
|
||||
cell_span(g, lo, hi, c0, c1, r0, r1);
|
||||
for (int r = r0; r <= r1; r++) {
|
||||
for (int c = c0; c <= c1; c++) {
|
||||
const size_t i = size_t(r) * g.gridCols + c;
|
||||
g.items[g.offsets[i] + counts[i]++] = ti;
|
||||
}
|
||||
}
|
||||
}
|
||||
g.stamp.assign(g.tris.size(), 0);
|
||||
g.rayId = 0;
|
||||
}
|
||||
|
||||
void build_ground_tops(Geo & g)
|
||||
{
|
||||
g.cellGround.assign(size_t(g.gridCols) * g.gridRows, -1.0e9f);
|
||||
for (int r = 0; r < g.gridRows; r++) {
|
||||
for (int c = 0; c < g.gridCols; c++) {
|
||||
const float x0 = g.gridOrigin[0] + float(c) * CELL_M;
|
||||
const float z0 = g.gridOrigin[1] + float(r) * CELL_M;
|
||||
float top = -1.0e9f;
|
||||
for (float z = z0 - g.hmCell; z <= z0 + CELL_M + g.hmCell; z += g.hmCell)
|
||||
for (float x = x0 - g.hmCell; x <= x0 + CELL_M + g.hmCell; x += g.hmCell)
|
||||
top = std::max(top, height_at(g, x, z));
|
||||
g.cellGround[size_t(r) * g.gridCols + c] = top;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Möller–Trumbore, both faces. Returns the distance along the ray, or -1.
|
||||
float ray_tri(const Tri & t, const float p[3], const float dir[3])
|
||||
{
|
||||
float pv[3], tv[3], qv[3];
|
||||
cross(dir, t.e2, pv);
|
||||
const float det = dot(t.e1, pv);
|
||||
if (std::fabs(det) < 1.0e-9f)
|
||||
return -1.0f;
|
||||
const float inv = 1.0f / det;
|
||||
sub(p, t.v0, tv);
|
||||
const float u = dot(tv, pv) * inv;
|
||||
if (u < 0.0f || u > 1.0f)
|
||||
return -1.0f;
|
||||
cross(tv, t.e1, qv);
|
||||
const float v = dot(dir, qv) * inv;
|
||||
if (v < 0.0f || u + v > 1.0f)
|
||||
return -1.0f;
|
||||
return dot(t.e2, qv) * inv;
|
||||
}
|
||||
|
||||
void tri_normal(const Tri & t, const float dir[3], float out[3])
|
||||
{
|
||||
cross(t.e1, t.e2, out);
|
||||
const float len = std::sqrt(dot(out, out));
|
||||
const float s = (len > 0.0f ? 1.0f / len : 0.0f) * (dot(out, dir) > 0.0f ? -1.0f : 1.0f);
|
||||
out[0] *= s;
|
||||
out[1] *= s;
|
||||
out[2] *= s;
|
||||
}
|
||||
|
||||
// Tests the cell's triangles of the selected groups; keeps the nearest hit within maxT.
|
||||
void test_cell(Geo & g, size_t cell, const float p[3], const float dir[3], float maxT, int mask, RayHit & best)
|
||||
{
|
||||
for (uint32_t k = g.offsets[cell]; k < g.offsets[cell + 1]; k++) {
|
||||
const uint32_t ti = g.items[k];
|
||||
if (g.stamp[ti] == g.rayId)
|
||||
continue;
|
||||
g.stamp[ti] = g.rayId;
|
||||
const Tri & t = g.tris[ti];
|
||||
if ((t.kind & mask) == 0)
|
||||
continue;
|
||||
const float d = ray_tri(t, p, dir);
|
||||
if (d >= 0.0f && d <= maxT && (best.dist < 0.0f || d < best.dist)) {
|
||||
best.dist = d;
|
||||
best.kind = t.kind;
|
||||
tri_normal(t, dir, best.normal);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void terrain_normal(const Geo & g, float x, float z, float out[3])
|
||||
{
|
||||
const float e = g.hmCell;
|
||||
const float dx = height_at(g, x + e, z) - height_at(g, x - e, z);
|
||||
const float dz = height_at(g, x, z + e) - height_at(g, x, z - e);
|
||||
out[0] = -dx;
|
||||
out[1] = 2.0f * e;
|
||||
out[2] = -dz;
|
||||
const float len = std::sqrt(dot(out, out));
|
||||
out[0] /= len;
|
||||
out[1] /= len;
|
||||
out[2] /= len;
|
||||
}
|
||||
|
||||
// Height of the ray above the terrain at distance t.
|
||||
float above_ground(const Geo & g, const float p[3], const float dir[3], float t)
|
||||
{
|
||||
return p[1] + dir[1] * t - height_at(g, p[0] + dir[0] * t, p[2] + dir[2] * t);
|
||||
}
|
||||
|
||||
// Terrain crossing of the ray within [t0, t1], marched at half the heightmap spacing and bisected.
|
||||
bool terrain_in(const Geo & g, const float p[3], const float dir[3], float t0, float t1, RayHit & best)
|
||||
{
|
||||
const float step = g.hmCell * 0.5f;
|
||||
float prevT = t0;
|
||||
if (above_ground(g, p, dir, t0) <= 0.0f) {
|
||||
best.dist = t0;
|
||||
} else {
|
||||
bool crossed = false;
|
||||
for (float t = std::min(t0 + step, t1); prevT < t1; t = std::min(t + step, t1)) {
|
||||
if (above_ground(g, p, dir, t) <= 0.0f) {
|
||||
float lo = prevT;
|
||||
float hi = t;
|
||||
for (int i = 0; i < 8; i++) {
|
||||
const float mid = 0.5f * (lo + hi);
|
||||
if (above_ground(g, p, dir, mid) > 0.0f)
|
||||
lo = mid;
|
||||
else
|
||||
hi = mid;
|
||||
}
|
||||
best.dist = hi;
|
||||
crossed = true;
|
||||
break;
|
||||
}
|
||||
prevT = t;
|
||||
}
|
||||
if (!crossed)
|
||||
return false;
|
||||
}
|
||||
best.kind = 0;
|
||||
terrain_normal(g, p[0] + dir[0] * best.dist, p[2] + dir[2] * best.dist, best.normal);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Walks the grid cells under the ray (2D DDA in XZ). In each cell the terrain is marched only when
|
||||
// the ray dips below the cell's highest ground, the objects tested only when it dips below the
|
||||
// cell's highest triangle. Stops at the first cell that holds a hit.
|
||||
void ray_walk(Geo & g, const float p[3], const float dir[3], float len, int mask, RayHit & best)
|
||||
{
|
||||
if (++g.rayId == 0) {
|
||||
std::fill(g.stamp.begin(), g.stamp.end(), 0);
|
||||
g.rayId = 1;
|
||||
}
|
||||
const bool terrain = (mask & RAY_TERRAIN) != 0;
|
||||
const int objects = mask & ~RAY_TERRAIN;
|
||||
const float gx = (p[0] - g.gridOrigin[0]) / CELL_M;
|
||||
const float gz = (p[2] - g.gridOrigin[1]) / CELL_M;
|
||||
int c = int(std::floor(gx));
|
||||
int r = int(std::floor(gz));
|
||||
const int stepC = dir[0] > 0.0f ? 1 : -1;
|
||||
const int stepR = dir[2] > 0.0f ? 1 : -1;
|
||||
const float big = 1.0e30f;
|
||||
const float dtC = std::fabs(dir[0]) > 1.0e-7f ? CELL_M / std::fabs(dir[0]) : big;
|
||||
const float dtR = std::fabs(dir[2]) > 1.0e-7f ? CELL_M / std::fabs(dir[2]) : big;
|
||||
float nextC = std::fabs(dir[0]) > 1.0e-7f ? ((stepC > 0 ? float(c + 1) - gx : gx - float(c)) * dtC) : big;
|
||||
float nextR = std::fabs(dir[2]) > 1.0e-7f ? ((stepR > 0 ? float(r + 1) - gz : gz - float(r)) * dtR) : big;
|
||||
float t0 = 0.0f;
|
||||
while (t0 <= len) {
|
||||
const float t1 = std::min(len, std::min(nextC, nextR));
|
||||
const bool inside = c >= 0 && r >= 0 && c < g.gridCols && r < g.gridRows;
|
||||
const size_t cell = inside ? size_t(r) * g.gridCols + c : 0;
|
||||
const float lowY = std::min(p[1] + dir[1] * t0, p[1] + dir[1] * t1);
|
||||
if (objects != 0 && inside && lowY <= g.cellTop[cell])
|
||||
test_cell(g, cell, p, dir, len, objects, best);
|
||||
const float groundEnd = best.dist >= 0.0f ? std::min(t1, best.dist) : t1;
|
||||
if (terrain && (!inside || lowY <= g.cellGround[cell]) && terrain_in(g, p, dir, t0, groundEnd, best))
|
||||
return;
|
||||
if (best.dist >= 0.0f && best.dist <= t1)
|
||||
return;
|
||||
if (t1 >= len)
|
||||
return;
|
||||
if (nextC < nextR) {
|
||||
c += stepC;
|
||||
t0 = nextC;
|
||||
nextC += dtC;
|
||||
} else {
|
||||
r += stepR;
|
||||
t0 = nextR;
|
||||
nextR += dtR;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
bool geo_load(const std::string & path, std::string & error)
|
||||
{
|
||||
Geo g;
|
||||
std::ifstream in(path, std::ios::binary);
|
||||
GeoHeader h;
|
||||
if (!in || !read_bytes(in, &h, sizeof(h))) {
|
||||
error = "cannot read " + path;
|
||||
return false;
|
||||
}
|
||||
if (std::memcmp(h.magic, GEO_MAGIC, sizeof(GEO_MAGIC)) != 0 || h.version < 1 || h.version > GEO_MAX_VERSION) {
|
||||
error = "not a .wtogeo file of a known version";
|
||||
return false;
|
||||
}
|
||||
g.water = h.waterLevel;
|
||||
g.hmW = h.hmWidth;
|
||||
g.hmH = h.hmHeight;
|
||||
g.hmCell = h.hmCellSize > 0.0f ? h.hmCellSize : 1.0f;
|
||||
g.hmOrigin[0] = h.hmOrigin[0];
|
||||
g.hmOrigin[1] = h.hmOrigin[1];
|
||||
g.heights.resize(size_t(h.hmWidth) * h.hmHeight);
|
||||
std::vector<float> verts(size_t(h.obsVertCount) * 3);
|
||||
std::vector<uint8_t> raw(size_t(h.obsTriCount) * 13);
|
||||
if (!read_bytes(in, g.heights.data(), g.heights.size() * sizeof(float)) ||
|
||||
!read_bytes(in, verts.data(), verts.size() * sizeof(float)) || !read_bytes(in, raw.data(), raw.size())) {
|
||||
error = "file is truncated";
|
||||
return false;
|
||||
}
|
||||
keep_triangles(g, verts, raw, h.obsTriCount);
|
||||
build_grid(g, h.boundsMin, h.boundsMax);
|
||||
build_ground_tops(g);
|
||||
g.loaded = true;
|
||||
g_geo = std::move(g);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool geo_loaded()
|
||||
{
|
||||
return g_geo.loaded;
|
||||
}
|
||||
|
||||
float geo_height(float x, float z)
|
||||
{
|
||||
return height_at(g_geo, x, z);
|
||||
}
|
||||
|
||||
float geo_water_level()
|
||||
{
|
||||
return g_geo.water;
|
||||
}
|
||||
|
||||
RayHit geo_ray(const float p[3], const float dir[3], float len, int mask)
|
||||
{
|
||||
RayHit best;
|
||||
if (!g_geo.loaded || !(len > 0.0f))
|
||||
return best;
|
||||
ray_walk(g_geo, p, dir, len, mask, best);
|
||||
return best;
|
||||
}
|
||||
|
||||
uint32_t geo_triangle_count()
|
||||
{
|
||||
return uint32_t(g_geo.tris.size());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
// The simulator's world geometry: the level's terrain heightmap and the collision triangles of its
|
||||
// placed objects, read from the navigation extractor's `.wtogeo` (native/wto-nav/wto_nav_format.h),
|
||||
// which is also what the AI lab's 3D view draws. Rays answer the AI script's line of sight, ground
|
||||
// and obstacle probes in place of the engine's traces.
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
#include <string>
|
||||
|
||||
namespace wto_sim {
|
||||
|
||||
// Ray masks: terrain plus groups of WtoObstacleClass.
|
||||
enum RayMask : int {
|
||||
RAY_TERRAIN = 1,
|
||||
RAY_HARD = 2, // buildings, rocks, walls (hard solid and hard without cover)
|
||||
RAY_BRIDGE = 4, // bridge decks
|
||||
RAY_CRUSHABLE = 8, // fences, bushes, light objects a tank drives through
|
||||
RAY_TREE = 16, // tree trunks
|
||||
RAY_PLATFORM = 32, // walkable tops of placed objects
|
||||
RAY_ALL = 63,
|
||||
};
|
||||
|
||||
// What a ray hit: -1 nothing, 0 terrain, otherwise the RayMask bit of the object group.
|
||||
struct RayHit {
|
||||
float dist = -1.0f;
|
||||
int kind = -1;
|
||||
float normal[3] = { 0.0f, 1.0f, 0.0f };
|
||||
};
|
||||
|
||||
// Loads the geometry; on failure returns false and `error` says why. Replaces what was loaded.
|
||||
bool geo_load(const std::string & path, std::string & error);
|
||||
bool geo_loaded();
|
||||
// Bilinear terrain height (clamped to the heightmap); 0 when nothing is loaded.
|
||||
float geo_height(float x, float z);
|
||||
// The level's water level, or -1e6 when it has none.
|
||||
float geo_water_level();
|
||||
// First hit of the ray p + dir * t for t in [0, len], against what `mask` selects. `dir` is unit.
|
||||
RayHit geo_ray(const float p[3], const float dir[3], float len, int mask);
|
||||
// Triangles kept after dropping buried faces, and grid cells, for the load log.
|
||||
uint32_t geo_triangle_count();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// "wtoNav" requests in the simulator (see sim_nav.h). The script's DataBlock arrives as text
|
||||
// lines; queries go through the shared protocol, the pack ops are answered here: the simulated
|
||||
// battle's pack is set by the host, so there is no prefetch and no fingerprint check.
|
||||
#include "sim_nav.h"
|
||||
|
||||
#include "wto_nav_protocol.h"
|
||||
#include "wto_nav_runtime.h"
|
||||
|
||||
#include <cstdio>
|
||||
#include <map>
|
||||
#include <vector>
|
||||
|
||||
#ifndef WIN32_LEAN_AND_MEAN
|
||||
#define WIN32_LEAN_AND_MEAN
|
||||
#endif
|
||||
#include <windows.h>
|
||||
|
||||
namespace wto_sim {
|
||||
|
||||
namespace {
|
||||
|
||||
struct Block {
|
||||
std::map<std::string, std::string> values;
|
||||
std::vector<std::pair<std::string, std::string>> reply;
|
||||
};
|
||||
|
||||
std::string g_pack;
|
||||
std::string g_level;
|
||||
|
||||
const char * block_get(const void * blk, const char * name)
|
||||
{
|
||||
const Block * b = static_cast<const Block *>(blk);
|
||||
const auto it = b->values.find(name);
|
||||
return it == b->values.end() ? "" : it->second.c_str();
|
||||
}
|
||||
|
||||
void block_set(Block * b, const char * name, const std::string & value)
|
||||
{
|
||||
b->values[name] = value;
|
||||
b->reply.emplace_back(name, value);
|
||||
}
|
||||
|
||||
void block_set_str(void * blk, const char * name, const char * value)
|
||||
{
|
||||
block_set(static_cast<Block *>(blk), name, value ? value : "");
|
||||
}
|
||||
|
||||
void block_set_int(void * blk, const char * name, int32_t value)
|
||||
{
|
||||
block_set(static_cast<Block *>(blk), name, std::to_string(value));
|
||||
}
|
||||
|
||||
void parse(const std::string & text, Block & b)
|
||||
{
|
||||
size_t at = 0;
|
||||
while (at < text.size()) {
|
||||
size_t end = text.find('\n', at);
|
||||
if (end == std::string::npos)
|
||||
end = text.size();
|
||||
const size_t eq = text.find('=', at);
|
||||
if (eq != std::string::npos && eq < end)
|
||||
b.values[text.substr(at, eq - at)] = text.substr(eq + 1, end - eq - 1);
|
||||
at = end + 1;
|
||||
}
|
||||
}
|
||||
|
||||
std::wstring widen(const std::string & s)
|
||||
{
|
||||
if (s.empty())
|
||||
return std::wstring();
|
||||
const int n = MultiByteToWideChar(CP_UTF8, 0, s.c_str(), int(s.size()), nullptr, 0);
|
||||
std::wstring out(size_t(n), L'\0');
|
||||
MultiByteToWideChar(CP_UTF8, 0, s.c_str(), int(s.size()), out.data(), n);
|
||||
return out;
|
||||
}
|
||||
|
||||
void load_map(const WtoNavBlock & nb, Block & b)
|
||||
{
|
||||
WtoNavLoadInfo info = {};
|
||||
std::string reason;
|
||||
if (g_pack.empty()) {
|
||||
reason = "no pack set for the simulated level";
|
||||
} else {
|
||||
wto_nav_protocol_setup(&nb);
|
||||
wto_nav_load(widen(g_pack).c_str(), nullptr, &info);
|
||||
if (info.result != WTO_NAV_LOAD_OK)
|
||||
reason = info.detail;
|
||||
}
|
||||
const bool ok = reason.empty();
|
||||
const bool fallback = std::string(block_get(&b, "allowFallback")) != "0";
|
||||
block_set(&b, "state", ok ? "loaded" : fallback ? "fallback" : "failed");
|
||||
block_set(&b, "fingerprint", "unknown");
|
||||
block_set(&b, "level", g_level);
|
||||
block_set(&b, "reason", reason);
|
||||
block_set_int(&b, "tiers", ok ? int32_t(info.tiers) : 0);
|
||||
block_set_int(&b, "covers", ok ? int32_t(info.covers) : 0);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
void nav_set_pack(const std::string & packPath, const std::string & level)
|
||||
{
|
||||
g_pack = packPath;
|
||||
g_level = level;
|
||||
}
|
||||
|
||||
std::string nav_request(const std::string & request)
|
||||
{
|
||||
Block b;
|
||||
parse(request, b);
|
||||
WtoNavBlock nb;
|
||||
nb.blk = &b;
|
||||
nb.get_str = block_get;
|
||||
nb.set_str = block_set_str;
|
||||
nb.set_int = block_set_int;
|
||||
const std::string op = block_get(&b, "op");
|
||||
if (!wto_nav_protocol_query(&nb, op.c_str())) {
|
||||
if (op == "load_map") {
|
||||
load_map(nb, b);
|
||||
} else if (op == "prefetch") {
|
||||
block_set(&b, "state", "skipped");
|
||||
block_set(&b, "level", g_level);
|
||||
block_set(&b, "reason", "the simulator loads on load_map");
|
||||
} else if (op == "unload_map") {
|
||||
wto_nav_unload();
|
||||
block_set_int(&b, "ok", 1);
|
||||
} else {
|
||||
std::fprintf(stderr, "WTO_NAV|BAD_REQUEST|op=%s\n", op.c_str());
|
||||
}
|
||||
}
|
||||
std::string out;
|
||||
for (const auto & kv : b.reply)
|
||||
out += kv.first + "=" + kv.second + "\n";
|
||||
return out;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// The simulator's side of the AI script's "wtoNav" requests: the same navigation engine and
|
||||
// request protocol as the game (native/wto-nav), fed from the simulated level's pack.
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace wto_sim {
|
||||
|
||||
// The pack load_map will read; the level name is reported back to the script.
|
||||
void nav_set_pack(const std::string & packPath, const std::string & level);
|
||||
|
||||
// Answers one request. Both are "key=value" lines; the reply holds only the values written back.
|
||||
std::string nav_request(const std::string & request);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
// daScript module `wto_sim`: what the ground AI simulator's scripts need from native code, the
|
||||
// level geometry (rays, ground height, water) and the navigation engine behind "wtoNav" requests.
|
||||
// The engine stand-ins of the simulator (Dacoll, RendInst, Mission...) are scripts built on it.
|
||||
#include "daScript/misc/platform.h"
|
||||
|
||||
#include "daScript/ast/ast.h"
|
||||
#include "daScript/ast/ast_interop.h"
|
||||
#include "daScript/ast/ast_handle.h"
|
||||
|
||||
#include "sim_geo.h"
|
||||
#include "sim_nav.h"
|
||||
|
||||
#include <cstdio>
|
||||
|
||||
namespace das {
|
||||
|
||||
// Loads the level geometry; prints why when it fails.
|
||||
static bool wto_sim_geo_load(const char * path)
|
||||
{
|
||||
std::string error;
|
||||
if (wto_sim::geo_load(path ? path : "", error)) {
|
||||
std::printf("WTO_SIM|GEO_LOADED|path=%s|tris=%u\n", path, wto_sim::geo_triangle_count());
|
||||
return true;
|
||||
}
|
||||
std::printf("WTO_SIM|GEO_FAILED|path=%s|reason=%s\n", path ? path : "", error.c_str());
|
||||
return false;
|
||||
}
|
||||
|
||||
static float wto_sim_geo_height(float x, float z)
|
||||
{
|
||||
return wto_sim::geo_height(x, z);
|
||||
}
|
||||
|
||||
static float wto_sim_geo_water()
|
||||
{
|
||||
return wto_sim::geo_water_level();
|
||||
}
|
||||
|
||||
// Distance to the first hit of the ray, or -1; `kind` is 0 for terrain, else the object group.
|
||||
static float wto_sim_geo_ray(float3 p, float3 dir, float len, int32_t mask, int32_t & kind, float3 & normal)
|
||||
{
|
||||
const float pa[3] = { p.x, p.y, p.z };
|
||||
const float da[3] = { dir.x, dir.y, dir.z };
|
||||
const wto_sim::RayHit hit = wto_sim::geo_ray(pa, da, len, mask);
|
||||
kind = hit.kind;
|
||||
normal = float3(hit.normal[0], hit.normal[1], hit.normal[2]);
|
||||
return hit.dist;
|
||||
}
|
||||
|
||||
static void wto_sim_nav_set_pack(const char * packPath, const char * level)
|
||||
{
|
||||
wto_sim::nav_set_pack(packPath ? packPath : "", level ? level : "");
|
||||
}
|
||||
|
||||
static char * wto_sim_nav_request(const char * request, Context * context, LineInfoArg * at)
|
||||
{
|
||||
const std::string reply = wto_sim::nav_request(request ? request : "");
|
||||
return context->allocateString(reply, at);
|
||||
}
|
||||
|
||||
class Module_WtoSim : public Module {
|
||||
public:
|
||||
Module_WtoSim() : Module("wto_sim") {
|
||||
ModuleLibrary lib;
|
||||
lib.addModule(this);
|
||||
lib.addBuiltInModule();
|
||||
addConstant(*this, "WTO_SIM_RAY_TERRAIN", int32_t(wto_sim::RAY_TERRAIN));
|
||||
addConstant(*this, "WTO_SIM_RAY_HARD", int32_t(wto_sim::RAY_HARD));
|
||||
addConstant(*this, "WTO_SIM_RAY_BRIDGE", int32_t(wto_sim::RAY_BRIDGE));
|
||||
addConstant(*this, "WTO_SIM_RAY_CRUSHABLE", int32_t(wto_sim::RAY_CRUSHABLE));
|
||||
addConstant(*this, "WTO_SIM_RAY_TREE", int32_t(wto_sim::RAY_TREE));
|
||||
addConstant(*this, "WTO_SIM_RAY_PLATFORM", int32_t(wto_sim::RAY_PLATFORM));
|
||||
addConstant(*this, "WTO_SIM_RAY_ALL", int32_t(wto_sim::RAY_ALL));
|
||||
addExtern<DAS_BIND_FUN(wto_sim_geo_load)>(*this, lib, "wto_sim_geo_load",
|
||||
SideEffects::modifyExternal, "wto_sim_geo_load")->args({"path"});
|
||||
addExtern<DAS_BIND_FUN(wto_sim_geo_height)>(*this, lib, "wto_sim_geo_height",
|
||||
SideEffects::accessExternal, "wto_sim_geo_height")->args({"x", "z"});
|
||||
addExtern<DAS_BIND_FUN(wto_sim_geo_water)>(*this, lib, "wto_sim_geo_water",
|
||||
SideEffects::accessExternal, "wto_sim_geo_water");
|
||||
addExtern<DAS_BIND_FUN(wto_sim_geo_ray)>(*this, lib, "wto_sim_geo_ray",
|
||||
SideEffects::modifyArgumentAndExternal, "wto_sim_geo_ray")
|
||||
->args({"p", "dir", "len", "mask", "kind", "normal"});
|
||||
addExtern<DAS_BIND_FUN(wto_sim_nav_set_pack)>(*this, lib, "wto_sim_nav_set_pack",
|
||||
SideEffects::modifyExternal, "wto_sim_nav_set_pack")->args({"pack", "level"});
|
||||
addExtern<DAS_BIND_FUN(wto_sim_nav_request)>(*this, lib, "wto_sim_nav_request",
|
||||
SideEffects::modifyExternal, "wto_sim_nav_request")->args({"request", "context", "at"});
|
||||
}
|
||||
};
|
||||
|
||||
REGISTER_DYN_MODULE(Module_WtoSim, Module_WtoSim);
|
||||
}
|
||||
|
||||
REGISTER_MODULE_IN_NAMESPACE(Module_WtoSim, das);
|
||||
@@ -0,0 +1,165 @@
|
||||
/*
|
||||
* Shared binary format definitions for WTOffline ground AI navigation data:
|
||||
* - `.wtogeo`: offline intermediate geometry dump (extractor -> Recast baker)
|
||||
* - `.wtonav`: runtime navigation pack (baked Detour meshes + covers + tactical grid)
|
||||
*
|
||||
* All coordinates are in Dagor world space (left-handed, Y up, metres).
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define WTO_GEO_MAGIC "WTOGEO\0\1"
|
||||
#define WTO_GEO_VERSION 3u
|
||||
#define WTO_GEO_FLAG_ROAD_MASK 0x01u
|
||||
#define WTO_GEO_FLAG_DOWNHILL_LINKS 0x02u
|
||||
|
||||
#define WTO_NAV_MAGIC "WTONAV\0\1"
|
||||
#define WTO_NAV_VERSION 1u
|
||||
|
||||
#define WTO_NAV_TIER_COUNT 3u
|
||||
#define WTO_NAV_TIER_NARROW 0u /* Tracked width <= 2.9 m (agentRadius 1.65 m) */
|
||||
#define WTO_NAV_TIER_STANDARD 1u /* Tracked width <= 3.6 m (agentRadius 2.05 m) */
|
||||
#define WTO_NAV_TIER_WIDE 2u /* Wide/heavy tracked > 3.6 m (agentRadius 2.45 m) */
|
||||
|
||||
/* Detour polygon Area IDs (0 = RC_NULL_AREA / unwalkable). */
|
||||
enum WtoPolyArea {
|
||||
WTO_AREA_UNWALKABLE = 0,
|
||||
WTO_AREA_ROAD = 1,
|
||||
WTO_AREA_BRIDGE = 2,
|
||||
WTO_AREA_GROUND = 3,
|
||||
WTO_AREA_ROUGH = 4,
|
||||
WTO_AREA_FOREST = 5,
|
||||
WTO_AREA_CRUSHABLE = 6,
|
||||
WTO_AREA_SHALLOW_WATER = 7,
|
||||
WTO_AREA_CHOKEPOINT = 8, /* Not baked: chokepoints keep their surface area, see WTO_FLAG_CHOKEPOINT */
|
||||
WTO_AREA_EXPOSED = 9,
|
||||
WTO_AREA_DEEP_WATER = 10,
|
||||
WTO_AREA_NO_GO = 11
|
||||
};
|
||||
|
||||
/* Detour polygon flags for runtime dtQueryFilter filtering. */
|
||||
enum WtoPolyFlag {
|
||||
WTO_FLAG_WALK = 0x01,
|
||||
WTO_FLAG_SHALLOW_WATER = 0x02,
|
||||
WTO_FLAG_DEEP_WATER = 0x04,
|
||||
WTO_FLAG_CHOKEPOINT = 0x08, /* Narrower than navBake.chokepointMaxWidthVehicles for this mesh's tier */
|
||||
WTO_FLAG_BLOCKED = 0x10,
|
||||
WTO_FLAG_ROAD = 0x20, /* Surface identity, set on road polygons */
|
||||
WTO_FLAG_DOWNHILL = 0x40, /* One-way Detour connection */
|
||||
WTO_FLAG_PLATFORM = 0x80 /* Walkable top of a validated placed object */
|
||||
};
|
||||
|
||||
/* Obstacle classification written into `.wtogeo` by the extractor. */
|
||||
enum WtoObstacleClass {
|
||||
WTO_OBS_HARD_SOLID = 0, /* Buildings, rocks, cliffs, bunkers, concrete walls */
|
||||
WTO_OBS_BRIDGE_DECK = 1, /* Walkable bridge decks and ramps */
|
||||
WTO_OBS_CRUSHABLE = 2, /* Wooden fences, hedges, low-HP destructibles */
|
||||
WTO_OBS_TREE_THICK = 3, /* Thick immovable tree trunks (r >= 0.25 m) */
|
||||
WTO_OBS_TREE_THIN = 4, /* Thin tree trunks / saplings (high-cost forest) */
|
||||
WTO_OBS_HARD_NO_COVER = 5, /* Vehicle collision with no eligible cover surface */
|
||||
WTO_OBS_PLATFORM = 6, /* Placed geometry with eligible upward-facing support surfaces */
|
||||
WTO_OBS_PLATFORM_NO_COVER = 7 /* Support surfaces from vehicle-only collision */
|
||||
};
|
||||
|
||||
/* Baked tank cover classifications. */
|
||||
enum WtoCoverKind {
|
||||
WTO_COVER_FULL = 1, /* Blocks hull + turret (reload, repair, corner peek) */
|
||||
WTO_COVER_HULLDOWN = 2 /* Blocks hull, turret clear with forward firing arc */
|
||||
};
|
||||
|
||||
#pragma pack(push, 1)
|
||||
|
||||
/* Intermediate geometry bundle header (`.wtogeo`). */
|
||||
typedef struct WtoGeoHeader {
|
||||
char magic[8]; /* WTO_GEO_MAGIC */
|
||||
uint32_t version; /* WTO_GEO_VERSION */
|
||||
uint32_t flags; /* WTO_GEO_FLAG_* */
|
||||
uint8_t everSha1[20]; /* Built-in SHA-1 from DBLD eVER block */
|
||||
float waterLevel; /* Level water_level in metres (-1e6 if none) */
|
||||
float boundsMin[2]; /* World XZ crop min (battle area union + margin) */
|
||||
float boundsMax[2]; /* World XZ crop max */
|
||||
uint32_t hmWidth; /* Cropped heightmap grid columns (X) */
|
||||
uint32_t hmHeight; /* Cropped heightmap grid rows (Z) */
|
||||
float hmCellSize; /* Metres per heightmap sample */
|
||||
float hmOrigin[2]; /* World XZ of cropped sample (0, 0) */
|
||||
uint32_t obsVertCount; /* Number of float3 obstacle vertices */
|
||||
uint32_t obsTriCount; /* Number of obstacle triangles (uint32[3] + uint8 class) */
|
||||
} WtoGeoHeader;
|
||||
|
||||
/* Optional trailer after obstacle triangles, followed by size*size uint8 road mask cells. */
|
||||
typedef struct WtoGeoRoadMask {
|
||||
uint32_t size;
|
||||
float origin[2]; /* World XZ of the first LMp2 cell */
|
||||
float cellSize;
|
||||
} WtoGeoRoadMask;
|
||||
|
||||
/* Optional downhill links trailer: uint32_t count followed by records. */
|
||||
typedef struct WtoGeoDownhillLink {
|
||||
float endpoints[6]; /* From XYZ (high) followed by to XYZ (low) */
|
||||
float radiusM; /* Detour endpoint attachment radius */
|
||||
uint32_t tierMask;
|
||||
} WtoGeoDownhillLink;
|
||||
|
||||
/* Baked tank cover point (68 bytes). */
|
||||
typedef struct WtoCoverPoint {
|
||||
float pos[3]; /* World XYZ parking position behind cover */
|
||||
float coverDir[2]; /* Unit XZ vector pointing FROM pos TOWARD the blocked threat */
|
||||
float retreatDir[2]; /* Unit XZ safe reverse/retreat direction away from cover */
|
||||
float peekLeft[3]; /* World XYZ left corner peek spot (valid if hasPeekLeft) */
|
||||
float peekRight[3]; /* World XYZ right corner peek spot (valid if hasPeekRight) */
|
||||
float halfAngleDeg; /* Effective covered half-angle around coverDir */
|
||||
float heightM; /* Continuous cover height above the final parking point */
|
||||
float widthM; /* Continuous hard-obstacle width */
|
||||
uint8_t kind; /* WtoCoverKind */
|
||||
uint8_t hasPeekLeft; /* 1 if peekLeft is valid and navigable */
|
||||
uint8_t hasPeekRight; /* 1 if peekRight is valid and navigable */
|
||||
uint8_t reserved;
|
||||
} WtoCoverPoint;
|
||||
|
||||
/* Low-resolution (8 m) tactical grid cell (4 bytes). */
|
||||
typedef struct WtoTacticalCell {
|
||||
uint8_t exposure; /* 0..255: static visibility exposure from enemy side */
|
||||
uint8_t clearanceHalfM; /* Distance to nearest hard obstacle in 0.5 m units (0..127.5 m) */
|
||||
uint8_t corridorTeam1; /* 0..255: Team 1 replay prior (128 = neutral) */
|
||||
uint8_t corridorTeam2; /* 0..255: Team 2 replay prior (128 = neutral) */
|
||||
} WtoTacticalCell;
|
||||
|
||||
/* Runtime navigation pack header (`.wtonav`, uncompressed payload header). */
|
||||
typedef struct WtoNavHeader {
|
||||
char magic[8]; /* WTO_NAV_MAGIC */
|
||||
uint32_t version; /* WTO_NAV_VERSION */
|
||||
uint32_t flags;
|
||||
uint8_t everSha1[20]; /* Source level eVER SHA-1 fingerprint */
|
||||
float bmin[3]; /* World AABB min */
|
||||
float bmax[3]; /* World AABB max */
|
||||
float waterLevel;
|
||||
uint32_t tierCount; /* WTO_NAV_TIER_COUNT (3) */
|
||||
uint32_t tierOffsets[WTO_NAV_TIER_COUNT];
|
||||
uint32_t tierSizes[WTO_NAV_TIER_COUNT];
|
||||
uint32_t coverOffset;
|
||||
uint32_t coverCount;
|
||||
uint32_t tacOffset;
|
||||
uint32_t tacCols;
|
||||
uint32_t tacRows;
|
||||
float tacCellM;
|
||||
float tacOrigin[2];
|
||||
} WtoNavHeader;
|
||||
|
||||
/* Per-tier Detour blob layout at tierOffsets[t]:
|
||||
* dtNavMeshParams (exact upstream struct)
|
||||
* uint32_t tileCount
|
||||
* repeated tileCount times:
|
||||
* uint32_t tileDataSize
|
||||
* uint8_t tileData[tileDataSize]
|
||||
*/
|
||||
|
||||
#pragma pack(pop)
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,95 @@
|
||||
/*
|
||||
* State shared by the navigation engine's translation units (wto_nav_runtime.cpp: packs and
|
||||
* loading; wto_nav_paths.cpp: queued sliced path searches; wto_nav_queries.cpp: point queries and
|
||||
* dynamic costs). Everything below is guarded by g_lock unless noted.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include "wto_nav_runtime.h"
|
||||
#include "wto_nav_format.h"
|
||||
|
||||
#include "DetourCommon.h"
|
||||
#include "DetourNavMesh.h"
|
||||
#include "DetourNavMeshQuery.h"
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#include <vector>
|
||||
|
||||
#ifndef DT_VIRTUAL_QUERYFILTER
|
||||
#error "Detour must be built with DT_VIRTUAL_QUERYFILTER for the chokepoint and dynamic cost filter"
|
||||
#endif
|
||||
|
||||
namespace wtonav {
|
||||
|
||||
constexpr int kPathSearchNodes = 32768; /* Node pool of the sliced path search, per tier */
|
||||
constexpr int kPointSearchNodes = 2048; /* Node pool of point queries (wall distance) */
|
||||
constexpr int kMaxPathPolys = 4096;
|
||||
|
||||
/* A circle that multiplies the cost of every edge whose midpoint lies inside it. */
|
||||
struct DynamicCost {
|
||||
float pos[3];
|
||||
float radius;
|
||||
float mul;
|
||||
float until;
|
||||
};
|
||||
|
||||
extern DynamicCost g_dynamic[WTO_NAV_RT_MAX_DYNAMIC];
|
||||
extern uint32_t g_dynamic_count;
|
||||
|
||||
/* Area costs per WtoPolyArea, times the chokepoint multiplier, live dynamic costs and the
|
||||
* traffic of the searching path's group. */
|
||||
class QueryFilter : public dtQueryFilter {
|
||||
public:
|
||||
float chokepointMul = 1.0f;
|
||||
|
||||
float getCost(const float *pa, const float *pb,
|
||||
const dtPolyRef, const dtMeshTile *, const dtPoly *,
|
||||
const dtPolyRef curRef, const dtMeshTile *, const dtPoly *curPoly,
|
||||
const dtPolyRef, const dtMeshTile *, const dtPoly *) const override;
|
||||
};
|
||||
|
||||
struct Pack {
|
||||
float heightSpan = 0.0f; /* Vertical extent of the mesh bounds */
|
||||
dtNavMesh *meshes[WTO_NAV_TIER_COUNT] = {};
|
||||
dtNavMeshQuery *pathQueries[WTO_NAV_TIER_COUNT] = {}; /* Owned by the sliced path search */
|
||||
dtNavMeshQuery *pointQueries[WTO_NAV_TIER_COUNT] = {}; /* Snapping, raycasts, wall distance */
|
||||
std::vector<WtoCoverPoint> covers;
|
||||
std::vector<WtoTacticalCell> tactical;
|
||||
/* First flat polygon index of every tile slot, and per traffic group how many counted paths
|
||||
* cross each polygon (indexed by tileBase[tile] + polygon). */
|
||||
std::vector<uint32_t> tileBase[WTO_NAV_TIER_COUNT];
|
||||
std::vector<uint16_t> traffic[WTO_NAV_TIER_COUNT][WTO_NAV_RT_TRAFFIC_GROUPS];
|
||||
};
|
||||
|
||||
extern SRWLOCK g_lock;
|
||||
extern Pack *g_pack;
|
||||
extern QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT];
|
||||
extern WtoNavStats g_stats;
|
||||
extern WtoNavTuning g_tuning;
|
||||
|
||||
/* Tier and traffic group (0-based, -1 none) of the search being advanced; read by getCost. */
|
||||
extern int g_cost_tier;
|
||||
extern int g_cost_group;
|
||||
|
||||
double now_micros();
|
||||
|
||||
/* Flat polygon index for Pack::traffic, or -1. */
|
||||
int poly_index(const Pack &pack, uint32_t tier, dtPolyRef ref);
|
||||
|
||||
/*
|
||||
* Nearest polygon within `snap` metres; mission points (spawn and capture zone centres) carry
|
||||
* heights that are not on the ground, so a miss is retried over the mesh's whole height range,
|
||||
* still within `snap` horizontally.
|
||||
*/
|
||||
bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span,
|
||||
const float point[3], dtPolyRef *ref, float nearest[3]);
|
||||
|
||||
/* Called with g_lock held whenever the loaded pack changes. */
|
||||
void paths_reset_locked();
|
||||
void dynamic_reset_locked();
|
||||
void dynamic_expire_locked(float now);
|
||||
uint32_t paths_pending_locked();
|
||||
uint32_t traffic_paths_locked();
|
||||
|
||||
} // namespace wtonav
|
||||
@@ -0,0 +1,402 @@
|
||||
/*
|
||||
* Queued path searches (wto_nav_runtime.h): every slot holds at most one request. Requests are
|
||||
* searched one at a time, oldest first, with Detour's sliced search; wto_nav_pump advances the
|
||||
* search in small iteration chunks until its per-frame time budget is spent, so one long path
|
||||
* across a 4 km map spreads over several frames instead of stalling one.
|
||||
*
|
||||
* Paths of a traffic group (a team) are remembered per slot for trafficHoldSec: their polygons
|
||||
* cost more for the group's later searches, so a team spreads over parallel routes instead of
|
||||
* queueing on one road. Finished corners are pulled away from the edges they turn around, so a
|
||||
* vehicle cutting a corner does not clip the building the mesh was eroded from.
|
||||
*/
|
||||
#include "wto_nav_internal.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace wtonav {
|
||||
namespace {
|
||||
|
||||
constexpr int kIterChunk = 64; /* Detour node expansions between budget checks */
|
||||
constexpr float kStraightCos = 0.985f; /* Corners turning less than ~10 degrees stay put */
|
||||
constexpr int kCornerRayPolys = 256;
|
||||
|
||||
enum class JobState : uint8_t { Empty, Queued, Running, Done };
|
||||
|
||||
struct PathJob {
|
||||
uint32_t ticket;
|
||||
JobState state;
|
||||
uint32_t tier;
|
||||
uint32_t filter;
|
||||
int group; /* 0-based traffic group, -1 none */
|
||||
dtPolyRef startRef;
|
||||
dtPolyRef goalRef;
|
||||
float startPt[3];
|
||||
float goalPt[3];
|
||||
double searchMicros;
|
||||
uint32_t frames;
|
||||
uint32_t lastPump;
|
||||
WtoNavPathResult result;
|
||||
float corners[WTO_NAV_RT_MAX_CORNERS * 3];
|
||||
};
|
||||
|
||||
/* Polygons of a slot's last finished path while they count as its group's traffic. */
|
||||
struct Occupancy {
|
||||
int group = -1;
|
||||
uint32_t tier = 0;
|
||||
float until = 0.0f;
|
||||
std::vector<uint32_t> polys;
|
||||
};
|
||||
|
||||
PathJob g_jobs[WTO_NAV_RT_PATH_SLOTS];
|
||||
Occupancy g_occupancy[WTO_NAV_RT_PATH_SLOTS];
|
||||
uint32_t g_next_ticket = 1;
|
||||
uint32_t g_pump_serial;
|
||||
float g_pump_now;
|
||||
int g_active = -1; /* Slot whose search owns its tier's path query */
|
||||
dtPolyRef g_poly_path[kMaxPathPolys];
|
||||
dtPolyRef g_corner_refs[WTO_NAV_RT_MAX_CORNERS];
|
||||
unsigned char g_corner_flags[WTO_NAV_RT_MAX_CORNERS];
|
||||
dtPolyRef g_ray_polys[kCornerRayPolys];
|
||||
|
||||
void release(Occupancy &occ)
|
||||
{
|
||||
if (occ.group >= 0 && g_pack != nullptr) {
|
||||
std::vector<uint16_t> &counts = g_pack->traffic[occ.tier][occ.group];
|
||||
for (uint32_t at : occ.polys) {
|
||||
if (at < counts.size() && counts[at] != 0)
|
||||
counts[at]--;
|
||||
}
|
||||
}
|
||||
occ.group = -1;
|
||||
occ.polys.clear();
|
||||
}
|
||||
|
||||
void occupy(Occupancy &occ, const PathJob &job, int count)
|
||||
{
|
||||
release(occ);
|
||||
if (job.group < 0 || !(g_tuning.trafficCostPerPath > 0.0f) || !(g_tuning.trafficHoldSec > 0.0f))
|
||||
return;
|
||||
std::vector<uint16_t> &counts = g_pack->traffic[job.tier][job.group];
|
||||
for (int i = 0; i < count; i++) {
|
||||
const int at = poly_index(*g_pack, job.tier, g_poly_path[i]);
|
||||
if (at < 0 || counts[(size_t)at] == UINT16_MAX)
|
||||
continue;
|
||||
counts[(size_t)at]++;
|
||||
occ.polys.push_back((uint32_t)at);
|
||||
}
|
||||
occ.group = job.group;
|
||||
occ.tier = job.tier;
|
||||
occ.until = g_pump_now + g_tuning.trafficHoldSec;
|
||||
}
|
||||
|
||||
void expire_occupancy(float now)
|
||||
{
|
||||
for (Occupancy &occ : g_occupancy) {
|
||||
if (occ.group >= 0 && occ.until < now)
|
||||
release(occ);
|
||||
}
|
||||
}
|
||||
|
||||
void normalize_xz(float v[3])
|
||||
{
|
||||
v[1] = 0.0f;
|
||||
const float len = dtMathSqrtf(v[0] * v[0] + v[2] * v[2]);
|
||||
if (len > 1e-4f) {
|
||||
v[0] /= len;
|
||||
v[2] /= len;
|
||||
} else {
|
||||
v[0] = v[2] = 0.0f;
|
||||
}
|
||||
}
|
||||
|
||||
/* Whether the mesh lets a vehicle go straight from `from` (on `ref`) to `to`; `end` gets the
|
||||
* polygon reached. */
|
||||
bool open_line(const dtNavMeshQuery *query, const dtQueryFilter &filter, dtPolyRef ref, const float from[3],
|
||||
const float to[3], dtPolyRef *end)
|
||||
{
|
||||
float t = 0.0f, normal[3];
|
||||
int visited = 0;
|
||||
if (dtStatusFailed(query->raycast(ref, from, to, &filter, &t, normal, g_ray_polys, &visited, kCornerRayPolys)) ||
|
||||
t != FLT_MAX || visited <= 0)
|
||||
return false;
|
||||
if (end != nullptr)
|
||||
*end = g_ray_polys[visited - 1];
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Moves corner i (between corners i-1 and i+1) up to cornerOffsetM away from the edge it turns
|
||||
* around, keeping both legs and the move itself on the mesh. */
|
||||
bool push_corner(const dtNavMeshQuery *query, const dtQueryFilter &filter, float *corners, int i, dtPolyRef prev_ref)
|
||||
{
|
||||
float *c = corners + i * 3;
|
||||
const float *p = c - 3, *n = c + 3;
|
||||
float in[3] = { c[0] - p[0], 0.0f, c[2] - p[2] }, out[3] = { n[0] - c[0], 0.0f, n[2] - c[2] };
|
||||
normalize_xz(in);
|
||||
normalize_xz(out);
|
||||
if (dtVdot2D(in, out) > kStraightCos)
|
||||
return false;
|
||||
float push[3] = { in[0] - out[0], 0.0f, in[2] - out[2] };
|
||||
normalize_xz(push);
|
||||
for (float scale = 1.0f; scale > 0.2f; scale *= 0.5f) {
|
||||
const float step = g_tuning.cornerOffsetM * scale;
|
||||
float moved[3] = { c[0] + push[0] * step, c[1], c[2] + push[2] * step };
|
||||
dtPolyRef moved_ref = 0;
|
||||
if (!open_line(query, filter, g_corner_refs[i], c, moved, &moved_ref) ||
|
||||
!open_line(query, filter, prev_ref, p, moved, nullptr) ||
|
||||
!open_line(query, filter, moved_ref, moved, n, nullptr))
|
||||
continue;
|
||||
float height = 0.0f;
|
||||
if (dtStatusSucceed(query->getPolyHeight(moved_ref, moved, &height)))
|
||||
moved[1] = height;
|
||||
dtVcopy(c, moved);
|
||||
g_corner_refs[i] = moved_ref;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Corners on either end of an off-mesh link (one-way downhill) stay where they are. */
|
||||
void push_corners(const PathJob &job, float *corners, int count)
|
||||
{
|
||||
if (!(g_tuning.cornerOffsetM > 0.0f) || count < 3)
|
||||
return;
|
||||
const dtNavMeshQuery *query = g_pack->pointQueries[job.tier];
|
||||
const QueryFilter &filter = g_filters[job.filter];
|
||||
for (int i = 1; i < count - 1; i++) {
|
||||
const bool linked = (g_corner_flags[i] | g_corner_flags[i - 1]) & DT_STRAIGHTPATH_OFFMESH_CONNECTION;
|
||||
if (!linked && g_corner_refs[i] != 0 && g_corner_refs[i - 1] != 0 &&
|
||||
push_corner(query, filter, corners, i, g_corner_refs[i - 1]))
|
||||
g_stats.cornersMoved++;
|
||||
}
|
||||
}
|
||||
|
||||
void finish(PathJob &job, WtoNavPathStatus status)
|
||||
{
|
||||
job.state = JobState::Done;
|
||||
job.result.status = status;
|
||||
if (g_pack == nullptr)
|
||||
return;
|
||||
g_stats.queries++;
|
||||
if (status != WTO_NAV_PATH_FULL)
|
||||
g_stats.failures++;
|
||||
g_stats.totalMicros += job.searchMicros;
|
||||
if (job.searchMicros > g_stats.maxMicros)
|
||||
g_stats.maxMicros = job.searchMicros;
|
||||
if (job.frames > g_stats.maxFrames)
|
||||
g_stats.maxFrames = job.frames;
|
||||
}
|
||||
|
||||
/* Snaps start and goal; on success the job is queued, otherwise it is finished. */
|
||||
void prepare(PathJob &job, const WtoNavPathRequest &req)
|
||||
{
|
||||
if (g_pack == nullptr || req.tier >= WTO_NAV_TIER_COUNT || req.filter >= WTO_NAV_RT_FILTER_COUNT || !(req.snapM > 0.0f)) {
|
||||
finish(job, WTO_NAV_PATH_FAILED);
|
||||
return;
|
||||
}
|
||||
const dtNavMeshQuery *query = g_pack->pointQueries[req.tier];
|
||||
const QueryFilter &filter = g_filters[req.filter];
|
||||
if (!snap_to_mesh(query, filter, req.snapM, g_pack->heightSpan, req.start, &job.startRef, job.startPt)) {
|
||||
finish(job, WTO_NAV_PATH_NO_START);
|
||||
return;
|
||||
}
|
||||
if (!snap_to_mesh(query, filter, req.snapM, g_pack->heightSpan, req.goal, &job.goalRef, job.goalPt)) {
|
||||
if (!(req.goalSnapM > req.snapM) ||
|
||||
!snap_to_mesh(query, filter, req.goalSnapM, g_pack->heightSpan, req.goal, &job.goalRef, job.goalPt)) {
|
||||
finish(job, WTO_NAV_PATH_NO_GOAL);
|
||||
return;
|
||||
}
|
||||
job.result.goalMoved = 1;
|
||||
}
|
||||
job.state = JobState::Queued;
|
||||
}
|
||||
|
||||
int next_queued()
|
||||
{
|
||||
int best = -1;
|
||||
for (int i = 0; i < WTO_NAV_RT_PATH_SLOTS; i++) {
|
||||
if (g_jobs[i].state == JobState::Queued && (best < 0 || g_jobs[i].ticket < g_jobs[best].ticket))
|
||||
best = i;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/* Turns a finished polygon corridor into straight-path corners. */
|
||||
void finalize(PathJob &job, dtNavMeshQuery *query)
|
||||
{
|
||||
int count = 0;
|
||||
dtStatus status = query->finalizeSlicedFindPath(g_poly_path, &count, kMaxPathPolys);
|
||||
if (dtStatusFailed(status) || count == 0) {
|
||||
finish(job, WTO_NAV_PATH_FAILED);
|
||||
return;
|
||||
}
|
||||
const bool partial = dtStatusDetail(status, DT_PARTIAL_RESULT) || g_poly_path[count - 1] != job.goalRef;
|
||||
float goal[3];
|
||||
dtVcopy(goal, job.goalPt);
|
||||
if (partial && dtStatusFailed(query->closestPointOnPoly(g_poly_path[count - 1], job.goalPt, goal, nullptr))) {
|
||||
finish(job, WTO_NAV_PATH_FAILED);
|
||||
return;
|
||||
}
|
||||
int corners = 0;
|
||||
status = query->findStraightPath(job.startPt, goal, g_poly_path, count, job.corners, g_corner_flags, g_corner_refs,
|
||||
&corners, WTO_NAV_RT_MAX_CORNERS, 0);
|
||||
if (dtStatusFailed(status) || corners == 0) {
|
||||
finish(job, WTO_NAV_PATH_FAILED);
|
||||
return;
|
||||
}
|
||||
push_corners(job, job.corners, corners);
|
||||
occupy(g_occupancy[&job - g_jobs], job, count);
|
||||
float length = 0.0f;
|
||||
for (int i = 1; i < corners; i++)
|
||||
length += dtVdist(job.corners + (i - 1) * 3, job.corners + i * 3);
|
||||
job.result.count = corners;
|
||||
job.result.lengthM = length;
|
||||
job.result.truncated = dtStatusDetail(status, DT_BUFFER_TOO_SMALL) ? 1 : 0;
|
||||
finish(job, partial ? WTO_NAV_PATH_PARTIAL : WTO_NAV_PATH_FULL);
|
||||
}
|
||||
|
||||
/* Starts the oldest queued search; false when nothing is left to search. */
|
||||
bool start_next()
|
||||
{
|
||||
for (;;) {
|
||||
const int slot = next_queued();
|
||||
if (slot < 0)
|
||||
return false;
|
||||
PathJob &job = g_jobs[slot];
|
||||
dtNavMeshQuery *query = g_pack->pathQueries[job.tier];
|
||||
if (dtStatusFailed(query->initSlicedFindPath(job.startRef, job.goalRef, job.startPt, job.goalPt,
|
||||
&g_filters[job.filter], 0))) {
|
||||
finish(job, WTO_NAV_PATH_FAILED);
|
||||
continue;
|
||||
}
|
||||
job.state = JobState::Running;
|
||||
g_active = slot;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
/* The pack is already replaced: its traffic counters start at zero, so nothing is released. */
|
||||
void paths_reset_locked()
|
||||
{
|
||||
memset(g_jobs, 0, sizeof(g_jobs));
|
||||
for (Occupancy &occ : g_occupancy) {
|
||||
occ.group = -1;
|
||||
occ.polys.clear();
|
||||
}
|
||||
g_active = -1;
|
||||
}
|
||||
|
||||
uint32_t traffic_paths_locked()
|
||||
{
|
||||
uint32_t paths = 0;
|
||||
for (const Occupancy &occ : g_occupancy)
|
||||
paths += occ.group >= 0;
|
||||
return paths;
|
||||
}
|
||||
|
||||
uint32_t paths_pending_locked()
|
||||
{
|
||||
uint32_t pending = 0;
|
||||
for (const PathJob &job : g_jobs)
|
||||
pending += job.state == JobState::Queued || job.state == JobState::Running;
|
||||
return pending;
|
||||
}
|
||||
|
||||
} // namespace wtonav
|
||||
|
||||
using namespace wtonav;
|
||||
|
||||
extern "C" uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request)
|
||||
{
|
||||
if (slot >= WTO_NAV_RT_PATH_SLOTS || request == nullptr)
|
||||
return 0;
|
||||
AcquireSRWLockExclusive(&g_lock);
|
||||
PathJob &job = g_jobs[slot];
|
||||
if (g_active == (int)slot)
|
||||
g_active = -1; /* The next initSlicedFindPath discards the abandoned search */
|
||||
memset(&job, 0, sizeof(job));
|
||||
release(g_occupancy[slot]); /* A path never counts as traffic against its own replacement */
|
||||
if (g_next_ticket == 0)
|
||||
g_next_ticket = 1;
|
||||
job.ticket = g_next_ticket++;
|
||||
job.tier = request->tier;
|
||||
job.filter = request->filter;
|
||||
job.group = request->group >= 1 && request->group <= WTO_NAV_RT_TRAFFIC_GROUPS ? (int)request->group - 1 : -1;
|
||||
prepare(job, *request);
|
||||
const uint32_t ticket = job.ticket;
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
return ticket;
|
||||
}
|
||||
|
||||
extern "C" void wto_nav_path_result(uint32_t slot, uint32_t ticket, float *points, int max_points, WtoNavPathResult *result)
|
||||
{
|
||||
memset(result, 0, sizeof(*result));
|
||||
result->status = WTO_NAV_PATH_STALE;
|
||||
if (slot >= WTO_NAV_RT_PATH_SLOTS || ticket == 0)
|
||||
return;
|
||||
AcquireSRWLockShared(&g_lock);
|
||||
const PathJob &job = g_jobs[slot];
|
||||
if (job.ticket == ticket) {
|
||||
if (job.state == JobState::Queued || job.state == JobState::Running) {
|
||||
result->status = WTO_NAV_PATH_PENDING;
|
||||
} else if (job.state == JobState::Done) {
|
||||
*result = job.result;
|
||||
if (result->count > max_points)
|
||||
result->count = max_points < 0 ? 0 : max_points;
|
||||
if (points != nullptr && result->count > 0)
|
||||
memcpy(points, job.corners, sizeof(float) * 3 * (size_t)result->count);
|
||||
}
|
||||
}
|
||||
ReleaseSRWLockShared(&g_lock);
|
||||
}
|
||||
|
||||
extern "C" void wto_nav_pump(double budget_us, float now)
|
||||
{
|
||||
AcquireSRWLockExclusive(&g_lock);
|
||||
const double began = now_micros();
|
||||
dynamic_expire_locked(now);
|
||||
g_pump_serial++;
|
||||
g_pump_now = now;
|
||||
expire_occupancy(now);
|
||||
if (g_pack == nullptr) {
|
||||
for (PathJob &job : g_jobs) {
|
||||
if (job.state == JobState::Queued || job.state == JobState::Running)
|
||||
finish(job, WTO_NAV_PATH_FAILED);
|
||||
}
|
||||
g_active = -1;
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
return;
|
||||
}
|
||||
for (;;) {
|
||||
if (g_active < 0 && !start_next())
|
||||
break;
|
||||
PathJob &job = g_jobs[g_active];
|
||||
dtNavMeshQuery *query = g_pack->pathQueries[job.tier];
|
||||
if (job.lastPump != g_pump_serial) {
|
||||
job.lastPump = g_pump_serial;
|
||||
job.frames++;
|
||||
}
|
||||
const double chunk_began = now_micros();
|
||||
int done = 0;
|
||||
g_cost_tier = (int)job.tier;
|
||||
g_cost_group = g_tuning.trafficCostPerPath > 0.0f ? job.group : -1;
|
||||
const dtStatus status = query->updateSlicedFindPath(kIterChunk, &done);
|
||||
g_cost_group = -1;
|
||||
job.searchMicros += now_micros() - chunk_began;
|
||||
if (dtStatusFailed(status)) {
|
||||
finish(job, WTO_NAV_PATH_FAILED);
|
||||
g_active = -1;
|
||||
} else if (!dtStatusInProgress(status)) {
|
||||
finalize(job, query);
|
||||
g_active = -1;
|
||||
}
|
||||
if (now_micros() - began >= budget_us)
|
||||
break;
|
||||
}
|
||||
const double spent = now_micros() - began;
|
||||
if (spent > g_stats.pumpMaxMicros)
|
||||
g_stats.pumpMaxMicros = spent;
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
/* The "wtoNav" request protocol on top of the navigation engine (see wto_nav_protocol.h). */
|
||||
#include "wto_nav_protocol.h"
|
||||
#include "wto_nav_runtime.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
/* Costs in the order of WtoPolyArea; empty names are areas the mesh never carries. */
|
||||
static const char *const AREA_KEYS[WTO_NAV_RT_AREA_COUNT] = {
|
||||
"", "road", "bridge", "ground", "rough", "forest", "crushable", "shallowWater", "", "exposed", "", "",
|
||||
};
|
||||
|
||||
static float get_real(const WtoNavBlock *b, const char *name, float def)
|
||||
{
|
||||
const char *text = b->get_str(b->blk, name);
|
||||
char *end;
|
||||
float value;
|
||||
if (text == NULL || text[0] == '\0')
|
||||
return def;
|
||||
value = strtof(text, &end);
|
||||
return (*end == '\0' && value == value) ? value : def;
|
||||
}
|
||||
|
||||
static long get_long(const WtoNavBlock *b, const char *name, long def)
|
||||
{
|
||||
const char *text = b->get_str(b->blk, name);
|
||||
char *end;
|
||||
long value;
|
||||
if (text == NULL || text[0] == '\0')
|
||||
return def;
|
||||
value = strtol(text, &end, 10);
|
||||
return *end == '\0' ? value : def;
|
||||
}
|
||||
|
||||
/* <prefix>x, <prefix>y, <prefix>z */
|
||||
static void get_vec(const WtoNavBlock *b, char prefix, float out[3])
|
||||
{
|
||||
char key[3];
|
||||
key[0] = prefix;
|
||||
key[1] = 'x';
|
||||
key[2] = '\0';
|
||||
out[0] = get_real(b, key, 0.0f);
|
||||
key[1] = 'y';
|
||||
out[1] = get_real(b, key, 0.0f);
|
||||
key[1] = 'z';
|
||||
out[2] = get_real(b, key, 0.0f);
|
||||
}
|
||||
|
||||
static void set_int(const WtoNavBlock *b, const char *name, int32_t value)
|
||||
{
|
||||
b->set_int(b->blk, name, value);
|
||||
}
|
||||
|
||||
static int32_t to_cm(float metres)
|
||||
{
|
||||
const float cm = metres * 100.0f;
|
||||
if (cm > 2.0e9f)
|
||||
return INT32_MAX;
|
||||
if (cm < -2.0e9f)
|
||||
return INT32_MIN;
|
||||
return (int32_t)(cm >= 0.0f ? cm + 0.5f : cm - 0.5f);
|
||||
}
|
||||
|
||||
static void set_vec_cm(const WtoNavBlock *b, const char *x, const char *y, const char *z, const float v[3])
|
||||
{
|
||||
set_int(b, x, to_cm(v[0]));
|
||||
set_int(b, y, to_cm(v[1]));
|
||||
set_int(b, z, to_cm(v[2]));
|
||||
}
|
||||
|
||||
static void read_costs(const WtoNavBlock *b, const char *prefix, WtoNavCosts *costs)
|
||||
{
|
||||
char key[48];
|
||||
int area;
|
||||
for (area = 0; area < WTO_NAV_RT_AREA_COUNT; area++) {
|
||||
costs->area[area] = 1.0f;
|
||||
if (AREA_KEYS[area][0] == '\0')
|
||||
continue;
|
||||
snprintf(key, sizeof(key), "%s_%s", prefix, AREA_KEYS[area]);
|
||||
costs->area[area] = get_real(b, key, 1.0f);
|
||||
if (!(costs->area[area] > 0.0f))
|
||||
costs->area[area] = 1.0f;
|
||||
}
|
||||
snprintf(key, sizeof(key), "%s_chokepoint", prefix);
|
||||
costs->chokepointMul = get_real(b, key, 1.0f);
|
||||
if (!(costs->chokepointMul > 0.0f))
|
||||
costs->chokepointMul = 1.0f;
|
||||
}
|
||||
|
||||
void wto_nav_protocol_setup(const WtoNavBlock *b)
|
||||
{
|
||||
WtoNavCosts costs;
|
||||
WtoNavTuning tuning;
|
||||
read_costs(b, "t", &costs);
|
||||
wto_nav_set_costs(0, &costs);
|
||||
read_costs(b, "w", &costs);
|
||||
wto_nav_set_costs(1, &costs);
|
||||
tuning.trafficCostPerPath = get_real(b, "trafficPerPath", 0.0f);
|
||||
tuning.trafficCostMaxMul = get_real(b, "trafficMaxMul", 1.0f);
|
||||
tuning.trafficHoldSec = get_real(b, "trafficHoldSec", 0.0f);
|
||||
tuning.cornerOffsetM = get_real(b, "cornerOffset", 0.0f);
|
||||
wto_nav_set_tuning(&tuning);
|
||||
}
|
||||
|
||||
static void path_request(const WtoNavBlock *b)
|
||||
{
|
||||
WtoNavPathRequest req;
|
||||
const long slot = get_long(b, "slot", -1), tier = get_long(b, "tier", -1), filter = get_long(b, "filter", 0);
|
||||
const long group = get_long(b, "group", 0);
|
||||
uint32_t ticket = 0;
|
||||
|
||||
memset(&req, 0, sizeof(req));
|
||||
req.tier = (uint32_t)tier;
|
||||
req.filter = (uint32_t)filter;
|
||||
req.group = group > 0 ? (uint32_t)group : 0u;
|
||||
req.snapM = get_real(b, "snap", 0.0f);
|
||||
req.goalSnapM = get_real(b, "goalSnap", 0.0f);
|
||||
get_vec(b, 's', req.start);
|
||||
get_vec(b, 'g', req.goal);
|
||||
if (slot >= 0 && tier >= 0 && filter >= 0)
|
||||
ticket = wto_nav_path_request((uint32_t)slot, &req);
|
||||
set_int(b, "ticket", (int32_t)ticket);
|
||||
}
|
||||
|
||||
static void path_result(const WtoNavBlock *b)
|
||||
{
|
||||
static const char *const STATUS[] = { "full", "partial", "no_start", "no_goal", "failed", "pending", "stale" };
|
||||
float points[WTO_NAV_RT_MAX_CORNERS * 3];
|
||||
const long slot = get_long(b, "slot", -1), ticket = get_long(b, "ticket", 0);
|
||||
WtoNavPathResult result;
|
||||
int i;
|
||||
|
||||
wto_nav_path_result(slot < 0 ? UINT32_MAX : (uint32_t)slot, ticket <= 0 ? 0u : (uint32_t)ticket,
|
||||
points, WTO_NAV_RT_MAX_CORNERS, &result);
|
||||
b->set_str(b->blk, "status", STATUS[result.status]);
|
||||
set_int(b, "count", result.count);
|
||||
set_int(b, "lenCm", to_cm(result.lengthM));
|
||||
set_int(b, "truncated", result.truncated);
|
||||
set_int(b, "goalMoved", result.goalMoved);
|
||||
for (i = 0; i < result.count; i++) {
|
||||
char kx[16], ky[16], kz[16];
|
||||
snprintf(kx, sizeof(kx), "p%dx", i);
|
||||
snprintf(ky, sizeof(ky), "p%dy", i);
|
||||
snprintf(kz, sizeof(kz), "p%dz", i);
|
||||
set_vec_cm(b, kx, ky, kz, points + i * 3);
|
||||
}
|
||||
}
|
||||
|
||||
static void probe(const WtoNavBlock *b)
|
||||
{
|
||||
WtoNavProbe info;
|
||||
float pos[3];
|
||||
get_vec(b, 'p', pos);
|
||||
if (!wto_nav_probe((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0), pos,
|
||||
get_real(b, "snap", 0.0f), get_real(b, "wallR", 0.0f), &info))
|
||||
info.onMesh = -1;
|
||||
set_int(b, "onMesh", info.onMesh);
|
||||
if (info.onMesh != 1)
|
||||
return;
|
||||
set_int(b, "offCm", to_cm(info.offsetM));
|
||||
set_int(b, "wallCm", to_cm(info.wallDistM));
|
||||
set_int(b, "area", (int32_t)info.area);
|
||||
set_int(b, "flags", (int32_t)info.flags);
|
||||
set_vec_cm(b, "nx", "ny", "nz", info.nearest);
|
||||
}
|
||||
|
||||
static void raycast(const WtoNavBlock *b)
|
||||
{
|
||||
float start[3], goal[3], hit[3], frac = 0.0f;
|
||||
int clear;
|
||||
get_vec(b, 's', start);
|
||||
get_vec(b, 'g', goal);
|
||||
clear = wto_nav_raycast((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0),
|
||||
get_real(b, "snap", 0.0f), start, goal, &frac, hit);
|
||||
set_int(b, "clear", clear);
|
||||
set_int(b, "hitPm", (int32_t)(frac * 1000.0f + 0.5f));
|
||||
set_vec_cm(b, "hx", "hy", "hz", hit);
|
||||
}
|
||||
|
||||
static void nearest(const WtoNavBlock *b)
|
||||
{
|
||||
float pos[3], out[3] = { 0.0f, 0.0f, 0.0f };
|
||||
int found;
|
||||
get_vec(b, 'p', pos);
|
||||
found = wto_nav_nearest((uint32_t)get_long(b, "tier", 0), (uint32_t)get_long(b, "filter", 0),
|
||||
get_real(b, "radius", 0.0f), pos, out);
|
||||
set_int(b, "found", found);
|
||||
set_vec_cm(b, "x", "y", "z", out);
|
||||
}
|
||||
|
||||
static void add_dynamic(const WtoNavBlock *b)
|
||||
{
|
||||
float pos[3];
|
||||
get_vec(b, 'p', pos);
|
||||
set_int(b, "count", (int32_t)wto_nav_add_dynamic(pos, get_real(b, "radius", 0.0f), get_real(b, "mul", 1.0f),
|
||||
get_real(b, "until", 0.0f)));
|
||||
}
|
||||
|
||||
static void get_stats(const WtoNavBlock *b)
|
||||
{
|
||||
WtoNavStats stats;
|
||||
wto_nav_get_stats(&stats);
|
||||
set_int(b, "loaded", stats.loaded);
|
||||
set_int(b, "queries", (int32_t)stats.queries);
|
||||
set_int(b, "failures", (int32_t)stats.failures);
|
||||
set_int(b, "avgUs", stats.queries ? (int32_t)(stats.totalMicros / stats.queries) : 0);
|
||||
set_int(b, "maxUs", (int32_t)stats.maxMicros);
|
||||
set_int(b, "maxFrames", (int32_t)stats.maxFrames);
|
||||
set_int(b, "pumpMaxUs", (int32_t)stats.pumpMaxMicros);
|
||||
set_int(b, "pending", (int32_t)stats.pending);
|
||||
set_int(b, "dynamic", (int32_t)stats.dynamic);
|
||||
set_int(b, "meshQueries", (int32_t)stats.meshQueries);
|
||||
set_int(b, "traffic", (int32_t)stats.trafficPaths);
|
||||
set_int(b, "cornersMoved", (int32_t)stats.cornersMoved);
|
||||
}
|
||||
|
||||
static void pump(const WtoNavBlock *b)
|
||||
{
|
||||
WtoNavStats stats;
|
||||
wto_nav_pump((double)get_real(b, "budgetUs", 500.0f), get_real(b, "now", 0.0f));
|
||||
wto_nav_get_stats(&stats);
|
||||
set_int(b, "pending", (int32_t)stats.pending);
|
||||
}
|
||||
|
||||
int wto_nav_protocol_query(const WtoNavBlock *b, const char *op)
|
||||
{
|
||||
if (strcmp(op, "probe") == 0)
|
||||
probe(b);
|
||||
else if (strcmp(op, "path_result") == 0)
|
||||
path_result(b);
|
||||
else if (strcmp(op, "path_request") == 0)
|
||||
path_request(b);
|
||||
else if (strcmp(op, "raycast") == 0)
|
||||
raycast(b);
|
||||
else if (strcmp(op, "pump") == 0)
|
||||
pump(b);
|
||||
else if (strcmp(op, "nearest") == 0)
|
||||
nearest(b);
|
||||
else if (strcmp(op, "dynamic") == 0)
|
||||
add_dynamic(b);
|
||||
else if (strcmp(op, "get_stats") == 0)
|
||||
get_stats(b);
|
||||
else
|
||||
return 0;
|
||||
return 1;
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* The "wtoNav" request protocol of the ground AI script, shared by the game (wto-net
|
||||
* local_mp_nav.c) and the AI simulator (native/wto-ai-sim): the script fills a block of string
|
||||
* values with `op` and its arguments, the host answers by writing ints and strings back into it.
|
||||
* Coordinates in replies are centimetres. The host keeps the ops that depend on where the battle's
|
||||
* pack comes from (prefetch, load_map, unload_map); everything that only needs the loaded pack is
|
||||
* answered here.
|
||||
*
|
||||
* op=pump now (script seconds), budgetUs -> pending
|
||||
* op=path_request slot, tier, filter (0 tracked, 1 wheeled), group (team, 0 none), snap,
|
||||
* goalSnap, sx..sz, gx..gz -> ticket
|
||||
* op=path_result slot, ticket -> status=pending|full|partial|no_start|no_goal|failed|stale,
|
||||
* count, lenCm, truncated, goalMoved, p<i>x/p<i>y/p<i>z
|
||||
* op=probe tier, filter, snap, wallR, px..pz -> onMesh, offCm, wallCm, area, flags,
|
||||
* nx/ny/nz
|
||||
* op=raycast tier, filter, snap, sx..sz, gx..gz -> clear=1|0|-1, hitPm, hx/hy/hz
|
||||
* op=nearest tier, filter, radius, px..pz -> found, x/y/z
|
||||
* op=dynamic px..pz, radius, mul, until (script seconds) -> count
|
||||
* op=get_stats -> loaded, queries, failures, avgUs, maxUs, maxFrames, pumpMaxUs, pending,
|
||||
* dynamic, meshQueries, traffic, cornersMoved
|
||||
*
|
||||
* load_map carries the per-class costs t_<area>, w_<area> and the search tuning trafficPerPath,
|
||||
* trafficMaxMul, trafficHoldSec, cornerOffset; wto_nav_protocol_setup applies them.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Access to one request block. get_str returns "" for a value the block does not have. */
|
||||
typedef struct WtoNavBlock {
|
||||
void *blk;
|
||||
const char *(*get_str)(const void *blk, const char *name);
|
||||
void (*set_str)(void *blk, const char *name, const char *value);
|
||||
void (*set_int)(void *blk, const char *name, int32_t value);
|
||||
} WtoNavBlock;
|
||||
|
||||
/* Hands the costs and search tuning of a load_map request to the engine, before it loads. */
|
||||
void wto_nav_protocol_setup(const WtoNavBlock *b);
|
||||
|
||||
/* Answers `op` when it is one of the queries above; returns 0 for any other op. */
|
||||
int wto_nav_protocol_query(const WtoNavBlock *b, const char *op);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Point queries on the loaded pack (wto_nav_runtime.h) for the ground AI's path follower: what
|
||||
* lies under a vehicle (surface, flags, distance to the mesh edge), whether the mesh lets it go
|
||||
* straight somewhere, the nearest walkable point, and dynamic cost circles (wrecks, jams, rubble)
|
||||
* that later path searches route around.
|
||||
*/
|
||||
#include "wto_nav_internal.h"
|
||||
|
||||
#include <float.h>
|
||||
#include <string.h>
|
||||
|
||||
namespace wtonav {
|
||||
|
||||
DynamicCost g_dynamic[WTO_NAV_RT_MAX_DYNAMIC];
|
||||
uint32_t g_dynamic_count;
|
||||
|
||||
void dynamic_reset_locked()
|
||||
{
|
||||
g_dynamic_count = 0;
|
||||
}
|
||||
|
||||
void dynamic_expire_locked(float now)
|
||||
{
|
||||
uint32_t kept = 0;
|
||||
for (uint32_t i = 0; i < g_dynamic_count; i++) {
|
||||
if (g_dynamic[i].until >= now)
|
||||
g_dynamic[kept++] = g_dynamic[i];
|
||||
}
|
||||
g_dynamic_count = kept;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
bool valid_query(uint32_t tier, uint32_t filter)
|
||||
{
|
||||
return g_pack != nullptr && tier < WTO_NAV_TIER_COUNT && filter < WTO_NAV_RT_FILTER_COUNT;
|
||||
}
|
||||
|
||||
/* An existing circle overlapping most of the new one, or -1. */
|
||||
int find_dynamic(const float pos[3], float radius)
|
||||
{
|
||||
for (uint32_t i = 0; i < g_dynamic_count; i++) {
|
||||
const float dx = g_dynamic[i].pos[0] - pos[0], dz = g_dynamic[i].pos[2] - pos[2];
|
||||
const float reach = (g_dynamic[i].radius > radius ? g_dynamic[i].radius : radius) * 0.5f;
|
||||
if (dx * dx + dz * dz <= reach * reach)
|
||||
return (int)i;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
int soonest_dynamic()
|
||||
{
|
||||
int best = 0;
|
||||
for (uint32_t i = 1; i < g_dynamic_count; i++) {
|
||||
if (g_dynamic[i].until < g_dynamic[best].until)
|
||||
best = (int)i;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
} // namespace wtonav
|
||||
|
||||
using namespace wtonav;
|
||||
|
||||
extern "C" int wto_nav_probe(uint32_t tier, uint32_t filter, const float pos[3], float snap_m, float wall_radius_m, WtoNavProbe *probe)
|
||||
{
|
||||
memset(probe, 0, sizeof(*probe));
|
||||
AcquireSRWLockExclusive(&g_lock); /* findDistanceToWall uses the query's node pool */
|
||||
if (!valid_query(tier, filter) || !(snap_m > 0.0f)) {
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
return 0;
|
||||
}
|
||||
g_stats.meshQueries++;
|
||||
dtNavMeshQuery *query = g_pack->pointQueries[tier];
|
||||
const QueryFilter &qf = g_filters[filter];
|
||||
dtPolyRef ref = 0;
|
||||
if (snap_to_mesh(query, qf, snap_m, g_pack->heightSpan, pos, &ref, probe->nearest)) {
|
||||
const dtMeshTile *tile = nullptr;
|
||||
const dtPoly *poly = nullptr;
|
||||
probe->onMesh = 1;
|
||||
probe->offsetM = dtVdist2D(pos, probe->nearest);
|
||||
if (dtStatusSucceed(g_pack->meshes[tier]->getTileAndPolyByRef(ref, &tile, &poly))) {
|
||||
probe->area = poly->getArea();
|
||||
probe->flags = poly->flags;
|
||||
}
|
||||
float hit_pos[3], hit_normal[3];
|
||||
float dist = wall_radius_m;
|
||||
if (wall_radius_m > 0.0f &&
|
||||
dtStatusFailed(query->findDistanceToWall(ref, probe->nearest, wall_radius_m, &qf, &dist, hit_pos, hit_normal)))
|
||||
dist = wall_radius_m;
|
||||
probe->wallDistM = dist;
|
||||
}
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
return 1;
|
||||
}
|
||||
|
||||
extern "C" int wto_nav_raycast(uint32_t tier, uint32_t filter, float snap_m, const float start[3], const float goal[3],
|
||||
float *hit_frac, float hit[3])
|
||||
{
|
||||
*hit_frac = 0.0f;
|
||||
dtVcopy(hit, start);
|
||||
AcquireSRWLockShared(&g_lock);
|
||||
if (!valid_query(tier, filter) || !(snap_m > 0.0f)) {
|
||||
ReleaseSRWLockShared(&g_lock);
|
||||
return -1;
|
||||
}
|
||||
InterlockedIncrement((volatile LONG *)&g_stats.meshQueries);
|
||||
const dtNavMeshQuery *query = g_pack->pointQueries[tier];
|
||||
const QueryFilter &qf = g_filters[filter];
|
||||
dtPolyRef ref = 0;
|
||||
float from[3];
|
||||
int clear = -1;
|
||||
if (snap_to_mesh(query, qf, snap_m, g_pack->heightSpan, start, &ref, from)) {
|
||||
float t = 0.0f, normal[3];
|
||||
dtPolyRef visited[64];
|
||||
int visited_count = 0;
|
||||
if (dtStatusSucceed(query->raycast(ref, from, goal, &qf, &t, normal, visited, &visited_count, 64))) {
|
||||
clear = t == FLT_MAX ? 1 : 0;
|
||||
*hit_frac = t == FLT_MAX ? 1.0f : t;
|
||||
dtVlerp(hit, from, goal, *hit_frac);
|
||||
}
|
||||
}
|
||||
ReleaseSRWLockShared(&g_lock);
|
||||
return clear;
|
||||
}
|
||||
|
||||
extern "C" int wto_nav_nearest(uint32_t tier, uint32_t filter, float radius_m, const float pos[3], float out[3])
|
||||
{
|
||||
int found = 0;
|
||||
AcquireSRWLockShared(&g_lock);
|
||||
if (valid_query(tier, filter) && radius_m > 0.0f) {
|
||||
InterlockedIncrement((volatile LONG *)&g_stats.meshQueries);
|
||||
dtPolyRef ref = 0;
|
||||
found = snap_to_mesh(g_pack->pointQueries[tier], g_filters[filter], radius_m, g_pack->heightSpan, pos, &ref, out);
|
||||
}
|
||||
ReleaseSRWLockShared(&g_lock);
|
||||
return found;
|
||||
}
|
||||
|
||||
extern "C" uint32_t wto_nav_add_dynamic(const float pos[3], float radius_m, float cost_mul, float until)
|
||||
{
|
||||
if (!(radius_m > 0.0f) || !(cost_mul > 0.0f))
|
||||
return 0;
|
||||
AcquireSRWLockExclusive(&g_lock);
|
||||
int at = find_dynamic(pos, radius_m);
|
||||
if (at >= 0) {
|
||||
DynamicCost &d = g_dynamic[at];
|
||||
dtVcopy(d.pos, pos);
|
||||
d.radius = d.radius > radius_m ? d.radius : radius_m;
|
||||
d.mul = d.mul > cost_mul ? d.mul : cost_mul;
|
||||
d.until = d.until > until ? d.until : until;
|
||||
} else {
|
||||
at = g_dynamic_count < WTO_NAV_RT_MAX_DYNAMIC ? (int)g_dynamic_count++ : soonest_dynamic();
|
||||
DynamicCost &d = g_dynamic[at];
|
||||
dtVcopy(d.pos, pos);
|
||||
d.radius = radius_m;
|
||||
d.mul = cost_mul;
|
||||
d.until = until;
|
||||
}
|
||||
const uint32_t count = g_dynamic_count;
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
return count;
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
/*
|
||||
* In-game navigation engine (wto_nav_runtime.h): loads one `.wtonav` pack written by
|
||||
* tools/navgen/bake into upstream Detour meshes, optionally on a background thread while the
|
||||
* battle is still loading. Path searches live in wto_nav_paths.cpp, point queries and dynamic
|
||||
* costs in wto_nav_queries.cpp.
|
||||
*/
|
||||
#include "wto_nav_internal.h"
|
||||
|
||||
#include "DetourAlloc.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <string>
|
||||
|
||||
namespace wtonav {
|
||||
|
||||
SRWLOCK g_lock = SRWLOCK_INIT;
|
||||
Pack *g_pack;
|
||||
QueryFilter g_filters[WTO_NAV_RT_FILTER_COUNT];
|
||||
WtoNavStats g_stats;
|
||||
WtoNavTuning g_tuning;
|
||||
int g_cost_tier = -1;
|
||||
int g_cost_group = -1;
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr size_t kMaxPackBytes = 512u * 1024u * 1024u;
|
||||
constexpr size_t kMaxEverBytes = 64u * 1024u;
|
||||
constexpr int kMaxLevelBlocks = 4096;
|
||||
|
||||
bool g_filters_ready;
|
||||
|
||||
/* A pack read on a background thread, waiting for wto_nav_load. Guarded by g_stage_lock. */
|
||||
struct Staged {
|
||||
std::wstring packPath;
|
||||
std::wstring levelPath;
|
||||
HANDLE thread = nullptr;
|
||||
Pack *pack = nullptr;
|
||||
WtoNavLoadInfo info = {};
|
||||
};
|
||||
|
||||
SRWLOCK g_stage_lock = SRWLOCK_INIT;
|
||||
Staged *g_staged;
|
||||
|
||||
void init_filters_locked()
|
||||
{
|
||||
if (g_filters_ready)
|
||||
return;
|
||||
for (QueryFilter &filter : g_filters) {
|
||||
filter.setIncludeFlags(WTO_FLAG_WALK);
|
||||
filter.setExcludeFlags(WTO_FLAG_DEEP_WATER | WTO_FLAG_BLOCKED);
|
||||
}
|
||||
g_filters_ready = true;
|
||||
}
|
||||
|
||||
void free_pack(Pack *pack)
|
||||
{
|
||||
if (pack == nullptr)
|
||||
return;
|
||||
for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) {
|
||||
dtFreeNavMeshQuery(pack->pathQueries[t]);
|
||||
dtFreeNavMeshQuery(pack->pointQueries[t]);
|
||||
dtFreeNavMesh(pack->meshes[t]);
|
||||
}
|
||||
delete pack;
|
||||
}
|
||||
|
||||
bool read_file(const wchar_t *path, std::vector<uint8_t> &out, WtoNavLoadInfo *info)
|
||||
{
|
||||
FILE *file = nullptr;
|
||||
if (_wfopen_s(&file, path, L"rb") != 0 || file == nullptr) {
|
||||
info->result = GetFileAttributesW(path) == INVALID_FILE_ATTRIBUTES ? WTO_NAV_LOAD_MISSING : WTO_NAV_LOAD_UNREADABLE;
|
||||
snprintf(info->detail, sizeof(info->detail), "%s", info->result == WTO_NAV_LOAD_MISSING ? "no pack file" : "cannot open pack");
|
||||
return false;
|
||||
}
|
||||
bool ok = _fseeki64(file, 0, SEEK_END) == 0;
|
||||
long long size = ok ? _ftelli64(file) : -1;
|
||||
ok = ok && size > 0 && (unsigned long long)size <= kMaxPackBytes && _fseeki64(file, 0, SEEK_SET) == 0;
|
||||
if (ok) {
|
||||
out.resize((size_t)size);
|
||||
ok = fread(out.data(), 1, out.size(), file) == out.size();
|
||||
}
|
||||
fclose(file);
|
||||
if (!ok) {
|
||||
info->result = WTO_NAV_LOAD_UNREADABLE;
|
||||
snprintf(info->detail, sizeof(info->detail), "cannot read pack (%lld bytes)", size);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool fits(const std::vector<uint8_t> &data, uint64_t offset, uint64_t size)
|
||||
{
|
||||
return offset <= data.size() && size <= data.size() - offset;
|
||||
}
|
||||
|
||||
bool init_queries(Pack *pack, uint32_t tier)
|
||||
{
|
||||
pack->pathQueries[tier] = dtAllocNavMeshQuery();
|
||||
pack->pointQueries[tier] = dtAllocNavMeshQuery();
|
||||
return pack->pathQueries[tier] != nullptr && pack->pointQueries[tier] != nullptr &&
|
||||
dtStatusSucceed(pack->pathQueries[tier]->init(pack->meshes[tier], kPathSearchNodes)) &&
|
||||
dtStatusSucceed(pack->pointQueries[tier]->init(pack->meshes[tier], kPointSearchNodes));
|
||||
}
|
||||
|
||||
/* Traffic counters: one per polygon and group, addressed through each tile slot's first index. */
|
||||
void init_traffic(Pack *pack, uint32_t tier)
|
||||
{
|
||||
const dtNavMesh *mesh = pack->meshes[tier];
|
||||
const int max_tiles = mesh->getMaxTiles();
|
||||
uint32_t total = 0;
|
||||
pack->tileBase[tier].assign((size_t)max_tiles, 0);
|
||||
for (int i = 0; i < max_tiles; i++) {
|
||||
pack->tileBase[tier][(size_t)i] = total;
|
||||
const dtMeshTile *tile = mesh->getTile(i);
|
||||
if (tile != nullptr && tile->header != nullptr)
|
||||
total += (uint32_t)tile->header->polyCount;
|
||||
}
|
||||
for (std::vector<uint16_t> &counts : pack->traffic[tier])
|
||||
counts.assign(total, 0);
|
||||
}
|
||||
|
||||
bool load_tier(const std::vector<uint8_t> &data, const WtoNavHeader &hdr, uint32_t tier, Pack *pack, uint32_t *polys, char *detail, size_t detail_size)
|
||||
{
|
||||
uint64_t at = hdr.tierOffsets[tier];
|
||||
const uint64_t end = at + hdr.tierSizes[tier];
|
||||
dtNavMeshParams params;
|
||||
uint32_t tile_count = 0;
|
||||
|
||||
if (!fits(data, at, hdr.tierSizes[tier]) || hdr.tierSizes[tier] < sizeof(params) + sizeof(tile_count)) {
|
||||
snprintf(detail, detail_size, "tier %u outside the file", tier);
|
||||
return false;
|
||||
}
|
||||
memcpy(¶ms, data.data() + at, sizeof(params));
|
||||
at += sizeof(params);
|
||||
memcpy(&tile_count, data.data() + at, sizeof(tile_count));
|
||||
at += sizeof(tile_count);
|
||||
|
||||
pack->meshes[tier] = dtAllocNavMesh();
|
||||
if (pack->meshes[tier] == nullptr || dtStatusFailed(pack->meshes[tier]->init(¶ms))) {
|
||||
snprintf(detail, detail_size, "tier %u mesh parameters rejected", tier);
|
||||
return false;
|
||||
}
|
||||
for (uint32_t i = 0; i < tile_count; i++) {
|
||||
uint32_t size = 0;
|
||||
if (at + sizeof(size) > end) {
|
||||
snprintf(detail, detail_size, "tier %u tile %u header truncated", tier, i);
|
||||
return false;
|
||||
}
|
||||
memcpy(&size, data.data() + at, sizeof(size));
|
||||
at += sizeof(size);
|
||||
if (size == 0 || at + size > end) {
|
||||
snprintf(detail, detail_size, "tier %u tile %u truncated", tier, i);
|
||||
return false;
|
||||
}
|
||||
unsigned char *tile = (unsigned char *)dtAlloc(size, DT_ALLOC_PERM);
|
||||
if (tile == nullptr) {
|
||||
snprintf(detail, detail_size, "out of memory for tier %u", tier);
|
||||
return false;
|
||||
}
|
||||
memcpy(tile, data.data() + at, size);
|
||||
at += size;
|
||||
if (dtStatusFailed(pack->meshes[tier]->addTile(tile, (int)size, DT_TILE_FREE_DATA, 0, nullptr))) {
|
||||
dtFree(tile);
|
||||
snprintf(detail, detail_size, "tier %u tile %u rejected by Detour", tier, i);
|
||||
return false;
|
||||
}
|
||||
*polys += (uint32_t)((const dtMeshHeader *)tile)->polyCount;
|
||||
}
|
||||
init_traffic(pack, tier);
|
||||
if (!init_queries(pack, tier)) {
|
||||
snprintf(detail, detail_size, "tier %u query init failed", tier);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
Pack *parse_pack(const std::vector<uint8_t> &data, WtoNavLoadInfo *info)
|
||||
{
|
||||
WtoNavHeader hdr;
|
||||
if (data.size() < sizeof(hdr)) {
|
||||
snprintf(info->detail, sizeof(info->detail), "file shorter than the header");
|
||||
return nullptr;
|
||||
}
|
||||
memcpy(&hdr, data.data(), sizeof(hdr));
|
||||
if (memcmp(hdr.magic, WTO_NAV_MAGIC, sizeof(hdr.magic)) != 0 || hdr.version != WTO_NAV_VERSION ||
|
||||
hdr.tierCount != WTO_NAV_TIER_COUNT) {
|
||||
snprintf(info->detail, sizeof(info->detail), "not a version %u pack", WTO_NAV_VERSION);
|
||||
return nullptr;
|
||||
}
|
||||
const uint64_t cover_bytes = (uint64_t)hdr.coverCount * sizeof(WtoCoverPoint);
|
||||
const uint64_t tac_bytes = (uint64_t)hdr.tacCols * hdr.tacRows * sizeof(WtoTacticalCell);
|
||||
if (!fits(data, hdr.coverOffset, cover_bytes) || !fits(data, hdr.tacOffset, tac_bytes)) {
|
||||
snprintf(info->detail, sizeof(info->detail), "cover or tactical grid outside the file");
|
||||
return nullptr;
|
||||
}
|
||||
memcpy(info->packSha1, hdr.everSha1, sizeof(info->packSha1));
|
||||
|
||||
Pack *pack = new Pack();
|
||||
pack->heightSpan = hdr.bmax[1] - hdr.bmin[1];
|
||||
for (uint32_t t = 0; t < WTO_NAV_TIER_COUNT; t++) {
|
||||
if (!load_tier(data, hdr, t, pack, &info->polys[t], info->detail, sizeof(info->detail))) {
|
||||
free_pack(pack);
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
pack->covers.resize(hdr.coverCount);
|
||||
if (cover_bytes != 0)
|
||||
memcpy(pack->covers.data(), data.data() + hdr.coverOffset, (size_t)cover_bytes);
|
||||
pack->tactical.resize((size_t)hdr.tacCols * hdr.tacRows);
|
||||
if (tac_bytes != 0)
|
||||
memcpy(pack->tactical.data(), data.data() + hdr.tacOffset, (size_t)tac_bytes);
|
||||
info->tiers = WTO_NAV_TIER_COUNT;
|
||||
info->covers = hdr.coverCount;
|
||||
return pack;
|
||||
}
|
||||
|
||||
/* Reads and parses a pack plus the level fingerprint; runs on any thread, touches no globals. */
|
||||
Pack *read_pack(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info)
|
||||
{
|
||||
const double began = now_micros();
|
||||
std::vector<uint8_t> data;
|
||||
Pack *pack = nullptr;
|
||||
|
||||
memset(info, 0, sizeof(*info));
|
||||
if (level_path != nullptr && level_path[0] != L'\0')
|
||||
info->fingerprintKnown = wto_nav_read_level_fingerprint(level_path, info->levelSha1);
|
||||
if (read_file(pack_path, data, info)) {
|
||||
pack = parse_pack(data, info);
|
||||
info->result = pack != nullptr ? WTO_NAV_LOAD_OK : WTO_NAV_LOAD_CORRUPT;
|
||||
}
|
||||
if (pack != nullptr && info->fingerprintKnown)
|
||||
info->fingerprintMatch = memcmp(info->packSha1, info->levelSha1, sizeof(info->packSha1)) == 0;
|
||||
info->readMs = (now_micros() - began) / 1000.0;
|
||||
return pack;
|
||||
}
|
||||
|
||||
DWORD WINAPI prefetch_main(void *arg)
|
||||
{
|
||||
Staged *staged = (Staged *)arg;
|
||||
staged->pack = read_pack(staged->packPath.c_str(), staged->levelPath.c_str(), &staged->info);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/* Waits for the background read of `staged` and frees what it produced. */
|
||||
void discard_staged(Staged *staged)
|
||||
{
|
||||
if (staged == nullptr)
|
||||
return;
|
||||
if (staged->thread != nullptr) {
|
||||
WaitForSingleObject(staged->thread, INFINITE);
|
||||
CloseHandle(staged->thread);
|
||||
}
|
||||
free_pack(staged->pack);
|
||||
delete staged;
|
||||
}
|
||||
|
||||
/* Takes the staged pack if it is `pack_path`; the caller then owns (and joins) it. */
|
||||
Staged *take_staged(const wchar_t *pack_path)
|
||||
{
|
||||
AcquireSRWLockExclusive(&g_stage_lock);
|
||||
Staged *staged = g_staged;
|
||||
if (staged != nullptr && staged->packPath == pack_path)
|
||||
g_staged = nullptr;
|
||||
else
|
||||
staged = nullptr;
|
||||
ReleaseSRWLockExclusive(&g_stage_lock);
|
||||
return staged;
|
||||
}
|
||||
|
||||
void replace_pack(Pack *pack)
|
||||
{
|
||||
AcquireSRWLockExclusive(&g_lock);
|
||||
init_filters_locked();
|
||||
free_pack(g_pack);
|
||||
g_pack = pack;
|
||||
paths_reset_locked();
|
||||
dynamic_reset_locked();
|
||||
memset(&g_stats, 0, sizeof(g_stats));
|
||||
g_stats.loaded = pack != nullptr;
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
float QueryFilter::getCost(const float *pa, const float *pb,
|
||||
const dtPolyRef, const dtMeshTile *, const dtPoly *,
|
||||
const dtPolyRef curRef, const dtMeshTile *, const dtPoly *curPoly,
|
||||
const dtPolyRef, const dtMeshTile *, const dtPoly *) const
|
||||
{
|
||||
float cost = dtVdist(pa, pb) * getAreaCost(curPoly->getArea());
|
||||
if (curPoly->flags & WTO_FLAG_CHOKEPOINT)
|
||||
cost *= chokepointMul;
|
||||
if (g_cost_group >= 0 && g_pack != nullptr) {
|
||||
const int at = poly_index(*g_pack, (uint32_t)g_cost_tier, curRef);
|
||||
const uint16_t paths = at >= 0 ? g_pack->traffic[g_cost_tier][g_cost_group][(size_t)at] : 0;
|
||||
if (paths != 0) {
|
||||
const float mul = 1.0f + g_tuning.trafficCostPerPath * (float)paths;
|
||||
cost *= mul < g_tuning.trafficCostMaxMul ? mul : g_tuning.trafficCostMaxMul;
|
||||
}
|
||||
}
|
||||
if (g_dynamic_count != 0) {
|
||||
const float mx = (pa[0] + pb[0]) * 0.5f, mz = (pa[2] + pb[2]) * 0.5f;
|
||||
float mul = 1.0f;
|
||||
for (uint32_t i = 0; i < g_dynamic_count; i++) {
|
||||
const DynamicCost &d = g_dynamic[i];
|
||||
const float dx = mx - d.pos[0], dz = mz - d.pos[2];
|
||||
if (dx * dx + dz * dz < d.radius * d.radius && d.mul > mul)
|
||||
mul = d.mul;
|
||||
}
|
||||
cost *= mul;
|
||||
}
|
||||
return cost;
|
||||
}
|
||||
|
||||
bool snap_to_mesh(const dtNavMeshQuery *query, const dtQueryFilter &filter, float snap, float height_span,
|
||||
const float point[3], dtPolyRef *ref, float nearest[3])
|
||||
{
|
||||
const float near_extents[3] = { snap, snap, snap };
|
||||
if (dtStatusSucceed(query->findNearestPoly(point, near_extents, &filter, ref, nearest)) && *ref != 0)
|
||||
return true;
|
||||
const float column_extents[3] = { snap, height_span > snap ? height_span : snap, snap };
|
||||
return dtStatusSucceed(query->findNearestPoly(point, column_extents, &filter, ref, nearest)) && *ref != 0;
|
||||
}
|
||||
|
||||
int poly_index(const Pack &pack, uint32_t tier, dtPolyRef ref)
|
||||
{
|
||||
if (tier >= WTO_NAV_TIER_COUNT || pack.meshes[tier] == nullptr || ref == 0)
|
||||
return -1;
|
||||
unsigned int salt = 0, tile = 0, poly = 0;
|
||||
pack.meshes[tier]->decodePolyId(ref, salt, tile, poly);
|
||||
const std::vector<uint32_t> &base = pack.tileBase[tier];
|
||||
if (tile >= base.size())
|
||||
return -1;
|
||||
const size_t at = (size_t)base[tile] + poly;
|
||||
return at < pack.traffic[tier][0].size() ? (int)at : -1;
|
||||
}
|
||||
|
||||
double now_micros()
|
||||
{
|
||||
static LARGE_INTEGER frequency;
|
||||
LARGE_INTEGER counter;
|
||||
if (frequency.QuadPart == 0)
|
||||
QueryPerformanceFrequency(&frequency);
|
||||
QueryPerformanceCounter(&counter);
|
||||
return (double)counter.QuadPart * 1e6 / (double)frequency.QuadPart;
|
||||
}
|
||||
|
||||
} // namespace wtonav
|
||||
|
||||
using namespace wtonav;
|
||||
|
||||
extern "C" int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20])
|
||||
{
|
||||
FILE *file = nullptr;
|
||||
uint8_t header[12];
|
||||
int found = 0;
|
||||
|
||||
if (level_path == nullptr || _wfopen_s(&file, level_path, L"rb") != 0 || file == nullptr)
|
||||
return 0;
|
||||
if (fread(header, 1, sizeof(header), file) != sizeof(header) || memcmp(header, "DBLD3x64", 8) != 0) {
|
||||
fclose(file);
|
||||
return 0;
|
||||
}
|
||||
/* Tagged top-level blocks: u32 length (low 30 bits, tag included), 4-byte NUL-padded tag. */
|
||||
for (int block = 0; block < kMaxLevelBlocks && !found; block++) {
|
||||
uint32_t len_flags = 0;
|
||||
char tag[4];
|
||||
if (fread(&len_flags, 1, 4, file) != 4 || fread(tag, 1, 4, file) != 4)
|
||||
break;
|
||||
const uint32_t len = len_flags & 0x3FFFFFFFu;
|
||||
if (len < 4)
|
||||
break;
|
||||
if (memcmp(tag, "\0END", 4) == 0)
|
||||
break;
|
||||
if (memcmp(tag, "eVER", 4) != 0) {
|
||||
if (_fseeki64(file, (long long)len - 4, SEEK_CUR) != 0)
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
/* Exporter version string (u32 length, bytes padded to 4), section count, level SHA-1. */
|
||||
std::vector<uint8_t> body(len - 4 <= kMaxEverBytes ? len - 4 : 0);
|
||||
if (body.empty() || fread(body.data(), 1, body.size(), file) != body.size())
|
||||
break;
|
||||
uint32_t text_len = 0;
|
||||
memcpy(&text_len, body.data(), body.size() >= 4 ? 4 : 0);
|
||||
const size_t at = 4 + (((size_t)text_len + 3u) & ~(size_t)3u);
|
||||
if (body.size() >= 4 && at + 4 + 20 <= body.size()) {
|
||||
memcpy(sha1, body.data() + at + 4, 20);
|
||||
found = 1;
|
||||
}
|
||||
break;
|
||||
}
|
||||
fclose(file);
|
||||
return found;
|
||||
}
|
||||
|
||||
extern "C" void wto_nav_prefetch(const wchar_t *pack_path, const wchar_t *level_path)
|
||||
{
|
||||
if (pack_path == nullptr || pack_path[0] == L'\0')
|
||||
return;
|
||||
AcquireSRWLockExclusive(&g_stage_lock);
|
||||
if (g_staged != nullptr && g_staged->packPath == pack_path) {
|
||||
ReleaseSRWLockExclusive(&g_stage_lock);
|
||||
return;
|
||||
}
|
||||
Staged *previous = g_staged;
|
||||
Staged *staged = new Staged();
|
||||
staged->packPath = pack_path;
|
||||
staged->levelPath = level_path != nullptr ? level_path : L"";
|
||||
staged->thread = CreateThread(nullptr, 0, prefetch_main, staged, 0, nullptr);
|
||||
if (staged->thread == nullptr) {
|
||||
delete staged;
|
||||
staged = nullptr;
|
||||
}
|
||||
g_staged = staged;
|
||||
ReleaseSRWLockExclusive(&g_stage_lock);
|
||||
discard_staged(previous);
|
||||
}
|
||||
|
||||
extern "C" void wto_nav_load(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info)
|
||||
{
|
||||
const double began = now_micros();
|
||||
Staged *staged = take_staged(pack_path);
|
||||
Pack *pack;
|
||||
|
||||
if (staged != nullptr) {
|
||||
WaitForSingleObject(staged->thread, INFINITE);
|
||||
CloseHandle(staged->thread);
|
||||
staged->thread = nullptr;
|
||||
pack = staged->pack;
|
||||
staged->pack = nullptr;
|
||||
*info = staged->info;
|
||||
info->prefetched = 1;
|
||||
discard_staged(staged);
|
||||
} else {
|
||||
pack = read_pack(pack_path, level_path, info);
|
||||
}
|
||||
info->waitMs = (now_micros() - began) / 1000.0;
|
||||
replace_pack(pack);
|
||||
}
|
||||
|
||||
extern "C" void wto_nav_unload(void)
|
||||
{
|
||||
replace_pack(nullptr);
|
||||
}
|
||||
|
||||
extern "C" int wto_nav_is_loaded(void)
|
||||
{
|
||||
AcquireSRWLockShared(&g_lock);
|
||||
const int loaded = g_pack != nullptr;
|
||||
ReleaseSRWLockShared(&g_lock);
|
||||
return loaded;
|
||||
}
|
||||
|
||||
extern "C" void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs)
|
||||
{
|
||||
if (filter >= WTO_NAV_RT_FILTER_COUNT || costs == nullptr)
|
||||
return;
|
||||
AcquireSRWLockExclusive(&g_lock);
|
||||
init_filters_locked();
|
||||
for (int area = 0; area < WTO_NAV_RT_AREA_COUNT; area++)
|
||||
g_filters[filter].setAreaCost(area, costs->area[area]);
|
||||
g_filters[filter].chokepointMul = costs->chokepointMul;
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
}
|
||||
|
||||
extern "C" void wto_nav_set_tuning(const WtoNavTuning *tuning)
|
||||
{
|
||||
if (tuning == nullptr)
|
||||
return;
|
||||
AcquireSRWLockExclusive(&g_lock);
|
||||
g_tuning = *tuning;
|
||||
if (!(g_tuning.trafficCostPerPath > 0.0f))
|
||||
g_tuning.trafficCostPerPath = 0.0f;
|
||||
if (!(g_tuning.trafficCostMaxMul >= 1.0f))
|
||||
g_tuning.trafficCostMaxMul = 1.0f;
|
||||
if (!(g_tuning.trafficHoldSec > 0.0f))
|
||||
g_tuning.trafficHoldSec = 0.0f;
|
||||
if (!(g_tuning.cornerOffsetM > 0.0f))
|
||||
g_tuning.cornerOffsetM = 0.0f;
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
}
|
||||
|
||||
extern "C" void wto_nav_get_stats(WtoNavStats *stats)
|
||||
{
|
||||
AcquireSRWLockExclusive(&g_lock);
|
||||
g_stats.pending = paths_pending_locked();
|
||||
g_stats.trafficPaths = traffic_paths_locked();
|
||||
g_stats.dynamic = g_dynamic_count;
|
||||
*stats = g_stats;
|
||||
ReleaseSRWLockExclusive(&g_lock);
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
/*
|
||||
* In-game navigation engine: one baked `.wtonav` pack (tools/navgen) held for the battle in
|
||||
* progress, queried through upstream Detour. The C side (wto-net local_mp_nav.c) owns the
|
||||
* daScript request protocol; this interface only knows packs, levels, paths and mesh queries.
|
||||
*
|
||||
* Every function is safe to call from any thread; queries are serialized internally.
|
||||
*/
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#define WTO_NAV_RT_AREA_COUNT 12 /* WtoPolyArea values 0..11 */
|
||||
#define WTO_NAV_RT_FILTER_COUNT 2 /* 0 tracked, 1 wheeled */
|
||||
#define WTO_NAV_RT_PATH_SLOTS 160 /* Independent path searches the script may keep in flight */
|
||||
#define WTO_NAV_RT_MAX_CORNERS 96 /* Straight-path corners returned per path */
|
||||
#define WTO_NAV_RT_MAX_DYNAMIC 64 /* Live dynamic cost circles (wrecks, jams, rubble) */
|
||||
#define WTO_NAV_RT_TRAFFIC_GROUPS 2 /* Teams whose planned paths count as traffic for each other */
|
||||
|
||||
/* Battle-wide search behaviour, set before the pack loads. */
|
||||
typedef struct WtoNavTuning {
|
||||
float trafficCostPerPath; /* Cost added per path of the same group through a polygon; 0 = off */
|
||||
float trafficCostMaxMul; /* Highest traffic multiplier */
|
||||
float trafficHoldSec; /* A finished path counts as traffic this long (script seconds) */
|
||||
float cornerOffsetM; /* Path corners are moved this far away from the edge they turn around */
|
||||
} WtoNavTuning;
|
||||
|
||||
/* Detour traversal costs for one vehicle class, indexed by WtoPolyArea. */
|
||||
typedef struct WtoNavCosts {
|
||||
float area[WTO_NAV_RT_AREA_COUNT];
|
||||
float chokepointMul; /* Multiplies the area cost on WTO_FLAG_CHOKEPOINT polygons */
|
||||
} WtoNavCosts;
|
||||
|
||||
typedef enum WtoNavLoadResult {
|
||||
WTO_NAV_LOAD_OK = 0,
|
||||
WTO_NAV_LOAD_MISSING, /* No pack file for the level */
|
||||
WTO_NAV_LOAD_UNREADABLE, /* The file exists but cannot be read */
|
||||
WTO_NAV_LOAD_CORRUPT, /* Bad header, offsets or Detour tile data */
|
||||
} WtoNavLoadResult;
|
||||
|
||||
typedef struct WtoNavLoadInfo {
|
||||
WtoNavLoadResult result;
|
||||
int fingerprintKnown; /* 1 when the level file's eVER SHA-1 was read */
|
||||
int fingerprintMatch; /* 1 when it equals the pack's; meaningful only when known */
|
||||
int prefetched; /* 1 when the pack was read in the background beforehand */
|
||||
uint8_t packSha1[20];
|
||||
uint8_t levelSha1[20];
|
||||
uint32_t tiers;
|
||||
uint32_t covers;
|
||||
uint32_t polys[3];
|
||||
double readMs; /* Time spent reading and parsing, wherever it happened */
|
||||
double waitMs; /* Time the caller of wto_nav_load was held up */
|
||||
char detail[96]; /* Why loading failed, for the log */
|
||||
} WtoNavLoadInfo;
|
||||
|
||||
typedef enum WtoNavPathStatus {
|
||||
WTO_NAV_PATH_FULL = 0,
|
||||
WTO_NAV_PATH_PARTIAL, /* Ends at the reachable polygon closest to the goal */
|
||||
WTO_NAV_PATH_NO_START, /* Start not within the snap radius of the mesh */
|
||||
WTO_NAV_PATH_NO_GOAL, /* Goal not within the goal snap radius of the mesh */
|
||||
WTO_NAV_PATH_FAILED, /* No pack loaded, bad tier or Detour failure */
|
||||
WTO_NAV_PATH_PENDING, /* Queued or being searched; ask again after the next pump */
|
||||
WTO_NAV_PATH_STALE, /* The slot holds another (newer) request, or none */
|
||||
} WtoNavPathStatus;
|
||||
|
||||
typedef struct WtoNavPathRequest {
|
||||
uint32_t tier; /* 0 narrow, 1 standard, 2 wide */
|
||||
uint32_t filter; /* 0 tracked, 1 wheeled */
|
||||
float snapM; /* Start (and first goal) snap radius */
|
||||
float goalSnapM; /* Wider horizontal goal snap when the goal misses snapM */
|
||||
uint32_t group; /* 1..WTO_NAV_RT_TRAFFIC_GROUPS: avoids and adds to that group's traffic; 0 none */
|
||||
float start[3];
|
||||
float goal[3];
|
||||
} WtoNavPathRequest;
|
||||
|
||||
typedef struct WtoNavPathResult {
|
||||
WtoNavPathStatus status;
|
||||
int count; /* Corners written, the first being the snapped start */
|
||||
int truncated; /* 1 when the path has more corners than were returned */
|
||||
int goalMoved; /* 1 when the goal was snapped with goalSnapM */
|
||||
float lengthM; /* Length of the returned corners */
|
||||
} WtoNavPathResult;
|
||||
|
||||
/* What the mesh says about one point of the tier's mesh. */
|
||||
typedef struct WtoNavProbe {
|
||||
int onMesh; /* 1 when a polygon lies within the snap radius */
|
||||
float nearest[3]; /* Closest point on that polygon */
|
||||
float offsetM; /* Horizontal distance from the asked point to `nearest` */
|
||||
float wallDistM; /* Distance to the mesh edge, capped at the search radius */
|
||||
uint32_t area; /* WtoPolyArea of the polygon */
|
||||
uint32_t flags; /* WtoPolyFlag bits of the polygon */
|
||||
} WtoNavProbe;
|
||||
|
||||
typedef struct WtoNavStats {
|
||||
int loaded;
|
||||
uint32_t queries; /* Finished path searches */
|
||||
uint32_t failures; /* Of which not FULL */
|
||||
double totalMicros; /* Search time of finished paths, summed over their frames */
|
||||
double maxMicros; /* Longest search time of a single path */
|
||||
uint32_t maxFrames; /* Most pump frames a single path took */
|
||||
double pumpMaxMicros; /* Longest single pump */
|
||||
uint32_t pending; /* Paths waiting or being searched now */
|
||||
uint32_t dynamic; /* Live dynamic cost circles */
|
||||
uint32_t meshQueries; /* Probe, raycast and nearest calls */
|
||||
uint32_t trafficPaths; /* Finished paths counting as traffic now */
|
||||
uint32_t cornersMoved; /* Path corners moved away from the edge they turn around */
|
||||
} WtoNavStats;
|
||||
|
||||
/* Reads the eVER SHA-1 of a Dagor level file (levels/<name>.bin) without loading the level. */
|
||||
int wto_nav_read_level_fingerprint(const wchar_t *level_path, uint8_t sha1[20]);
|
||||
|
||||
/*
|
||||
* Starts reading `pack_path` (and the fingerprint of `level_path`) on a background thread so a
|
||||
* later wto_nav_load of the same pack only takes the result. Nothing happens when that pack is
|
||||
* already being read or waiting; a different one replaces it.
|
||||
*/
|
||||
void wto_nav_prefetch(const wchar_t *pack_path, const wchar_t *level_path);
|
||||
|
||||
/*
|
||||
* Makes `pack_path` the loaded pack, replacing any other: from the background read when it is
|
||||
* the same file (waiting for it to finish), otherwise read here. A fingerprint mismatch is
|
||||
* reported but never refuses the pack. Clears paths in flight and dynamic costs.
|
||||
*/
|
||||
void wto_nav_load(const wchar_t *pack_path, const wchar_t *level_path, WtoNavLoadInfo *info);
|
||||
void wto_nav_unload(void);
|
||||
int wto_nav_is_loaded(void);
|
||||
|
||||
/* Replaces the traversal costs of one filter (0 tracked, 1 wheeled). */
|
||||
void wto_nav_set_costs(uint32_t filter, const WtoNavCosts *costs);
|
||||
|
||||
/* Replaces the traffic and corner settings; applies to searches started afterwards. */
|
||||
void wto_nav_set_tuning(const WtoNavTuning *tuning);
|
||||
|
||||
/*
|
||||
* Queues a path search in `slot`, replacing whatever the slot held. Start and goal are snapped
|
||||
* at once; a miss is final and reported through the ticket's result. Returns the ticket that
|
||||
* wto_nav_path_result must quote (0 when the slot or request is invalid).
|
||||
*
|
||||
* With a traffic group the search pays more for polygons that other paths of the group (finished
|
||||
* within trafficHoldSec) pass through, and its own result counts for the next ones. The slot's
|
||||
* previous path stops counting as soon as the new request arrives.
|
||||
*/
|
||||
uint32_t wto_nav_path_request(uint32_t slot, const WtoNavPathRequest *request);
|
||||
|
||||
/* Result of `ticket` in `slot`; `points` receives up to `max_points` xyz triples. */
|
||||
void wto_nav_path_result(uint32_t slot, uint32_t ticket, float *points, int max_points, WtoNavPathResult *result);
|
||||
|
||||
/*
|
||||
* Advances queued searches for at most `budget_us` microseconds (one call per game frame) and
|
||||
* expires dynamic costs whose end time is before `now` (script time, seconds).
|
||||
*/
|
||||
void wto_nav_pump(double budget_us, float now);
|
||||
|
||||
int wto_nav_probe(uint32_t tier, uint32_t filter, const float pos[3], float snap_m, float wall_radius_m, WtoNavProbe *probe);
|
||||
|
||||
/*
|
||||
* Walks the mesh surface from `start` toward `goal`. Returns 1 when nothing blocks the way,
|
||||
* 0 when a mesh edge does (`hit_frac` and `hit` tell where), -1 when `start` is off the mesh.
|
||||
*/
|
||||
int wto_nav_raycast(uint32_t tier, uint32_t filter, float snap_m, const float start[3], const float goal[3],
|
||||
float *hit_frac, float hit[3]);
|
||||
|
||||
/* Closest point of the tier's mesh within `radius_m` (horizontally, any height); 1 if found. */
|
||||
int wto_nav_nearest(uint32_t tier, uint32_t filter, float radius_m, const float pos[3], float out[3]);
|
||||
|
||||
/*
|
||||
* Adds a circle that multiplies path costs by `cost_mul` until script time `until`; a circle
|
||||
* close to an existing one updates it. Returns the number of live circles.
|
||||
*/
|
||||
uint32_t wto_nav_add_dynamic(const float pos[3], float radius_m, float cost_mul, float until);
|
||||
|
||||
void wto_nav_get_stats(WtoNavStats *stats);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
Output: <Out>\wto_ws.dll (default build\native). Static C runtime (/MT), so the DLL needs
|
||||
nothing but the system's ws2_32.dll. MinHook comes from native\third_party\minhook (BSD-2).
|
||||
The ground AI navigation engine (native\wto-nav) links upstream Detour from
|
||||
native\third_party\recastnavigation (zlib), compiled separately at its own warning level.
|
||||
#>
|
||||
param([string]$Out = (Join-Path $PSScriptRoot '..\..\build\native'))
|
||||
$ErrorActionPreference = 'Stop'
|
||||
@@ -16,19 +18,34 @@ $vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat'
|
||||
|
||||
$src = Join-Path $PSScriptRoot 'src'
|
||||
$mh = Join-Path $PSScriptRoot '..\third_party\minhook'
|
||||
$nav = Join-Path $PSScriptRoot '..\wto-nav'
|
||||
$dt = Join-Path $PSScriptRoot '..\third_party\recastnavigation\Detour'
|
||||
New-Item -ItemType Directory -Force $Out | Out-Null
|
||||
$obj = Join-Path $Out 'obj'
|
||||
New-Item -ItemType Directory -Force $obj | Out-Null
|
||||
$dtObj = Join-Path $obj 'detour'
|
||||
New-Item -ItemType Directory -Force $dtObj | Out-Null
|
||||
|
||||
$sources = @(
|
||||
function Quote($paths) { $paths | ForEach-Object { '"' + (Resolve-Path $_) + '"' } }
|
||||
|
||||
$sources = Quote @(
|
||||
"$src\dll_main.c", "$src\hook_config.c", "$src\redirect_rules.c", "$src\resolver_hooks.c", "$src\connection_hooks.c",
|
||||
"$src\local_mp_core.c", "$src\local_mp_values.c", "$src\local_mp_players.c", "$src\local_mp_loadout.c", "$src\local_mp_actions.c", "$src\local_mp_awards.c", "$src\local_mp_kills.c", "$src\local_mp_events.c", "$src\local_mp_scores.c", "$src\local_mp_nuke.c", "$src\local_mp_support.c",
|
||||
"$src\local_mp_damage_notifications.c", "$src\local_mp_ground_part_feedback.c", "$src\local_mp_hit_feedback.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_zones.c", "$src\local_mp_captures.c", "$src\local_mp_air_ai_sync.c",
|
||||
"$src\local_mp_damage_notifications.c", "$src\local_mp_ground_part_feedback.c", "$src\local_mp_hit_feedback.c", "$src\local_mp_air_events.c", "$src\local_mp_ground_ai.c", "$src\local_mp_nav.c", "$src\local_mp_zones.c", "$src\local_mp_captures.c", "$src\local_mp_air_ai_sync.c",
|
||||
"$nav\wto_nav_runtime.cpp", "$nav\wto_nav_paths.cpp", "$nav\wto_nav_queries.cpp", "$nav\wto_nav_protocol.c",
|
||||
"$mh\src\hook.c", "$mh\src\buffer.c", "$mh\src\trampoline.c", "$mh\src\hde\hde64.c"
|
||||
) | ForEach-Object { '"' + (Resolve-Path $_) + '"' }
|
||||
)
|
||||
$detourSources = Quote (Get-ChildItem "$dt\Source\*.cpp").FullName
|
||||
$detourObjects = (Get-ChildItem "$dt\Source\*.cpp") | ForEach-Object { '"' + (Join-Path $dtObj ($_.BaseName + '.obj')) + '"' }
|
||||
# Every translation unit that sees dtQueryFilter must agree on its layout (wto_nav_runtime.cpp).
|
||||
$detourFlags = "/DDT_VIRTUAL_QUERYFILTER /I`"$dt\Include`""
|
||||
|
||||
$command = "`"$vcvars`" >nul && cl /nologo /LD /O2 /MT /W4 /wd4100 /D_CRT_SECURE_NO_WARNINGS /DWIN32_LEAN_AND_MEAN " +
|
||||
"/I`"$mh\include`" /Fo`"$obj\\`" $($sources -join ' ') /Fe`"$Out\wto_ws.dll`" " +
|
||||
$detour = "`"$vcvars`" >nul && cl /nologo /c /O2 /MT /EHsc /W3 $detourFlags /Fo`"$dtObj\\`" $($detourSources -join ' ')"
|
||||
cmd /c $detour
|
||||
if ($LASTEXITCODE -ne 0) { throw "cl (Detour) failed with $LASTEXITCODE" }
|
||||
|
||||
$command = "`"$vcvars`" >nul && cl /nologo /LD /O2 /MT /EHsc /W4 /wd4100 /D_CRT_SECURE_NO_WARNINGS /DWIN32_LEAN_AND_MEAN $detourFlags " +
|
||||
"/I`"$mh\include`" /I`"$nav`" /Fo`"$obj\\`" $($sources -join ' ') $($detourObjects -join ' ') /Fe`"$Out\wto_ws.dll`" " +
|
||||
"/link /DEF:`"$src\wto_ws.def`" ws2_32.lib"
|
||||
cmd /c $command
|
||||
if ($LASTEXITCODE -ne 0) { throw "cl failed with $LASTEXITCODE" }
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
* exe.size_of_image=0x...
|
||||
* native.<name>=<value> what the LocalMP modules need from the executable: RVAs of
|
||||
* functions and globals, structure offsets (local_mp_values.c)
|
||||
* nav.dir=<folder> optional, UTF-8: where the ground AI finds <level>.wtonav packs
|
||||
*
|
||||
* wto_ws.log: which host names were answered locally and which connections were redirected or
|
||||
* refused, so a run shows every address the game tried (the audit handover 6.2 asks for).
|
||||
@@ -32,6 +33,7 @@ typedef struct NativeValue {
|
||||
} NativeValue;
|
||||
|
||||
static wchar_t g_folder[MAX_PATH];
|
||||
static wchar_t g_nav_dir[MAX_PATH];
|
||||
static CRITICAL_SECTION g_log_lock;
|
||||
static FILE *g_log;
|
||||
static int g_log_enabled = 1;
|
||||
@@ -87,10 +89,16 @@ static void read_native_value(const char *line)
|
||||
g_native_count++;
|
||||
}
|
||||
|
||||
static void read_nav_dir(const char *utf8)
|
||||
{
|
||||
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8, -1, g_nav_dir, MAX_PATH) == 0)
|
||||
g_nav_dir[0] = L'\0';
|
||||
}
|
||||
|
||||
static void read_settings(void)
|
||||
{
|
||||
wchar_t path[MAX_PATH];
|
||||
char line[160];
|
||||
char line[1024];
|
||||
FILE *file;
|
||||
if (_snwprintf_s(path, MAX_PATH, _TRUNCATE, L"%swto_ws.cfg", g_folder) < 0)
|
||||
return;
|
||||
@@ -108,10 +116,17 @@ static void read_settings(void)
|
||||
parse_value(line + 18, &g_exe_size_of_image);
|
||||
else if (strncmp(line, NATIVE_PREFIX, sizeof(NATIVE_PREFIX) - 1) == 0)
|
||||
read_native_value(line);
|
||||
else if (strncmp(line, "nav.dir=", 8) == 0)
|
||||
read_nav_dir(line + 8);
|
||||
}
|
||||
fclose(file);
|
||||
}
|
||||
|
||||
const wchar_t *config_nav_dir(void)
|
||||
{
|
||||
return g_nav_dir;
|
||||
}
|
||||
|
||||
int config_native_value(const char *name, int64_t *value)
|
||||
{
|
||||
size_t i;
|
||||
|
||||
@@ -13,3 +13,5 @@ void describe_address(const struct sockaddr *name, int length, char *text, size_
|
||||
int config_native_value(const char *name, int64_t *value);
|
||||
/* Whether the settings were resolved for the executable this process runs (PE time stamp and size). */
|
||||
int config_native_matches_executable(void);
|
||||
/* Folder of the ground AI navigation packs (wto_ws.cfg "nav.dir="); empty when not configured. */
|
||||
const wchar_t *config_nav_dir(void);
|
||||
@@ -19,6 +19,7 @@
|
||||
|
||||
#define SCRIPT_READY_ACTION "wtoGroundAiScriptReady"
|
||||
#define DRIVE_CONTROL_ACTION "wtoGroundAiDriveControl"
|
||||
#define NAV_ACTION "wtoNav"
|
||||
|
||||
typedef void (__fastcall *MissionActionFn)(const char *name, const void *blk);
|
||||
typedef uint8_t *(__fastcall *AsGroundModelFn)(uint8_t *unit);
|
||||
@@ -139,6 +140,11 @@ static void __fastcall hook_mission_action(const char *name, const void *blk)
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (name != NULL && strcmp(name, NAV_ACTION) == 0) {
|
||||
/* The script's request block doubles as the reply (local_mp_nav.c). */
|
||||
local_mp_nav_request((void *)blk);
|
||||
return;
|
||||
}
|
||||
if (name == NULL || strcmp(name, DRIVE_CONTROL_ACTION) != 0) {
|
||||
orig_mission_action(name, blk);
|
||||
return;
|
||||
@@ -162,6 +168,8 @@ void local_mp_ground_ai_update(float dt)
|
||||
if (orig_mission_action == NULL)
|
||||
return;
|
||||
hosting = local_mp_is_host();
|
||||
if (!hosting)
|
||||
local_mp_nav_session_ended();
|
||||
AcquireSRWLockExclusive(&control_lock);
|
||||
for (i = 0; i < sizeof(controls) / sizeof(controls[0]); i++) {
|
||||
GroundAiDriveControl *control = &controls[i];
|
||||
|
||||
@@ -122,3 +122,7 @@ int install_local_mp_air_event_hooks(void);
|
||||
int install_local_mp_ground_ai_hooks(void);
|
||||
void local_mp_ground_ai_update(float dt);
|
||||
int install_local_mp_air_ai_sync_hooks(void);
|
||||
|
||||
/* "wtoNav" requests of the ground AI script and the battle's navigation pack (local_mp_nav.c). */
|
||||
void local_mp_nav_request(void *blk);
|
||||
void local_mp_nav_session_ended(void);
|
||||
@@ -0,0 +1,321 @@
|
||||
/*
|
||||
* "wtoNav" requests of the ground AI script (call_mission_action, local_mp_ground_ai.c) and the
|
||||
* battle's navigation pack (native/wto-nav). The script fills a DataBlock with the request and this
|
||||
* module answers synchronously into the same block. The queries are the shared protocol of
|
||||
* native/wto-nav/wto_nav_protocol.h; this module adds the ops that depend on the battle:
|
||||
*
|
||||
* op=prefetch -> state=started|skipped, level, reason (battle still loading)
|
||||
* op=load_map allowFallback="0|1", plus the costs and tuning of the protocol
|
||||
* -> state=loaded|fallback|failed, fingerprint=match|mismatch|unknown, level,
|
||||
* reason, tiers, covers
|
||||
* op=unload_map -> ok
|
||||
*
|
||||
* Request values are strings: the script only uses the DataBlock string add it already relies on.
|
||||
* Replies are ints and strings written with the setters local_mp_awards resolves.
|
||||
*
|
||||
* The level comes from the mission settings (customBots wtoLevel, written by the local server),
|
||||
* the pack folder from wto_ws.cfg (nav.dir). The script asks for a prefetch while the battle
|
||||
* loads, so the pack is read on a background thread. Whether the battle uses the pack, falls back
|
||||
* to stock road paths or refuses to drive is decided by the first load_map of the battle and kept
|
||||
* until unload_map or the end of the session; it never changes in the middle of a battle.
|
||||
*/
|
||||
#include "hook_config.h"
|
||||
#include "local_mp_internal.h"
|
||||
#include "local_mp_offsets.h"
|
||||
#include "local_mp_values.h"
|
||||
#include "wto_nav_protocol.h"
|
||||
#include "wto_nav_runtime.h"
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define NAV_LEVEL_MAX 64
|
||||
|
||||
typedef void (__fastcall *BlkSetStrFn)(void *blk, const char *name, const char *value);
|
||||
typedef void (__fastcall *BlkSetIntFn)(void *blk, const char *name, const int32_t *value);
|
||||
typedef void (__fastcall *BlkToOwnedFn)(void *blk);
|
||||
|
||||
typedef enum NavDecision {
|
||||
NAV_UNDECIDED = 0,
|
||||
NAV_LOADED,
|
||||
NAV_FALLBACK,
|
||||
NAV_FAILED,
|
||||
} NavDecision;
|
||||
|
||||
typedef struct NavBattle {
|
||||
NavDecision decision;
|
||||
char level[NAV_LEVEL_MAX];
|
||||
char fingerprint[16];
|
||||
char reason[96];
|
||||
uint32_t tiers;
|
||||
uint32_t covers;
|
||||
} NavBattle;
|
||||
|
||||
static NavBattle g_battle;
|
||||
static SRWLOCK g_battle_lock = SRWLOCK_INIT;
|
||||
static LONG g_missing_values_logged;
|
||||
|
||||
static int values_ready(void)
|
||||
{
|
||||
if (g_lmp.blk_set_str && g_lmp.blk_set_int && g_lmp.blk_to_owned &&
|
||||
g_lmp_datablock_get_str && g_local_mp_mission_settings)
|
||||
return 1;
|
||||
if (InterlockedExchange(&g_missing_values_logged, 1) == 0)
|
||||
log_line("WTO_NAV|UNAVAILABLE|reason=DataBlock setters of local_mp_awards not resolved");
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void set_str(void *blk, const char *name, const char *value)
|
||||
{
|
||||
((BlkSetStrFn)g_lmp.blk_set_str)(blk, name, value ? value : "");
|
||||
}
|
||||
|
||||
/* Integer setters expect an owned DataBlock (as in local_mp_awards.c). */
|
||||
static void set_int(void *blk, const char *name, int32_t value)
|
||||
{
|
||||
if (*(int32_t *)((uint8_t *)blk + LMP_BLK_OFF_OWNED_STATE) != -1)
|
||||
((BlkToOwnedFn)g_lmp.blk_to_owned)(blk);
|
||||
((BlkSetIntFn)g_lmp.blk_set_int)(blk, name, &value);
|
||||
}
|
||||
|
||||
static long get_long(const void *blk, const char *name, long def)
|
||||
{
|
||||
const char *text = g_lmp_datablock_get_str(blk, name, "");
|
||||
char *end;
|
||||
long value;
|
||||
if (text == NULL || text[0] == '\0')
|
||||
return def;
|
||||
value = strtol(text, &end, 10);
|
||||
return *end == '\0' ? value : def;
|
||||
}
|
||||
|
||||
static const char *block_get_str(const void *blk, const char *name)
|
||||
{
|
||||
const char *text = g_lmp_datablock_get_str(blk, name, "");
|
||||
return text ? text : "";
|
||||
}
|
||||
|
||||
static WtoNavBlock game_block(void *blk)
|
||||
{
|
||||
WtoNavBlock b;
|
||||
b.blk = blk;
|
||||
b.get_str = block_get_str;
|
||||
b.set_str = set_str;
|
||||
b.set_int = set_int;
|
||||
return b;
|
||||
}
|
||||
|
||||
static void hex20(const uint8_t *sha1, char out[41])
|
||||
{
|
||||
static const char digits[] = "0123456789abcdef";
|
||||
int i;
|
||||
for (i = 0; i < 20; i++) {
|
||||
out[i * 2] = digits[sha1[i] >> 4];
|
||||
out[i * 2 + 1] = digits[sha1[i] & 15];
|
||||
}
|
||||
out[40] = '\0';
|
||||
}
|
||||
|
||||
/* "levels/avg_berlin.bin" -> "avg_berlin"; only names the bake could have produced. */
|
||||
static int battle_level(char out[NAV_LEVEL_MAX])
|
||||
{
|
||||
const char *path = g_lmp_datablock_get_str(g_local_mp_mission_settings + LMP_MIS_OFF_CUSTOM_BOTS, "wtoLevel", "");
|
||||
const char *name, *dot;
|
||||
size_t len, i;
|
||||
|
||||
if (path == NULL || path[0] == '\0')
|
||||
return 0;
|
||||
name = strrchr(path, '/');
|
||||
name = name ? name + 1 : path;
|
||||
dot = strrchr(name, '.');
|
||||
len = dot ? (size_t)(dot - name) : strlen(name);
|
||||
if (len == 0 || len >= NAV_LEVEL_MAX)
|
||||
return 0;
|
||||
for (i = 0; i < len; i++) {
|
||||
const char c = name[i];
|
||||
if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_'))
|
||||
return 0;
|
||||
out[i] = c;
|
||||
}
|
||||
out[len] = '\0';
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* <game>\levels\<level>.bin, the game folder being the parent of the executable's win64 folder. */
|
||||
static int level_file_path(const char *level, wchar_t *out, size_t out_count)
|
||||
{
|
||||
wchar_t exe[MAX_PATH];
|
||||
wchar_t *slash;
|
||||
DWORD length = GetModuleFileNameW(NULL, exe, MAX_PATH);
|
||||
int i;
|
||||
|
||||
if (length == 0 || length >= MAX_PATH)
|
||||
return 0;
|
||||
for (i = 0; i < 2; i++) {
|
||||
slash = wcsrchr(exe, L'\\');
|
||||
if (slash == NULL)
|
||||
return 0;
|
||||
*slash = L'\0';
|
||||
}
|
||||
return _snwprintf_s(out, out_count, _TRUNCATE, L"%s\\levels\\%S.bin", exe, level) > 0;
|
||||
}
|
||||
|
||||
/*
|
||||
* Pack and level paths of the battle in the mission settings; on failure `reason` says why.
|
||||
* `level_path` is left empty when the level file cannot be located (fingerprint unknown).
|
||||
*/
|
||||
static int battle_paths(char level[NAV_LEVEL_MAX], wchar_t pack[MAX_PATH], wchar_t level_path[MAX_PATH],
|
||||
char *reason, size_t reason_size)
|
||||
{
|
||||
const wchar_t *dir = config_nav_dir();
|
||||
if (!battle_level(level)) {
|
||||
level[0] = '\0';
|
||||
snprintf(reason, reason_size, "battle level unknown (customBots wtoLevel)");
|
||||
return 0;
|
||||
}
|
||||
if (dir[0] == L'\0') {
|
||||
snprintf(reason, reason_size, "no pack folder (wto_ws.cfg nav.dir)");
|
||||
return 0;
|
||||
}
|
||||
if (_snwprintf_s(pack, MAX_PATH, _TRUNCATE, L"%s\\%S.wtonav", dir, level) <= 0) {
|
||||
snprintf(reason, reason_size, "pack path too long");
|
||||
return 0;
|
||||
}
|
||||
if (!level_file_path(level, level_path, MAX_PATH))
|
||||
level_path[0] = L'\0';
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void log_loaded(const WtoNavLoadInfo *info)
|
||||
{
|
||||
char expected[41], actual[41];
|
||||
hex20(info->packSha1, expected);
|
||||
hex20(info->levelSha1, actual);
|
||||
if (info->fingerprintKnown && !info->fingerprintMatch)
|
||||
log_line("WTO_NAV|FINGERPRINT_MISMATCH|level=%s|expected=%s|actual=%s", g_battle.level, expected, actual);
|
||||
log_line("WTO_NAV|LOADED|level=%s|fingerprint=%s|tiers=%u|covers=%u|polys=%u/%u/%u|prefetched=%d|readMs=%.0f|waitMs=%.1f",
|
||||
g_battle.level, g_battle.fingerprint, info->tiers, info->covers,
|
||||
info->polys[0], info->polys[1], info->polys[2], info->prefetched, info->readMs, info->waitMs);
|
||||
}
|
||||
|
||||
static void decide_locked(const void *blk, int allow_fallback)
|
||||
{
|
||||
wchar_t pack[MAX_PATH], level_path[MAX_PATH];
|
||||
WtoNavLoadInfo info;
|
||||
WtoNavBlock request = game_block((void *)blk);
|
||||
|
||||
memset(&info, 0, sizeof(info));
|
||||
info.result = WTO_NAV_LOAD_MISSING;
|
||||
if (battle_paths(g_battle.level, pack, level_path, g_battle.reason, sizeof(g_battle.reason))) {
|
||||
wto_nav_protocol_setup(&request);
|
||||
wto_nav_load(pack, level_path[0] ? level_path : NULL, &info);
|
||||
if (info.result != WTO_NAV_LOAD_OK)
|
||||
snprintf(g_battle.reason, sizeof(g_battle.reason), "%s", info.detail);
|
||||
}
|
||||
|
||||
if (info.result == WTO_NAV_LOAD_OK && g_battle.reason[0] == '\0') {
|
||||
g_battle.decision = NAV_LOADED;
|
||||
g_battle.tiers = info.tiers;
|
||||
g_battle.covers = info.covers;
|
||||
snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "%s",
|
||||
!info.fingerprintKnown ? "unknown" : info.fingerprintMatch ? "match" : "mismatch");
|
||||
log_loaded(&info);
|
||||
return;
|
||||
}
|
||||
snprintf(g_battle.fingerprint, sizeof(g_battle.fingerprint), "unknown");
|
||||
g_battle.decision = allow_fallback ? NAV_FALLBACK : NAV_FAILED;
|
||||
if (allow_fallback)
|
||||
log_line("WTO_NAV|FALLBACK_STOCK_NAV|level=%s|reason=%s", g_battle.level, g_battle.reason);
|
||||
else
|
||||
log_line("WTO_NAV|LOAD_FAILED_NO_FALLBACK|level=%s|reason=%s", g_battle.level, g_battle.reason);
|
||||
}
|
||||
|
||||
static void prefetch(void *blk)
|
||||
{
|
||||
wchar_t pack[MAX_PATH], level_path[MAX_PATH];
|
||||
char level[NAV_LEVEL_MAX], reason[96] = "";
|
||||
int started = 0;
|
||||
|
||||
AcquireSRWLockExclusive(&g_battle_lock);
|
||||
if (g_battle.decision != NAV_UNDECIDED) {
|
||||
snprintf(reason, sizeof(reason), "battle already decided");
|
||||
level[0] = '\0';
|
||||
} else if (battle_paths(level, pack, level_path, reason, sizeof(reason))) {
|
||||
wto_nav_prefetch(pack, level_path);
|
||||
started = 1;
|
||||
log_line("WTO_NAV|PREFETCH|level=%s", level);
|
||||
}
|
||||
ReleaseSRWLockExclusive(&g_battle_lock);
|
||||
set_str(blk, "state", started ? "started" : "skipped");
|
||||
set_str(blk, "level", level);
|
||||
set_str(blk, "reason", reason);
|
||||
}
|
||||
|
||||
static void load_map(void *blk)
|
||||
{
|
||||
static const char *const STATES[] = { "", "loaded", "fallback", "failed" };
|
||||
const int allow_fallback = get_long(blk, "allowFallback", 1) != 0;
|
||||
|
||||
AcquireSRWLockExclusive(&g_battle_lock);
|
||||
if (g_battle.decision == NAV_UNDECIDED)
|
||||
decide_locked(blk, allow_fallback);
|
||||
set_str(blk, "state", STATES[g_battle.decision]);
|
||||
set_str(blk, "fingerprint", g_battle.fingerprint);
|
||||
set_str(blk, "level", g_battle.level);
|
||||
set_str(blk, "reason", g_battle.reason);
|
||||
set_int(blk, "tiers", (int32_t)g_battle.tiers);
|
||||
set_int(blk, "covers", (int32_t)g_battle.covers);
|
||||
ReleaseSRWLockExclusive(&g_battle_lock);
|
||||
}
|
||||
|
||||
static void unload_locked(const char *why)
|
||||
{
|
||||
if (g_battle.decision == NAV_UNDECIDED)
|
||||
return;
|
||||
if (wto_nav_is_loaded()) {
|
||||
WtoNavStats stats;
|
||||
wto_nav_get_stats(&stats);
|
||||
log_line("WTO_NAV|UNLOADED|level=%s|why=%s|paths=%u|failures=%u|avgUs=%.0f|maxUs=%.0f|maxFrames=%u|pumpMaxUs=%.0f|meshQueries=%u|cornersMoved=%u",
|
||||
g_battle.level, why, stats.queries, stats.failures,
|
||||
stats.queries ? stats.totalMicros / stats.queries : 0.0, stats.maxMicros,
|
||||
stats.maxFrames, stats.pumpMaxMicros, stats.meshQueries, stats.cornersMoved);
|
||||
wto_nav_unload();
|
||||
}
|
||||
memset(&g_battle, 0, sizeof(g_battle));
|
||||
}
|
||||
|
||||
void local_mp_nav_request(void *blk)
|
||||
{
|
||||
WtoNavBlock request;
|
||||
const char *op;
|
||||
|
||||
if (blk == NULL || !values_ready())
|
||||
return;
|
||||
op = g_lmp_datablock_get_str(blk, "op", "");
|
||||
if (op == NULL)
|
||||
return;
|
||||
request = game_block(blk);
|
||||
if (wto_nav_protocol_query(&request, op))
|
||||
return;
|
||||
if (strcmp(op, "prefetch") == 0) {
|
||||
prefetch(blk);
|
||||
} else if (strcmp(op, "load_map") == 0) {
|
||||
load_map(blk);
|
||||
} else if (strcmp(op, "unload_map") == 0) {
|
||||
AcquireSRWLockExclusive(&g_battle_lock);
|
||||
unload_locked("battle ended");
|
||||
ReleaseSRWLockExclusive(&g_battle_lock);
|
||||
set_int(blk, "ok", 1);
|
||||
} else {
|
||||
log_line("WTO_NAV|BAD_REQUEST|op=%s", op);
|
||||
}
|
||||
}
|
||||
|
||||
void local_mp_nav_session_ended(void)
|
||||
{
|
||||
if (TryAcquireSRWLockExclusive(&g_battle_lock)) {
|
||||
unload_locked("session ended");
|
||||
ReleaseSRWLockExclusive(&g_battle_lock);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user