feat(ground-ai): add offline tank navmesh and cover baking prototype
Add Stage 0 offline map geometry extraction and Recast/Detour baking tools for ground AI navigation on feat/tank-ai-nav: - Vendor upstream recastnavigation Recast and Detour sources (zlib license) under native/third_party/recastnavigation. - Define shared .wtogeo and .wtonav binary layouts in native/wto-nav/wto_nav_format.h. - Add mission-bounds.mts to collect union ground battle areas, spawns, and capture zones across mission templates. - Add Rust extractor (tools/navgen/extract) using wt-unpack and config/rendinst_dmg.blk destructionImpulse thresholds to classify hard solids, bridges, crushable objects, and tree trunks in Dagor world space. - Add multi-threaded MSVC C++ baker (tools/navgen/bake) producing 3 vehicle-width tiled Detour navmeshes, island pruning, dual-height voxel tank covers (full, hull-down, corner peek, retreat-verified), 8m tactical grids, and spawn-to-cap connectivity checks. - Add zero-dependency PNG top-down preview renderer (tools/navgen/render-preview.py). Verified: Rust release build (0 warnings), MSVC x64 baker build (0 warnings), root typecheck, and end-to-end extraction/baking/100% 3-tier connectivity and preview rendering on avg_berlin, avg_poland, and avg_hurtgen (2.61.0.58).
This commit is contained in:
1 parent
688406bb76
commit
842ee23fa4
40 files changed
+22824
No files matched your search
@@ -18,6 +18,7 @@ aces*.exe
|
|||||||
/apps/launcher/out/
|
/apps/launcher/out/
|
||||||
**/dist/
|
**/dist/
|
||||||
**/unpacked/
|
**/unpacked/
|
||||||
|
tools/navgen/extract/target/
|
||||||
|
|
||||||
# Node
|
# Node
|
||||||
node_modules/
|
node_modules/
|
||||||
|
|||||||
@@ -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,143 @@
|
|||||||
|
/*
|
||||||
|
* 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 1u
|
||||||
|
|
||||||
|
#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,
|
||||||
|
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,
|
||||||
|
WTO_FLAG_BLOCKED = 0x10
|
||||||
|
};
|
||||||
|
|
||||||
|
/* 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) */
|
||||||
|
};
|
||||||
|
|
||||||
|
/* 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;
|
||||||
|
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;
|
||||||
|
|
||||||
|
/* Baked tank cover point (48 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; /* Measured hard-obstacle height above ground at cover */
|
||||||
|
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
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,32 @@
|
|||||||
|
<#
|
||||||
|
Build tools/navgen/bake/wto_navgen_bake.exe using MSVC x64 C++ (Visual Studio).
|
||||||
|
Links vendored upstream Recast + Detour (zlib license) from native/third_party/recastnavigation.
|
||||||
|
#>
|
||||||
|
param([string]$Out = (Join-Path $PSScriptRoot '..\..\..\build\navgen'))
|
||||||
|
$ErrorActionPreference = 'Stop'
|
||||||
|
|
||||||
|
$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 x64 C++ tools was not found' }
|
||||||
|
$vcvars = Join-Path $vs 'VC\Auxiliary\Build\vcvars64.bat'
|
||||||
|
|
||||||
|
$root = Resolve-Path (Join-Path $PSScriptRoot '..\..\..')
|
||||||
|
$rc = Join-Path $root 'native\third_party\recastnavigation\Recast'
|
||||||
|
$dt = Join-Path $root 'native\third_party\recastnavigation\Detour'
|
||||||
|
$navInc = Join-Path $root 'native\wto-nav'
|
||||||
|
New-Item -ItemType Directory -Force $Out | Out-Null
|
||||||
|
$obj = Join-Path $Out 'obj'
|
||||||
|
New-Item -ItemType Directory -Force $obj | Out-Null
|
||||||
|
|
||||||
|
$sources = @(
|
||||||
|
(Join-Path $PSScriptRoot 'bake.cpp')
|
||||||
|
) + (Get-ChildItem "$rc\Source\*.cpp").FullName + (Get-ChildItem "$dt\Source\*.cpp").FullName
|
||||||
|
$quoted = $sources | ForEach-Object { '"' + $_ + '"' }
|
||||||
|
|
||||||
|
$exe = Join-Path $Out 'wto_navgen_bake.exe'
|
||||||
|
$cmd = "`"$vcvars`" >nul && cl /nologo /O2 /EHsc /std:c++17 /MT /W3 /D_CRT_SECURE_NO_WARNINGS " +
|
||||||
|
"/I`"$rc\Include`" /I`"$dt\Include`" /I`"$navInc`" " +
|
||||||
|
"/Fo`"$obj\\`" $($quoted -join ' ') /Fe`"$exe`""
|
||||||
|
cmd /c $cmd
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "cl failed with exit code $LASTEXITCODE" }
|
||||||
|
Write-Output $exe
|
||||||
Generated
+534
@@ -0,0 +1,534 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "adler2"
|
||||||
|
version = "2.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstream"
|
||||||
|
version = "1.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "85c097ce94629611e0a15ef1078a2fe2ce3b4a0f4b44708e85eeb09dd5f188eb"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"anstyle-parse",
|
||||||
|
"anstyle-query",
|
||||||
|
"anstyle-wincon",
|
||||||
|
"colorchoice",
|
||||||
|
"is_terminal_polyfill",
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle"
|
||||||
|
version = "1.0.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6c7a9e344b352bef7873e51ff425c2f90d5aa2a252db2b84289c93ff30beb3d7"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-parse"
|
||||||
|
version = "1.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a0571a23d2188b4aae7adc1df454cc81d6232cf37674fa717ac119f6c74d0dc1"
|
||||||
|
dependencies = [
|
||||||
|
"utf8parse",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-query"
|
||||||
|
version = "1.1.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "76a5cf9d05ffa9c878c447b33b069605e890ebcd36d2761f86367873c2ecaa7f"
|
||||||
|
dependencies = [
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anstyle-wincon"
|
||||||
|
version = "3.0.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2c2d00c1b2d84cef823d89d4da02ad8ff1e76c969e029da990b40f16dc834221"
|
||||||
|
dependencies = [
|
||||||
|
"anstyle",
|
||||||
|
"once_cell_polyfill",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "anyhow"
|
||||||
|
version = "1.0.105"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bcn-decode"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3a3d5cf71fc14b37654892fc02d25b45ddca03d4245e352510e3c55bdc5cda1f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bitflags"
|
||||||
|
version = "2.13.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block-buffer"
|
||||||
|
version = "0.10.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "byteorder"
|
||||||
|
version = "1.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "34fb07aac3b9f547c7af8dc897dfe73c10847b6c71130c364bdd7891d979c816"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cfg-if"
|
||||||
|
version = "1.0.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap"
|
||||||
|
version = "4.6.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "50066ca966813ca8957ee15361752f19424a8ff620dbe9c8993d9f99d99b04b3"
|
||||||
|
dependencies = [
|
||||||
|
"clap_builder",
|
||||||
|
"clap_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_builder"
|
||||||
|
version = "4.6.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a0ed97c96ef4efb3cc84e09fa388df4463e7cc3224ec38d7b1d9e45749333590"
|
||||||
|
dependencies = [
|
||||||
|
"anstream",
|
||||||
|
"anstyle",
|
||||||
|
"clap_lex",
|
||||||
|
"strsim",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_derive"
|
||||||
|
version = "4.6.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b4c174f11f949b9ca8c60580925e282b9cbd5454750e506f08648b2038080cd7"
|
||||||
|
dependencies = [
|
||||||
|
"heck",
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "clap_lex"
|
||||||
|
version = "1.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e0921b3876b3a1df8a1c9f912e7f94342458022c2e84288015893d83c4d62a79"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "colorchoice"
|
||||||
|
version = "1.0.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8f7f11958434c85b6efac08f8299dc08bd263184ce080232e2168940cda4368e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crc32fast"
|
||||||
|
version = "1.5.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crypto-common"
|
||||||
|
version = "0.1.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
"typenum",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "digest"
|
||||||
|
version = "0.10.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
||||||
|
dependencies = [
|
||||||
|
"block-buffer",
|
||||||
|
"crypto-common",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "equivalent"
|
||||||
|
version = "1.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "fdeflate"
|
||||||
|
version = "0.3.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c"
|
||||||
|
dependencies = [
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "flate2"
|
||||||
|
version = "1.1.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
|
||||||
|
dependencies = [
|
||||||
|
"crc32fast",
|
||||||
|
"miniz_oxide 0.9.1",
|
||||||
|
"zlib-rs",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "foldhash"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "generic-array"
|
||||||
|
version = "0.14.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
||||||
|
dependencies = [
|
||||||
|
"typenum",
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "hashbrown"
|
||||||
|
version = "0.17.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "heck"
|
||||||
|
version = "0.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "indexmap"
|
||||||
|
version = "2.14.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"
|
||||||
|
dependencies = [
|
||||||
|
"equivalent",
|
||||||
|
"hashbrown",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "is_terminal_polyfill"
|
||||||
|
version = "1.70.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "itoa"
|
||||||
|
version = "1.0.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lewton"
|
||||||
|
version = "0.10.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "777b48df9aaab155475a83a7df3070395ea1ac6902f5cd062b8f2b028075c030"
|
||||||
|
dependencies = [
|
||||||
|
"byteorder",
|
||||||
|
"tinyvec",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libc"
|
||||||
|
version = "0.2.191"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lztans"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4bad6ebd0a522f78e2889049a78d31ec62cd646a37524215fa00ea548b20bed0"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "md-5"
|
||||||
|
version = "0.10.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"digest",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "memchr"
|
||||||
|
version = "2.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "memmap2"
|
||||||
|
version = "0.9.12"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "miniz_oxide"
|
||||||
|
version = "0.8.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316"
|
||||||
|
dependencies = [
|
||||||
|
"adler2",
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "miniz_oxide"
|
||||||
|
version = "0.9.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
||||||
|
dependencies = [
|
||||||
|
"adler2",
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "once_cell_polyfill"
|
||||||
|
version = "1.70.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "png"
|
||||||
|
version = "0.18.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"crc32fast",
|
||||||
|
"fdeflate",
|
||||||
|
"flate2",
|
||||||
|
"miniz_oxide 0.8.9",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proc-macro2"
|
||||||
|
version = "1.0.107"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
|
||||||
|
dependencies = [
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quote"
|
||||||
|
version = "1.0.47"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ruzstd"
|
||||||
|
version = "0.8.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a7c1c839d570d835527c9a5e4db7cb2198683a988cb9d7293fc8674e6bd58fc8"
|
||||||
|
dependencies = [
|
||||||
|
"twox-hash",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"
|
||||||
|
dependencies = [
|
||||||
|
"serde_core",
|
||||||
|
"serde_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_core"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"
|
||||||
|
dependencies = [
|
||||||
|
"serde_derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_derive"
|
||||||
|
version = "1.0.229"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "serde_json"
|
||||||
|
version = "1.0.154"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6"
|
||||||
|
dependencies = [
|
||||||
|
"foldhash",
|
||||||
|
"indexmap",
|
||||||
|
"itoa",
|
||||||
|
"memchr",
|
||||||
|
"serde",
|
||||||
|
"serde_core",
|
||||||
|
"zmij",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "simd-adler32"
|
||||||
|
version = "0.3.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "strsim"
|
||||||
|
version = "0.11.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "3.0.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tinyvec"
|
||||||
|
version = "1.13.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "twox-hash"
|
||||||
|
version = "2.1.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "86a801b3cea342a06d468c8710662aa29e5e05e4f5c0d62f00bbb7f2ad7941c2"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typenum"
|
||||||
|
version = "1.20.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-ident"
|
||||||
|
version = "1.0.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "utf8parse"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "version_check"
|
||||||
|
version = "0.9.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-link"
|
||||||
|
version = "0.101.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f4e57b2aae53a240c62b65069a63eaf8d5fa747f5d0d8e670c5210a98847bce4"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.101.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "eed2df9f5f458664c87437f6758f0d93085b06433bf66b2b84c23c19f3d2012c"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wt-formats"
|
||||||
|
version = "0.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8cc92320ebb10137ea72419d36b91febc1aa597af3ee762d75282d3980575d89"
|
||||||
|
dependencies = [
|
||||||
|
"bcn-decode",
|
||||||
|
"flate2",
|
||||||
|
"lztans",
|
||||||
|
"png",
|
||||||
|
"ruzstd",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wt-unpack"
|
||||||
|
version = "0.5.1"
|
||||||
|
source = "git+https://github.com/patodois/wt-unpack?rev=01d5b7603ae35e261a676d9b7b644c521dd303a0#01d5b7603ae35e261a676d9b7b644c521dd303a0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"clap",
|
||||||
|
"lewton",
|
||||||
|
"lztans",
|
||||||
|
"md-5",
|
||||||
|
"memmap2",
|
||||||
|
"png",
|
||||||
|
"ruzstd",
|
||||||
|
"serde_json",
|
||||||
|
"wt-formats",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wto-navgen-extract"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"anyhow",
|
||||||
|
"serde",
|
||||||
|
"serde_json",
|
||||||
|
"wt-formats",
|
||||||
|
"wt-unpack",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zlib-rs"
|
||||||
|
version = "0.6.9"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zmij"
|
||||||
|
version = "1.0.23"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
[package]
|
||||||
|
name = "wto-navgen-extract"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
description = "Offline Dagor level geometry and collision extractor for WTOffline tank navigation"
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
anyhow = "1"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
serde_json = "1"
|
||||||
|
wt-formats = "0.1.0"
|
||||||
|
wt-unpack = { git = "https://github.com/patodois/wt-unpack", rev = "01d5b7603ae35e261a676d9b7b644c521dd303a0" }
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
opt-level = 3
|
||||||
|
lto = "thin"
|
||||||
@@ -0,0 +1,550 @@
|
|||||||
|
use std::collections::{HashMap, HashSet};
|
||||||
|
use std::fs::{self, File};
|
||||||
|
use std::io::{BufWriter, Write};
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
use anyhow::{bail, Context, Result};
|
||||||
|
use serde::Deserialize;
|
||||||
|
use wt_formats::grp::GrpPack;
|
||||||
|
use wt_unpack::blk::{self, Value};
|
||||||
|
use wt_unpack::collision::{Collision, CollisionNode, NodeKind, COLLISION};
|
||||||
|
use wt_unpack::level::{Heightmap, Level};
|
||||||
|
use wt_unpack::rendinst::ResourceIndex;
|
||||||
|
use wt_unpack::vromfs::Vromfs;
|
||||||
|
|
||||||
|
const WTO_GEO_MAGIC: &[u8; 8] = b"WTOGEO\0\x01";
|
||||||
|
const WTO_GEO_VERSION: u32 = 1;
|
||||||
|
|
||||||
|
const OBS_HARD_SOLID: u8 = 0;
|
||||||
|
const OBS_BRIDGE_DECK: u8 = 1;
|
||||||
|
const OBS_CRUSHABLE: u8 = 2;
|
||||||
|
const OBS_TREE_THICK: u8 = 3;
|
||||||
|
const OBS_TREE_THIN: u8 = 4;
|
||||||
|
|
||||||
|
#[derive(Debug, Deserialize)]
|
||||||
|
struct LevelPois {
|
||||||
|
level: String,
|
||||||
|
#[serde(rename = "levelPath")]
|
||||||
|
level_path: String,
|
||||||
|
#[serde(rename = "boundsMin")]
|
||||||
|
bounds_min: [f32; 2],
|
||||||
|
#[serde(rename = "boundsMax")]
|
||||||
|
bounds_max: [f32; 2],
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
struct PoolMeta {
|
||||||
|
is_bridge: bool,
|
||||||
|
is_crushable: bool,
|
||||||
|
is_soft_foliage: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct CachedCollision {
|
||||||
|
max_radius: f32,
|
||||||
|
tris: Vec<([f32; 3], [f32; 3], [f32; 3], u8)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_args() -> Result<(PathBuf, PathBuf, PathBuf)> {
|
||||||
|
let mut game: Option<PathBuf> = None;
|
||||||
|
let mut pois: Option<PathBuf> = None;
|
||||||
|
let mut out: Option<PathBuf> = None;
|
||||||
|
let mut args = std::env::args().skip(1);
|
||||||
|
while let Some(a) = args.next() {
|
||||||
|
match a.as_str() {
|
||||||
|
"--game" => game = args.next().map(PathBuf::from),
|
||||||
|
"--pois" => pois = args.next().map(PathBuf::from),
|
||||||
|
"--out" => out = args.next().map(PathBuf::from),
|
||||||
|
other => bail!("unknown argument: {other}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((
|
||||||
|
game.context("missing --game <clientDir>")?,
|
||||||
|
pois.context("missing --pois <level.pois.json>")?,
|
||||||
|
out.context("missing --out <level.wtogeo>")?,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
struct AcesMeta {
|
||||||
|
water_level: f32,
|
||||||
|
/// Authoritative tank-crushable impulse threshold from `config/rendinst_dmg.blk` (lowercase name -> destructionImpulse).
|
||||||
|
destr_impulse: HashMap<String, f32>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn read_aces_meta(game: &Path, level_name: &str) -> AcesMeta {
|
||||||
|
let mut meta = AcesMeta { water_level: -1.0e6, destr_impulse: HashMap::new() };
|
||||||
|
let aces_path = game.join("aces.vromfs.bin");
|
||||||
|
let Ok(raw) = fs::read(&aces_path) else { return meta; };
|
||||||
|
let Ok(arc) = Vromfs::parse(&raw) else { return meta; };
|
||||||
|
let shared = arc
|
||||||
|
.files
|
||||||
|
.iter()
|
||||||
|
.find(|f| f.name == wt_unpack::vromfs::SHARED_NAMEMAP_NAME)
|
||||||
|
.and_then(|nm| blk::SharedContext::from_namemap(&nm.data).ok())
|
||||||
|
.map(|(mut ctx, dict_name)| {
|
||||||
|
if let Some(df) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case(&dict_name)) {
|
||||||
|
ctx.dict = Some(df.data.clone());
|
||||||
|
}
|
||||||
|
ctx
|
||||||
|
});
|
||||||
|
|
||||||
|
let target = format!("levels/{}.blk", level_name.to_lowercase());
|
||||||
|
if let Some(entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case(&target)) {
|
||||||
|
if let Ok(doc) = blk::parse(&entry.data, shared.as_ref()) {
|
||||||
|
for (name, value) in &doc.params {
|
||||||
|
if name.eq_ignore_ascii_case("water_level") {
|
||||||
|
match value {
|
||||||
|
Value::Real(v) => meta.water_level = *v,
|
||||||
|
Value::Int(v) => meta.water_level = *v as f32,
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(dmg_entry) = arc.files.iter().find(|f| f.name.eq_ignore_ascii_case("config/rendinst_dmg.blk")) {
|
||||||
|
if let Ok(doc) = blk::parse(&dmg_entry.data, shared.as_ref()) {
|
||||||
|
for b in &doc.blocks {
|
||||||
|
let mut rname: Option<&str> = None;
|
||||||
|
let mut impulse: Option<f32> = None;
|
||||||
|
for (k, v) in &b.params {
|
||||||
|
if k.eq_ignore_ascii_case("name") {
|
||||||
|
if let Value::Str(s) = v { rname = Some(s.as_str()); }
|
||||||
|
} else if k.eq_ignore_ascii_case("destructionImpulse") {
|
||||||
|
match v {
|
||||||
|
Value::Real(x) => impulse = Some(*x),
|
||||||
|
Value::Int(x) => impulse = Some(*x as f32),
|
||||||
|
_ => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if let (Some(n), Some(imp)) = (rname, impulse) {
|
||||||
|
meta.destr_impulse.insert(n.to_lowercase(), imp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
meta
|
||||||
|
}
|
||||||
|
|
||||||
|
fn classify_pool(name: &str, destr_impulse: Option<f32>) -> PoolMeta {
|
||||||
|
let lower = name.to_lowercase();
|
||||||
|
let is_bridge = lower.contains("bridge")
|
||||||
|
|| lower.contains("viaduct")
|
||||||
|
|| lower.contains("overpass")
|
||||||
|
|| lower.contains("pontoon")
|
||||||
|
|| lower.contains("jetty")
|
||||||
|
|| lower.contains("pier");
|
||||||
|
|
||||||
|
let always_hard = lower.contains("rock")
|
||||||
|
|| lower.contains("cliff")
|
||||||
|
|| lower.contains("bunker")
|
||||||
|
|| lower.contains("house")
|
||||||
|
|| lower.contains("building")
|
||||||
|
|| lower.contains("castle")
|
||||||
|
|| lower.contains("tower")
|
||||||
|
|| lower.contains("church")
|
||||||
|
|| lower.contains("factory")
|
||||||
|
|| lower.contains("hangar")
|
||||||
|
|| lower.contains("wagon")
|
||||||
|
|| lower.contains("train")
|
||||||
|
|| lower.contains("locomotive")
|
||||||
|
|| lower.contains("container")
|
||||||
|
|| lower.contains("tank_wreck")
|
||||||
|
|| is_bridge;
|
||||||
|
|
||||||
|
let is_soft_foliage = !always_hard
|
||||||
|
&& (lower.starts_with("bush_")
|
||||||
|
|| lower.contains("_bush_")
|
||||||
|
|| lower.starts_with("shrub_")
|
||||||
|
|| lower.contains("_shrub_")
|
||||||
|
|| lower.contains("grass")
|
||||||
|
|| lower.contains("reed")
|
||||||
|
|| lower.contains("flower")
|
||||||
|
|| lower.contains("fern"));
|
||||||
|
|
||||||
|
// Authoritative War Thunder physics: objects in `config/rendinst_dmg.blk` with low
|
||||||
|
// `destructionImpulse` (<= 45,000 N*s) are crushed on contact by moving tanks (wooden fences,
|
||||||
|
// lamp posts, hedges, benches, sheds, destructible thin walls, small trees).
|
||||||
|
let is_crushable = !always_hard
|
||||||
|
&& match destr_impulse {
|
||||||
|
Some(imp) if imp > 0.0 && imp <= 45_000.0 => true,
|
||||||
|
_ => lower.contains("fence_wood")
|
||||||
|
|| lower.contains("wooden_fence")
|
||||||
|
|| lower.contains("hedge")
|
||||||
|
|| lower.contains("sign_")
|
||||||
|
|| lower.contains("bench")
|
||||||
|
|| lower.contains("hay"),
|
||||||
|
};
|
||||||
|
|
||||||
|
PoolMeta { is_bridge, is_crushable, is_soft_foliage }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn transform_point(tm: &[[f32; 3]; 4], p: [f32; 3]) -> [f32; 3] {
|
||||||
|
[
|
||||||
|
tm[0][0] * p[0] + tm[1][0] * p[1] + tm[2][0] * p[2] + tm[3][0],
|
||||||
|
tm[0][1] * p[0] + tm[1][1] * p[1] + tm[2][1] * p[2] + tm[3][1],
|
||||||
|
tm[0][2] * p[0] + tm[1][2] * p[1] + tm[2][2] * p[2] + tm[3][2],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn det3(tm: &[[f32; 3]; 4]) -> f32 {
|
||||||
|
let [a, b, c] = [tm[0], tm[1], tm[2]];
|
||||||
|
a[0] * (b[1] * c[2] - b[2] * c[1]) - a[1] * (b[0] * c[2] - b[2] * c[0])
|
||||||
|
+ a[2] * (b[0] * c[1] - b[1] * c[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn box_tris(n: &CollisionNode) -> Vec<([f32; 3], [f32; 3], [f32; 3])> {
|
||||||
|
let [lo, hi] = n.bbox;
|
||||||
|
let c = |i: usize| {
|
||||||
|
n.to_object([
|
||||||
|
if i & 1 == 0 { lo[0] } else { hi[0] },
|
||||||
|
if i & 2 == 0 { lo[1] } else { hi[1] },
|
||||||
|
if i & 4 == 0 { lo[2] } else { hi[2] },
|
||||||
|
])
|
||||||
|
};
|
||||||
|
let pts: Vec<[f32; 3]> = (0..8).map(c).collect();
|
||||||
|
let quads = [[0, 2, 3, 1], [4, 5, 7, 6], [0, 1, 5, 4], [2, 6, 7, 3], [0, 4, 6, 2], [1, 3, 7, 5]];
|
||||||
|
let mut tris = Vec::with_capacity(12);
|
||||||
|
for q in quads {
|
||||||
|
tris.push((pts[q[0]], pts[q[1]], pts[q[2]]));
|
||||||
|
tris.push((pts[q[0]], pts[q[2]], pts[q[3]]));
|
||||||
|
}
|
||||||
|
tris
|
||||||
|
}
|
||||||
|
|
||||||
|
fn capsule_tris(a: [f32; 3], b: [f32; 3], r: f32) -> Vec<([f32; 3], [f32; 3], [f32; 3])> {
|
||||||
|
let dx = b[0] - a[0];
|
||||||
|
let dy = b[1] - a[1];
|
||||||
|
let dz = b[2] - a[2];
|
||||||
|
let len = (dx * dx + dy * dy + dz * dz).sqrt();
|
||||||
|
let axis = if len > 1e-4 { [dx / len, dy / len, dz / len] } else { [0.0, 1.0, 0.0] };
|
||||||
|
let up = if axis[1].abs() < 0.9 { [0.0, 1.0, 0.0] } else { [1.0, 0.0, 0.0] };
|
||||||
|
let cross = |u: [f32; 3], v: [f32; 3]| {
|
||||||
|
[u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
|
||||||
|
};
|
||||||
|
let norm = |v: [f32; 3]| {
|
||||||
|
let l = (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt().max(1e-6);
|
||||||
|
[v[0] / l, v[1] / l, v[2] / l]
|
||||||
|
};
|
||||||
|
let u = norm(cross(axis, up));
|
||||||
|
let v = norm(cross(axis, u));
|
||||||
|
|
||||||
|
let segs = 6usize;
|
||||||
|
let mut ring_a = Vec::with_capacity(segs);
|
||||||
|
let mut ring_b = Vec::with_capacity(segs);
|
||||||
|
for i in 0..segs {
|
||||||
|
let ang = (i as f32) * std::f32::consts::TAU / (segs as f32);
|
||||||
|
let (ca, sa) = (ang.cos() * r, ang.sin() * r);
|
||||||
|
let off = [u[0] * ca + v[0] * sa, u[1] * ca + v[1] * sa, u[2] * ca + v[2] * sa];
|
||||||
|
ring_a.push([a[0] + off[0], a[1] + off[1], a[2] + off[2]]);
|
||||||
|
ring_b.push([b[0] + off[0], b[1] + off[1], b[2] + off[2]]);
|
||||||
|
}
|
||||||
|
let mut tris = Vec::with_capacity(segs * 2);
|
||||||
|
for i in 0..segs {
|
||||||
|
let j = (i + 1) % segs;
|
||||||
|
tris.push((ring_a[i], ring_a[j], ring_b[j]));
|
||||||
|
tris.push((ring_a[i], ring_b[j], ring_b[i]));
|
||||||
|
}
|
||||||
|
tris
|
||||||
|
}
|
||||||
|
|
||||||
|
fn tri_normal_y(a: [f32; 3], b: [f32; 3], c: [f32; 3]) -> f32 {
|
||||||
|
let e1 = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];
|
||||||
|
let e2 = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];
|
||||||
|
let nx = e1[1] * e2[2] - e1[2] * e2[1];
|
||||||
|
let ny = e1[2] * e2[0] - e1[0] * e2[2];
|
||||||
|
let nz = e1[0] * e2[1] - e1[1] * e2[0];
|
||||||
|
let len = (nx * nx + ny * ny + nz * nz).sqrt();
|
||||||
|
if len > 1e-6 { (ny / len).abs() } else { 0.0 }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_cached_collision(c: &Collision, meta: &PoolMeta) -> Option<CachedCollision> {
|
||||||
|
if meta.is_soft_foliage {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let mut tris = Vec::new();
|
||||||
|
for n in &c.nodes {
|
||||||
|
// Vehicles only collide with physics_collidable nodes (behavior bit 1).
|
||||||
|
if !n.physics_collidable() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let mat_soft = !n.materials.is_empty()
|
||||||
|
&& n.materials.iter().all(|m| {
|
||||||
|
let ml = m.to_lowercase();
|
||||||
|
ml.contains("bush") || ml.contains("foliage") || ml.contains("leaves") || ml.contains("glass")
|
||||||
|
});
|
||||||
|
if mat_soft {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let scale = det3(&n.tm).abs().cbrt();
|
||||||
|
match n.kind {
|
||||||
|
NodeKind::Mesh | NodeKind::Convex => {
|
||||||
|
if n.indices.len() < 3 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for t in n.indices.chunks_exact(3) {
|
||||||
|
let p0 = n.to_object(n.positions[t[0] as usize]);
|
||||||
|
let p1 = n.to_object(n.positions[t[1] as usize]);
|
||||||
|
let p2 = n.to_object(n.positions[t[2] as usize]);
|
||||||
|
let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 {
|
||||||
|
OBS_BRIDGE_DECK
|
||||||
|
} else if meta.is_crushable {
|
||||||
|
OBS_CRUSHABLE
|
||||||
|
} else {
|
||||||
|
OBS_HARD_SOLID
|
||||||
|
};
|
||||||
|
tris.push((p0, p1, p2, cls));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NodeKind::Box => {
|
||||||
|
for (p0, p1, p2) in box_tris(n) {
|
||||||
|
let cls = if meta.is_bridge && tri_normal_y(p0, p1, p2) >= 0.72 {
|
||||||
|
OBS_BRIDGE_DECK
|
||||||
|
} else if meta.is_crushable {
|
||||||
|
OBS_CRUSHABLE
|
||||||
|
} else {
|
||||||
|
OBS_HARD_SOLID
|
||||||
|
};
|
||||||
|
tris.push((p0, p1, p2, cls));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NodeKind::Capsule => {
|
||||||
|
if let Some(cap) = n.capsule {
|
||||||
|
let a = n.to_object(cap.a);
|
||||||
|
let b = n.to_object(cap.b);
|
||||||
|
let r = (cap.radius * scale).max(0.08);
|
||||||
|
let cls = if r >= 0.28 { OBS_TREE_THICK } else { OBS_TREE_THIN };
|
||||||
|
for (p0, p1, p2) in capsule_tris(a, b, r) {
|
||||||
|
tris.push((p0, p1, p2, cls));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NodeKind::Points | NodeKind::Sphere => {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if tris.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let bmin = c.bbox[0];
|
||||||
|
let bmax = c.bbox[1];
|
||||||
|
let max_r = [bmin[0].abs().max(bmax[0].abs()), bmin[2].abs().max(bmax[2].abs())]
|
||||||
|
.iter()
|
||||||
|
.copied()
|
||||||
|
.fold(0.0f32, f32::max)
|
||||||
|
* 1.42;
|
||||||
|
Some(CachedCollision { max_radius: max_r.max(4.0), tris })
|
||||||
|
}
|
||||||
|
|
||||||
|
fn crop_heightmap(hm: &Heightmap, min_x: f32, min_z: f32, max_x: f32, max_z: f32) -> (u32, u32, [f32; 2], Vec<f32>) {
|
||||||
|
let cs = hm.cell_size;
|
||||||
|
let x0 = (((min_x - hm.origin[0]) / cs).floor() as i32).clamp(0, (hm.width as i32) - 2) as u32;
|
||||||
|
let z0 = (((min_z - hm.origin[1]) / cs).floor() as i32).clamp(0, (hm.height as i32) - 2) as u32;
|
||||||
|
let x1 = (((max_x - hm.origin[0]) / cs).ceil() as i32).clamp((x0 as i32) + 1, (hm.width as i32) - 1) as u32;
|
||||||
|
let z1 = (((max_z - hm.origin[1]) / cs).ceil() as i32).clamp((z0 as i32) + 1, (hm.height as i32) - 1) as u32;
|
||||||
|
let cw = x1 - x0 + 1;
|
||||||
|
let ch = z1 - z0 + 1;
|
||||||
|
let mut heights = Vec::with_capacity((cw * ch) as usize);
|
||||||
|
for z in z0..=z1 {
|
||||||
|
let row = (z as usize) * (hm.width as usize);
|
||||||
|
for x in x0..=x1 {
|
||||||
|
heights.push(hm.metres(hm.data[row + x as usize]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let origin = [hm.origin[0] + (x0 as f32) * cs, hm.origin[1] + (z0 as f32) * cs];
|
||||||
|
(cw, ch, origin, heights)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() -> Result<()> {
|
||||||
|
let t0 = Instant::now();
|
||||||
|
let (game_dir, pois_path, out_path) = parse_args()?;
|
||||||
|
let pois: LevelPois = serde_json::from_str(
|
||||||
|
&fs::read_to_string(&pois_path).with_context(|| format!("reading {}", pois_path.display()))?,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
let level_file = game_dir.join(&pois.level_path);
|
||||||
|
let raw = fs::read(&level_file).with_context(|| format!("reading {}", level_file.display()))?;
|
||||||
|
let level = Level::parse(&raw).with_context(|| format!("parsing {}", level_file.display()))?;
|
||||||
|
|
||||||
|
let ever_sha1 = level.export_info()?.and_then(|e| e.sha1).unwrap_or([0u8; 20]);
|
||||||
|
let aces_meta = read_aces_meta(&game_dir, &pois.level);
|
||||||
|
let water_level = aces_meta.water_level;
|
||||||
|
|
||||||
|
if let Some(pm) = level.phys_map_info()? {
|
||||||
|
println!(
|
||||||
|
" LMp2: {}x{} scale={:.2}m origin=({:.0},{:.0}) mats={:?}",
|
||||||
|
pm.size[0],
|
||||||
|
pm.size[1],
|
||||||
|
pm.metres_per_texel,
|
||||||
|
pm.world_origin[0],
|
||||||
|
pm.world_origin[1],
|
||||||
|
&pm.materials[..pm.materials.len().min(10)]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let hm = level.heightmap()?.with_context(|| format!("{} has no HM2 heightmap", pois.level))?;
|
||||||
|
let (cw, ch, crop_origin, heights) = crop_heightmap(
|
||||||
|
&hm,
|
||||||
|
pois.bounds_min[0],
|
||||||
|
pois.bounds_min[1],
|
||||||
|
pois.bounds_max[0],
|
||||||
|
pois.bounds_max[1],
|
||||||
|
);
|
||||||
|
let crop_max_x = crop_origin[0] + ((cw - 1) as f32) * hm.cell_size;
|
||||||
|
let crop_max_z = crop_origin[1] + ((ch - 1) as f32) * hm.cell_size;
|
||||||
|
println!(
|
||||||
|
"{}: HM2 full={}x{} cs={:.2}m -> crop={}x{} [{:.0}..{:.0}]x[{:.0}..{:.0}] water={:.2}m",
|
||||||
|
pois.level,
|
||||||
|
hm.width,
|
||||||
|
hm.height,
|
||||||
|
hm.cell_size,
|
||||||
|
cw,
|
||||||
|
ch,
|
||||||
|
crop_origin[0],
|
||||||
|
crop_max_x,
|
||||||
|
crop_origin[1],
|
||||||
|
crop_max_z,
|
||||||
|
water_level
|
||||||
|
);
|
||||||
|
|
||||||
|
// Collect distinct placed RendInst pools from RIGz
|
||||||
|
let layers = level.rendinst_layers()?;
|
||||||
|
let mut pool_names: HashSet<String> = HashSet::new();
|
||||||
|
for layer in &layers {
|
||||||
|
for (pool, cnt) in layer.pools.iter().zip(layer.counts()) {
|
||||||
|
if cnt > 0 {
|
||||||
|
pool_names.insert(pool.name.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let res_index = ResourceIndex::build(&game_dir, &[COLLISION])?;
|
||||||
|
|
||||||
|
// Group collision loads by .grp file so each pack is read once
|
||||||
|
let mut by_pack: HashMap<PathBuf, Vec<(String, String)>> = HashMap::new();
|
||||||
|
let mut no_collision = 0usize;
|
||||||
|
for name in &pool_names {
|
||||||
|
let res_name = format!("{name}_collision");
|
||||||
|
if let Some(p) = res_index.find(COLLISION, &res_name) {
|
||||||
|
by_pack.entry(p.to_path_buf()).or_default().push((name.clone(), res_name));
|
||||||
|
} else {
|
||||||
|
no_collision += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut cached_cols: HashMap<String, CachedCollision> = HashMap::new();
|
||||||
|
for (pack_path, items) in &by_pack {
|
||||||
|
let Ok(bytes) = fs::read(pack_path) else { continue };
|
||||||
|
let Ok(pack) = GrpPack::parse(&bytes) else { continue };
|
||||||
|
for (pool_name, res_name) in items {
|
||||||
|
let Some(res) = pack.find(res_name, COLLISION) else { continue };
|
||||||
|
let Ok(col) = Collision::parse(res_name, pack.data(res)) else { continue };
|
||||||
|
let imp = aces_meta.destr_impulse.get(&pool_name.to_lowercase()).copied();
|
||||||
|
let meta = classify_pool(pool_name, imp);
|
||||||
|
if let Some(cc) = build_cached_collision(&col, &meta) {
|
||||||
|
cached_cols.insert(pool_name.clone(), cc);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stream placed collision triangles inside the cropped battle area
|
||||||
|
let pad = 16.0;
|
||||||
|
let mut verts: Vec<[f32; 3]> = Vec::with_capacity(200_000);
|
||||||
|
let mut tris: Vec<([u32; 3], u8)> = Vec::with_capacity(100_000);
|
||||||
|
let mut inst_used = 0usize;
|
||||||
|
let mut cls_counts = [0usize; 5];
|
||||||
|
|
||||||
|
for layer in &layers {
|
||||||
|
let instances = layer.instances()?;
|
||||||
|
for inst in instances {
|
||||||
|
let Some(pool) = layer.pools.get(inst.pool) else { continue };
|
||||||
|
let Some(cc) = cached_cols.get(&pool.name) else { continue };
|
||||||
|
let pos = inst.tm[3];
|
||||||
|
// Quick XZ culling using instance scale + object bounding radius
|
||||||
|
let sx = (inst.tm[0][0].powi(2) + inst.tm[0][1].powi(2) + inst.tm[0][2].powi(2)).sqrt();
|
||||||
|
let sz = (inst.tm[2][0].powi(2) + inst.tm[2][1].powi(2) + inst.tm[2][2].powi(2)).sqrt();
|
||||||
|
let rad = cc.max_radius * sx.max(sz).max(1.0);
|
||||||
|
if pos[0] + rad < crop_origin[0] - pad
|
||||||
|
|| pos[0] - rad > crop_max_x + pad
|
||||||
|
|| pos[2] + rad < crop_origin[1] - pad
|
||||||
|
|| pos[2] - rad > crop_max_z + pad
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
inst_used += 1;
|
||||||
|
for &(p0, p1, p2, cls) in &cc.tris {
|
||||||
|
let w0 = transform_point(&inst.tm, p0);
|
||||||
|
let w1 = transform_point(&inst.tm, p1);
|
||||||
|
let w2 = transform_point(&inst.tm, p2);
|
||||||
|
let base = verts.len() as u32;
|
||||||
|
verts.push(w0);
|
||||||
|
verts.push(w1);
|
||||||
|
verts.push(w2);
|
||||||
|
tris.push(([base, base + 1, base + 2], cls));
|
||||||
|
if (cls as usize) < cls_counts.len() {
|
||||||
|
cls_counts[cls as usize] += 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
println!(
|
||||||
|
" RIGz: pools={} cols={} noCol={} instancesInBounds={} obsTris={} [hard={} bridge={} crush={} treeThick={} treeThin={}] ({:.2}s)",
|
||||||
|
pool_names.len(),
|
||||||
|
cached_cols.len(),
|
||||||
|
no_collision,
|
||||||
|
inst_used,
|
||||||
|
tris.len(),
|
||||||
|
cls_counts[0],
|
||||||
|
cls_counts[1],
|
||||||
|
cls_counts[2],
|
||||||
|
cls_counts[3],
|
||||||
|
cls_counts[4],
|
||||||
|
t0.elapsed().as_secs_f32()
|
||||||
|
);
|
||||||
|
|
||||||
|
if let Some(parent) = out_path.parent() {
|
||||||
|
fs::create_dir_all(parent)?;
|
||||||
|
}
|
||||||
|
let mut w = BufWriter::new(File::create(&out_path)?);
|
||||||
|
// WtoGeoHeader (must match native/wto-nav/wto_nav_format.h byte-for-byte)
|
||||||
|
w.write_all(WTO_GEO_MAGIC)?;
|
||||||
|
w.write_all(&WTO_GEO_VERSION.to_le_bytes())?;
|
||||||
|
w.write_all(&0u32.to_le_bytes())?; // flags
|
||||||
|
w.write_all(&ever_sha1)?;
|
||||||
|
w.write_all(&water_level.to_le_bytes())?;
|
||||||
|
w.write_all(&crop_origin[0].to_le_bytes())?;
|
||||||
|
w.write_all(&crop_origin[1].to_le_bytes())?;
|
||||||
|
w.write_all(&crop_max_x.to_le_bytes())?;
|
||||||
|
w.write_all(&crop_max_z.to_le_bytes())?;
|
||||||
|
w.write_all(&cw.to_le_bytes())?;
|
||||||
|
w.write_all(&ch.to_le_bytes())?;
|
||||||
|
w.write_all(&hm.cell_size.to_le_bytes())?;
|
||||||
|
w.write_all(&crop_origin[0].to_le_bytes())?;
|
||||||
|
w.write_all(&crop_origin[1].to_le_bytes())?;
|
||||||
|
w.write_all(&(verts.len() as u32).to_le_bytes())?;
|
||||||
|
w.write_all(&(tris.len() as u32).to_le_bytes())?;
|
||||||
|
|
||||||
|
// Heightmap float32 samples
|
||||||
|
for h in &heights {
|
||||||
|
w.write_all(&h.to_le_bytes())?;
|
||||||
|
}
|
||||||
|
// Obstacle vertices (float32 x 3)
|
||||||
|
for v in &verts {
|
||||||
|
w.write_all(&v[0].to_le_bytes())?;
|
||||||
|
w.write_all(&v[1].to_le_bytes())?;
|
||||||
|
w.write_all(&v[2].to_le_bytes())?;
|
||||||
|
}
|
||||||
|
// Obstacle triangles (uint32 x 3 + uint8 class)
|
||||||
|
for (idx, cls) in &tris {
|
||||||
|
w.write_all(&idx[0].to_le_bytes())?;
|
||||||
|
w.write_all(&idx[1].to_le_bytes())?;
|
||||||
|
w.write_all(&idx[2].to_le_bytes())?;
|
||||||
|
w.write_all(&[*cls])?;
|
||||||
|
}
|
||||||
|
w.flush()?;
|
||||||
|
println!(" wrote {} ({:.1} MB)", out_path.display(), fs::metadata(&out_path)?.len() as f64 / (1024.0 * 1024.0));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
/**
|
||||||
|
* Extract union battle-area bounds, tank spawn points, and capture zones for ground
|
||||||
|
* levels from `char.vromfs.bin` (`config/mislist.blk`) and `mis.vromfs.bin` (recursively
|
||||||
|
* resolving `imports/import_record` mission templates).
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
* node --experimental-strip-types tools/navgen/mission-bounds.mts \
|
||||||
|
* --game "J:\GAME\WTLab\client-2.61.0.58" \
|
||||||
|
* --out "build\nav-work" \
|
||||||
|
* --levels avg_berlin,avg_poland,avg_hurtgen
|
||||||
|
*/
|
||||||
|
import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||||
|
import { join, resolve } from 'node:path';
|
||||||
|
import { readArchive, getFile, NAME_MAP_PATH } from '../../packages/vromfs/src/index.ts';
|
||||||
|
import { decodeBlk, parseSharedNameMap, findBlock, findParam, type BlkBlock, type SharedNameContext } from '../../packages/blk/src/index.ts';
|
||||||
|
|
||||||
|
interface PoiPoint {
|
||||||
|
readonly name: string;
|
||||||
|
readonly x: number;
|
||||||
|
readonly y: number;
|
||||||
|
readonly z: number;
|
||||||
|
readonly radius: number;
|
||||||
|
readonly mission: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface LevelPois {
|
||||||
|
readonly level: string;
|
||||||
|
readonly levelPath: string;
|
||||||
|
readonly missions: readonly string[];
|
||||||
|
readonly boundsMin: readonly [number, number];
|
||||||
|
readonly boundsMax: readonly [number, number];
|
||||||
|
readonly team1Spawns: readonly PoiPoint[];
|
||||||
|
readonly team2Spawns: readonly PoiPoint[];
|
||||||
|
readonly captureZones: readonly PoiPoint[];
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseArgs(argv: string[]) {
|
||||||
|
let gameDir = '';
|
||||||
|
let outDir = '';
|
||||||
|
let levelsFilter: Set<string> | null = null;
|
||||||
|
for (let i = 0; i < argv.length; i++) {
|
||||||
|
const a = argv[i]!;
|
||||||
|
if (a === '--game') gameDir = argv[++i] ?? '';
|
||||||
|
else if (a === '--out') outDir = argv[++i] ?? '';
|
||||||
|
else if (a === '--levels') {
|
||||||
|
const raw = argv[++i] ?? '';
|
||||||
|
levelsFilter = new Set(raw.split(',').map((s) => s.trim().toLowerCase()).filter(Boolean));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!gameDir || !outDir) {
|
||||||
|
throw new Error('Usage: --game <clientDir> --out <workDir> [--levels avg_berlin,avg_poland,avg_hurtgen]');
|
||||||
|
}
|
||||||
|
return { gameDir: resolve(gameDir), outDir: resolve(outDir), levelsFilter };
|
||||||
|
}
|
||||||
|
|
||||||
|
function openPack(packPath: string) {
|
||||||
|
const arc = readArchive(readFileSync(packPath));
|
||||||
|
const dicts = [...arc.files.keys()].filter((k) => k.endsWith('.dict'));
|
||||||
|
const dictionary = dicts.length ? arc.files.get(dicts[0]!) : undefined;
|
||||||
|
const names = arc.files.has(NAME_MAP_PATH) ? parseSharedNameMap(getFile(arc, NAME_MAP_PATH), dictionary).names : [];
|
||||||
|
const shared: SharedNameContext = { names, dictionary };
|
||||||
|
const lowerMap = new Map<string, string>();
|
||||||
|
for (const k of arc.files.keys()) lowerMap.set(k.toLowerCase(), k);
|
||||||
|
return {
|
||||||
|
arc,
|
||||||
|
lowerMap,
|
||||||
|
has(rel: string): boolean { return lowerMap.has(rel.toLowerCase()); },
|
||||||
|
readBlk(rel: string): BlkBlock {
|
||||||
|
const actual = lowerMap.get(rel.toLowerCase());
|
||||||
|
if (!actual) throw new Error(`missing ${rel} in ${packPath}`);
|
||||||
|
return decodeBlk(getFile(arc, actual), shared);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function val(b: BlkBlock | undefined, name: string): any {
|
||||||
|
const p = b ? findParam(b, name) : undefined;
|
||||||
|
return p ? (p.value as any).value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function listParams(b: BlkBlock | undefined, name: string): any[] {
|
||||||
|
if (!b) return [];
|
||||||
|
return b.params.filter((p) => p.name === name).map((p) => (p.value as any).value);
|
||||||
|
}
|
||||||
|
|
||||||
|
function collectAreasRecursive(
|
||||||
|
misPack: ReturnType<typeof openPack>,
|
||||||
|
blkPath: string,
|
||||||
|
visited: Set<string>,
|
||||||
|
outAreas: BlkBlock[],
|
||||||
|
) {
|
||||||
|
const key = blkPath.toLowerCase();
|
||||||
|
if (visited.has(key) || !misPack.has(key)) return;
|
||||||
|
visited.add(key);
|
||||||
|
let blk: BlkBlock;
|
||||||
|
try { blk = misPack.readBlk(key); } catch { return; }
|
||||||
|
|
||||||
|
const areas = findBlock(blk, 'areas');
|
||||||
|
if (areas) {
|
||||||
|
for (const sub of areas.blocks) outAreas.push(sub);
|
||||||
|
}
|
||||||
|
const imports = findBlock(blk, 'imports');
|
||||||
|
if (imports) {
|
||||||
|
for (const rec of imports.blocks) {
|
||||||
|
if (rec.name !== 'import_record') continue;
|
||||||
|
const impAreas = val(rec, 'importAreas');
|
||||||
|
if (impAreas === false) continue;
|
||||||
|
const file = String(val(rec, 'file') ?? '').replace(/\\/g, '/').replace(/^\/+/, '');
|
||||||
|
if (file) collectAreasRecursive(misPack, file, visited, outAreas);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function areaCornersXZ(area: BlkBlock): { minX: number; maxX: number; minZ: number; maxZ: number; cx: number; cy: number; cz: number; rad: number } | null {
|
||||||
|
const tm = val(area, 'tm');
|
||||||
|
if (Array.isArray(tm) && tm.length === 12) {
|
||||||
|
const cx = Number(tm[9]);
|
||||||
|
const cy = Number(tm[10]);
|
||||||
|
const cz = Number(tm[11]);
|
||||||
|
// Box extents in Dagor area tm: half-axes are 0.5 * axis vector length for Box, full radius for Sphere/Cylinder
|
||||||
|
const typeStr = String(val(area, 'type') ?? '');
|
||||||
|
const axX = Math.abs(tm[0]) + Math.abs(tm[3]) + Math.abs(tm[6]);
|
||||||
|
const axZ = Math.abs(tm[2]) + Math.abs(tm[5]) + Math.abs(tm[8]);
|
||||||
|
const halfX = typeStr === 'Sphere' || typeStr === 'Cylinder' ? Math.hypot(tm[0], tm[1], tm[2]) : 0.5 * axX;
|
||||||
|
const halfZ = typeStr === 'Sphere' || typeStr === 'Cylinder' ? Math.hypot(tm[6], tm[7], tm[8]) : 0.5 * axZ;
|
||||||
|
const rad = Math.max(8, 0.5 * (halfX + halfZ));
|
||||||
|
return { minX: cx - halfX, maxX: cx + halfX, minZ: cz - halfZ, maxZ: cz + halfZ, cx, cy, cz, rad };
|
||||||
|
}
|
||||||
|
const obj = findBlock(area, 'props');
|
||||||
|
const pos = val(area, 'pos') ?? val(obj, 'pos');
|
||||||
|
if (Array.isArray(pos) && pos.length >= 3) {
|
||||||
|
const rad = Number(val(area, 'radius') ?? 15);
|
||||||
|
return { minX: pos[0] - rad, maxX: pos[0] + rad, minZ: pos[2] - rad, maxZ: pos[2] + rad, cx: pos[0], cy: pos[1], cz: pos[2], rad };
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function dedupePois(pts: PoiPoint[], minDistM: number): PoiPoint[] {
|
||||||
|
const out: PoiPoint[] = [];
|
||||||
|
const d2 = minDistM * minDistM;
|
||||||
|
for (const p of pts) {
|
||||||
|
if (out.some((o) => (o.x - p.x) ** 2 + (o.z - p.z) ** 2 < d2)) continue;
|
||||||
|
out.push(p);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
function main() {
|
||||||
|
const { gameDir, outDir, levelsFilter } = parseArgs(process.argv.slice(2));
|
||||||
|
mkdirSync(outDir, { recursive: true });
|
||||||
|
|
||||||
|
const charPack = openPack(join(gameDir, 'char.vromfs.bin'));
|
||||||
|
const misPack = openPack(join(gameDir, 'mis.vromfs.bin'));
|
||||||
|
|
||||||
|
const mislist = charPack.readBlk('config/mislist.blk');
|
||||||
|
const skirmish = findBlock(mislist, 'skirmish');
|
||||||
|
if (!skirmish) throw new Error('config/mislist.blk missing skirmish');
|
||||||
|
|
||||||
|
const pathByLowerName = new Map<string, string>();
|
||||||
|
for (const k of misPack.arc.files.keys()) {
|
||||||
|
if (!k.toLowerCase().startsWith('gamedata/missions/') || !k.toLowerCase().endsWith('.blk')) continue;
|
||||||
|
const base = k.slice(k.lastIndexOf('/') + 1, -4).toLowerCase();
|
||||||
|
pathByLowerName.set(base, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
const targetCats = new Set(['air_ground_Dom', 'air_ground_Conq', 'air_ground_Bttl']);
|
||||||
|
const missionNames = new Set<string>();
|
||||||
|
for (const cat of skirmish.blocks) {
|
||||||
|
if (targetCats.has(cat.name)) {
|
||||||
|
for (const m of listParams(cat, 'm')) {
|
||||||
|
if (!String(m).toLowerCase().includes('newbie')) missionNames.add(String(m));
|
||||||
|
}
|
||||||
|
} else if (cat.name === 'test') {
|
||||||
|
for (const m of listParams(cat, 'm')) {
|
||||||
|
if (/^great_war_/i.test(String(m))) missionNames.add(String(m));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Acc {
|
||||||
|
levelPath: string;
|
||||||
|
missions: string[];
|
||||||
|
minX: number; maxX: number; minZ: number; maxZ: number;
|
||||||
|
hasBattleBox: boolean;
|
||||||
|
t1Spawns: PoiPoint[];
|
||||||
|
t2Spawns: PoiPoint[];
|
||||||
|
caps: PoiPoint[];
|
||||||
|
}
|
||||||
|
const byLevel = new Map<string, Acc>();
|
||||||
|
|
||||||
|
for (const mName of missionNames) {
|
||||||
|
const mPath = pathByLowerName.get(mName.toLowerCase());
|
||||||
|
if (!mPath) continue;
|
||||||
|
const doc = misPack.readBlk(mPath);
|
||||||
|
const ms = findBlock(doc, 'mission_settings');
|
||||||
|
const mis = findBlock(ms, 'mission');
|
||||||
|
if (val(mis, 'isTanksAllowed') === false) continue;
|
||||||
|
const levelPath = String(val(mis, 'level') ?? '');
|
||||||
|
if (!levelPath) continue;
|
||||||
|
const levelKey = levelPath.replace(/^levels\//i, '').replace(/\.bin$/i, '').toLowerCase();
|
||||||
|
if (levelsFilter && !levelsFilter.has(levelKey)) continue;
|
||||||
|
|
||||||
|
let acc = byLevel.get(levelKey);
|
||||||
|
if (!acc) {
|
||||||
|
acc = {
|
||||||
|
levelPath, missions: [],
|
||||||
|
minX: Infinity, maxX: -Infinity, minZ: Infinity, maxZ: -Infinity,
|
||||||
|
hasBattleBox: false, t1Spawns: [], t2Spawns: [], caps: [],
|
||||||
|
};
|
||||||
|
byLevel.set(levelKey, acc);
|
||||||
|
}
|
||||||
|
acc.missions.push(mName);
|
||||||
|
|
||||||
|
const areas: BlkBlock[] = [];
|
||||||
|
collectAreasRecursive(misPack, mPath, new Set<string>(), areas);
|
||||||
|
|
||||||
|
for (const a of areas) {
|
||||||
|
const n = a.name.toLowerCase();
|
||||||
|
// Ignore aircraft/heli spawns & zones
|
||||||
|
if (/air|heli|bomber|fighter|carrier|ship|boat|naval|sea/.test(n)) continue;
|
||||||
|
const box = areaCornersXZ(a);
|
||||||
|
if (!box) continue;
|
||||||
|
|
||||||
|
if (n.includes('battle_area') && !n.includes('air') && !n.includes('ship')) {
|
||||||
|
const w = box.maxX - box.minX;
|
||||||
|
const h = box.maxZ - box.minZ;
|
||||||
|
if (w >= 300 && w <= 8000 && h >= 300 && h <= 8000) {
|
||||||
|
acc.minX = Math.min(acc.minX, box.minX);
|
||||||
|
acc.maxX = Math.max(acc.maxX, box.maxX);
|
||||||
|
acc.minZ = Math.min(acc.minZ, box.minZ);
|
||||||
|
acc.maxZ = Math.max(acc.maxZ, box.maxZ);
|
||||||
|
acc.hasBattleBox = true;
|
||||||
|
}
|
||||||
|
} else if (n.includes('capture_area') || n.includes('capture_zone') || n.includes('cap_zone')) {
|
||||||
|
if (!n.includes('brief') && box.rad >= 5 && box.rad <= 250) {
|
||||||
|
acc.caps.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName });
|
||||||
|
}
|
||||||
|
} else if (n.includes('tankspawn') || (n.includes('spawn') && /t1|t2|team1|team2|tank/.test(n))) {
|
||||||
|
if (n.includes('brief')) continue;
|
||||||
|
if (n.includes('t1_') || n.includes('team1') || n.includes('_t1')) {
|
||||||
|
acc.t1Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName });
|
||||||
|
} else if (n.includes('t2_') || n.includes('team2') || n.includes('_t2')) {
|
||||||
|
acc.t2Spawns.push({ name: a.name, x: box.cx, y: box.cy, z: box.cz, radius: box.rad, mission: mName });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const [levelKey, acc] of byLevel) {
|
||||||
|
const t1 = dedupePois(acc.t1Spawns, 90);
|
||||||
|
const t2 = dedupePois(acc.t2Spawns, 90);
|
||||||
|
const caps = dedupePois(acc.caps, 30);
|
||||||
|
// Ensure all spawns & caps are covered inside bounds (with 160m margin)
|
||||||
|
for (const p of [...t1, ...t2, ...caps]) {
|
||||||
|
acc.minX = Math.min(acc.minX, p.x - 160);
|
||||||
|
acc.maxX = Math.max(acc.maxX, p.x + 160);
|
||||||
|
acc.minZ = Math.min(acc.minZ, p.z - 160);
|
||||||
|
acc.maxZ = Math.max(acc.maxZ, p.z + 160);
|
||||||
|
}
|
||||||
|
// Expand battle-area union by 120m safety padding
|
||||||
|
const margin = 120;
|
||||||
|
const out: LevelPois = {
|
||||||
|
level: levelKey,
|
||||||
|
levelPath: acc.levelPath,
|
||||||
|
missions: acc.missions.sort(),
|
||||||
|
boundsMin: [Math.floor(acc.minX - margin), Math.floor(acc.minZ - margin)],
|
||||||
|
boundsMax: [Math.ceil(acc.maxX + margin), Math.ceil(acc.maxZ + margin)],
|
||||||
|
team1Spawns: t1,
|
||||||
|
team2Spawns: t2,
|
||||||
|
captureZones: caps,
|
||||||
|
};
|
||||||
|
const outPath = join(outDir, `${levelKey}.pois.json`);
|
||||||
|
writeFileSync(outPath, `${JSON.stringify(out, null, 2)}\n`, 'utf8');
|
||||||
|
console.log(`${levelKey}: missions=${out.missions.length} bounds=[${out.boundsMin[0]}..${out.boundsMax[0]}] x [${out.boundsMin[1]}..${out.boundsMax[1]}] (${out.boundsMax[0] - out.boundsMin[0]}m x ${out.boundsMax[1] - out.boundsMin[1]}m) t1Spawns=${t1.length} t2Spawns=${t2.length} caps=${caps.length}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main();
|
||||||
@@ -0,0 +1,252 @@
|
|||||||
|
"""Render top-down PNG inspection maps (`*_nav.png` and `*_cover.png`) from `.preview.bin` + `.pois.json`.
|
||||||
|
Zero external dependencies (Python stdlib `struct` + `zlib` only).
|
||||||
|
"""
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import struct
|
||||||
|
import zlib
|
||||||
|
|
||||||
|
|
||||||
|
def write_png(path: str, width: int, height: int, rgb: bytearray) -> None:
|
||||||
|
def chunk(tag: bytes, data: bytes) -> bytes:
|
||||||
|
crc = zlib.crc32(tag + data) & 0xFFFFFFFF
|
||||||
|
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", crc)
|
||||||
|
|
||||||
|
raw = bytearray()
|
||||||
|
stride = width * 3
|
||||||
|
for y in range(height):
|
||||||
|
raw.append(0)
|
||||||
|
row = y * stride
|
||||||
|
raw.extend(rgb[row : row + stride])
|
||||||
|
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||||
|
png = b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + chunk(b"IDAT", zlib.compress(bytes(raw), 6)) + chunk(b"IEND", b"")
|
||||||
|
os.makedirs(os.path.dirname(os.path.abspath(path)), exist_ok=True)
|
||||||
|
with open(path, "wb") as f:
|
||||||
|
f.write(png)
|
||||||
|
|
||||||
|
|
||||||
|
def set_px(rgb: bytearray, w: int, h: int, x: int, y: int, r: int, g: int, b: int) -> None:
|
||||||
|
if 0 <= x < w and 0 <= y < h:
|
||||||
|
idx = (y * w + x) * 3
|
||||||
|
rgb[idx] = r
|
||||||
|
rgb[idx + 1] = g
|
||||||
|
rgb[idx + 2] = b
|
||||||
|
|
||||||
|
|
||||||
|
def draw_line(rgb: bytearray, w: int, h: int, x0: int, y0: int, x1: int, y1: int, col, thick: int = 1) -> None:
|
||||||
|
dx = abs(x1 - x0)
|
||||||
|
dy = abs(y1 - y0)
|
||||||
|
sx = 1 if x0 < x1 else -1
|
||||||
|
sy = 1 if y0 < y1 else -1
|
||||||
|
err = dx - dy
|
||||||
|
r, g, b = col
|
||||||
|
while True:
|
||||||
|
for oy in range(-thick // 2, thick // 2 + 1):
|
||||||
|
for ox in range(-thick // 2, thick // 2 + 1):
|
||||||
|
set_px(rgb, w, h, x0 + ox, y0 + oy, r, g, b)
|
||||||
|
if x0 == x1 and y0 == y1:
|
||||||
|
break
|
||||||
|
e2 = 2 * err
|
||||||
|
if e2 > -dy:
|
||||||
|
err -= dy
|
||||||
|
x0 += sx
|
||||||
|
if e2 < dx:
|
||||||
|
err += dx
|
||||||
|
y0 += sy
|
||||||
|
|
||||||
|
|
||||||
|
def draw_circle(rgb: bytearray, w: int, h: int, cx: int, cy: int, rad: int, col, fill: bool = False) -> None:
|
||||||
|
r, g, b = col
|
||||||
|
r2 = rad * rad
|
||||||
|
for dy in range(-rad, rad + 1):
|
||||||
|
for dx in range(-rad, rad + 1):
|
||||||
|
d2 = dx * dx + dy * dy
|
||||||
|
if fill and d2 <= r2:
|
||||||
|
set_px(rgb, w, h, cx + dx, cy + dy, r, g, b)
|
||||||
|
elif not fill and abs(d2 - r2) <= max(2, rad * 2):
|
||||||
|
set_px(rgb, w, h, cx + dx, cy + dy, r, g, b)
|
||||||
|
|
||||||
|
|
||||||
|
def draw_square(rgb: bytearray, w: int, h: int, cx: int, cy: int, half: int, col) -> None:
|
||||||
|
r, g, b = col
|
||||||
|
for dy in range(-half, half + 1):
|
||||||
|
for dx in range(-half, half + 1):
|
||||||
|
set_px(rgb, w, h, cx + dx, cy + dy, r, g, b)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
ap = argparse.ArgumentParser()
|
||||||
|
ap.add_argument("--preview", required=True)
|
||||||
|
ap.add_argument("--pois", required=True)
|
||||||
|
ap.add_argument("--out-dir", required=True)
|
||||||
|
ap.add_argument("--name", required=True)
|
||||||
|
args = ap.parse_args()
|
||||||
|
|
||||||
|
with open(args.preview, "rb") as f:
|
||||||
|
data = f.read()
|
||||||
|
with open(args.pois, "r", encoding="utf-8") as f:
|
||||||
|
pois = json.load(f)
|
||||||
|
|
||||||
|
assert data[:8] == b"WTOPREV1", "bad preview magic"
|
||||||
|
off = 8
|
||||||
|
pw, ph, min_x, min_z, max_x, max_z, water_y = struct.unpack_from("<IIfffff", data, off)
|
||||||
|
off += 28
|
||||||
|
n_px = pw * ph
|
||||||
|
heights = struct.unpack_from(f"<{n_px}f", data, off)
|
||||||
|
off += n_px * 4
|
||||||
|
flags = data[off : off + n_px]
|
||||||
|
off += n_px
|
||||||
|
|
||||||
|
cover_cnt = struct.unpack_from("<I", data, off)[0]
|
||||||
|
off += 4
|
||||||
|
covers = []
|
||||||
|
# WtoCoverPoint = 16 floats (64B? wait: pos[3]+dir[2]+ret[2]+peekL[3]+peekR[3]+halfAng+h+w = 16 floats = 64B + 4B = 68B)
|
||||||
|
cov_fmt = "<3f2f2f3f3f3f4B"
|
||||||
|
cov_sz = struct.calcsize(cov_fmt)
|
||||||
|
for _ in range(cover_cnt):
|
||||||
|
covers.append(struct.unpack_from(cov_fmt, data, off))
|
||||||
|
off += cov_sz
|
||||||
|
|
||||||
|
tac_cols, tac_rows = struct.unpack_from("<II", data, off)
|
||||||
|
off += 8
|
||||||
|
tac = data[off : off + tac_cols * tac_rows * 4]
|
||||||
|
off += tac_cols * tac_rows * 4
|
||||||
|
|
||||||
|
path_cnt = struct.unpack_from("<I", data, off)[0]
|
||||||
|
off += 4
|
||||||
|
paths = []
|
||||||
|
for _ in range(path_cnt):
|
||||||
|
npts = struct.unpack_from("<I", data, off)[0]
|
||||||
|
off += 4
|
||||||
|
pts = struct.unpack_from(f"<{npts * 3}f", data, off)
|
||||||
|
off += npts * 12
|
||||||
|
paths.append([(pts[i * 3], pts[i * 3 + 2]) for i in range(npts)])
|
||||||
|
|
||||||
|
def world_to_px(wx: float, wz: float):
|
||||||
|
px = int((wx - min_x) / max(1e-3, max_x - min_x) * (pw - 1))
|
||||||
|
py = int((max_z - wz) / max(1e-3, max_z - min_z) * (ph - 1)) # North (+Z) up
|
||||||
|
return px, py
|
||||||
|
|
||||||
|
h_min = min(heights)
|
||||||
|
h_max = max(heights)
|
||||||
|
h_span = max(1.0, h_max - h_min)
|
||||||
|
|
||||||
|
nav_rgb = bytearray(pw * ph * 3)
|
||||||
|
cov_rgb = bytearray(pw * ph * 3)
|
||||||
|
|
||||||
|
for rz in range(ph):
|
||||||
|
py = ph - 1 - rz # Flip Z so North (+Z) is top of image
|
||||||
|
row_off = rz * pw
|
||||||
|
for rx in range(pw):
|
||||||
|
h = heights[row_off + rx]
|
||||||
|
fl = flags[row_off + rx]
|
||||||
|
# Base terrain shade with 5m contour lines
|
||||||
|
t = (h - h_min) / h_span
|
||||||
|
base = int(38 + t * 52)
|
||||||
|
if abs((h % 5.0)) < 0.25:
|
||||||
|
base = max(20, base - 16)
|
||||||
|
|
||||||
|
# Nav map color:
|
||||||
|
# Dark gray = unwalkable obstacle / steep cliff
|
||||||
|
# Deep blue = deep water, Cyan-blue = shallow water
|
||||||
|
# Bright green = T2 (wide heavy) + T1 + T0 walkable
|
||||||
|
# Mid-green = T1 + T0 walkable (standard tank fits, wide heavy doesn't)
|
||||||
|
# Yellow-green = T0 only (narrow tank alley)
|
||||||
|
# Orange = chokepoint, Purple-tint = crushable/forest, Teal = bridge
|
||||||
|
r, g, b = base, base, base
|
||||||
|
if fl & 16: # deep water
|
||||||
|
r, g, b = 22, 58, 125
|
||||||
|
elif fl & 8: # shallow water
|
||||||
|
r, g, b = 55, 130, 185
|
||||||
|
elif fl & 128: # bridge
|
||||||
|
r, g, b = 70, 210, 210
|
||||||
|
elif fl & 32: # chokepoint
|
||||||
|
r, g, b = 220, 145, 45
|
||||||
|
elif fl & 64: # crushable/forest
|
||||||
|
r, g, b = int(base * 0.6 + 65), int(base * 0.8 + 85), int(base * 0.5 + 35)
|
||||||
|
elif fl & 4: # T2 wide walkable
|
||||||
|
r, g, b = int(base * 0.5 + 48), int(base * 0.7 + 125), int(base * 0.5 + 52)
|
||||||
|
elif fl & 2: # T1 standard walkable
|
||||||
|
r, g, b = int(base * 0.5 + 88), int(base * 0.7 + 115), int(base * 0.4 + 40)
|
||||||
|
elif fl & 1: # T0 narrow only
|
||||||
|
r, g, b = 185, 175, 65
|
||||||
|
else:
|
||||||
|
# Hard obstacle / cliff
|
||||||
|
r, g, b = max(18, base - 18), max(18, base - 18), max(22, base - 14)
|
||||||
|
|
||||||
|
idx = (py * pw + rx) * 3
|
||||||
|
nav_rgb[idx] = min(255, r)
|
||||||
|
nav_rgb[idx + 1] = min(255, g)
|
||||||
|
nav_rgb[idx + 2] = min(255, b)
|
||||||
|
|
||||||
|
# Cover map background: muted terrain + exposure tint
|
||||||
|
tx = min(tac_cols - 1, int(rx * tac_cols / pw))
|
||||||
|
tz = min(tac_rows - 1, int(rz * tac_rows / ph))
|
||||||
|
exp_v = tac[(tz * tac_cols + tx) * 4] if tac_cols > 0 and tac_rows > 0 else 0
|
||||||
|
if fl & 16:
|
||||||
|
cr, cg, cb = 20, 48, 95
|
||||||
|
elif fl & 2:
|
||||||
|
cr = min(255, int(base * 0.85 + exp_v * 0.18))
|
||||||
|
cg = min(255, int(base * 0.90 + 20))
|
||||||
|
cb = min(255, int(base * 0.85))
|
||||||
|
else:
|
||||||
|
cr, cg, cb = 26, 26, 30
|
||||||
|
cov_rgb[idx] = cr
|
||||||
|
cov_rgb[idx + 1] = cg
|
||||||
|
cov_rgb[idx + 2] = cb
|
||||||
|
|
||||||
|
# Overlay sample Detour paths (bright cyan) on nav map
|
||||||
|
for path in paths:
|
||||||
|
for i in range(len(path) - 1):
|
||||||
|
x0, y0 = world_to_px(*path[i])
|
||||||
|
x1, y1 = world_to_px(*path[i + 1])
|
||||||
|
draw_line(nav_rgb, pw, ph, x0, y0, x1, y1, (0, 245, 255), thick=2)
|
||||||
|
|
||||||
|
# Overlay spawns & capture zones on BOTH maps
|
||||||
|
for rgb in (nav_rgb, cov_rgb):
|
||||||
|
for sp in pois.get("team1Spawns", []):
|
||||||
|
x, y = world_to_px(sp["x"], sp["z"])
|
||||||
|
draw_square(rgb, pw, ph, x, y, 5, (40, 130, 255))
|
||||||
|
draw_square(rgb, pw, ph, x, y, 2, (255, 255, 255))
|
||||||
|
for sp in pois.get("team2Spawns", []):
|
||||||
|
x, y = world_to_px(sp["x"], sp["z"])
|
||||||
|
draw_square(rgb, pw, ph, x, y, 5, (255, 65, 65))
|
||||||
|
draw_square(rgb, pw, ph, x, y, 2, (255, 255, 255))
|
||||||
|
for cap in pois.get("captureZones", []):
|
||||||
|
x, y = world_to_px(cap["x"], cap["z"])
|
||||||
|
rad_px = max(8, int(cap.get("radius", 25.0) / max(1.0, max_x - min_x) * pw))
|
||||||
|
draw_circle(rgb, pw, ph, x, y, rad_px, (255, 215, 0), fill=False)
|
||||||
|
draw_circle(rgb, pw, ph, x, y, 4, (255, 230, 40), fill=True)
|
||||||
|
|
||||||
|
# Overlay covers on cover map: Blue=FULL, Green=HULLDOWN, Yellow=PEEK
|
||||||
|
for c in covers:
|
||||||
|
px_w, py_w, pz_w = c[0], c[1], c[2]
|
||||||
|
dx, dz = c[3], c[4]
|
||||||
|
peek_l = (c[7], c[9])
|
||||||
|
peek_r = (c[10], c[12])
|
||||||
|
kind = c[16]
|
||||||
|
has_pl, has_pr = c[17], c[18]
|
||||||
|
x, y = world_to_px(px_w, pz_w)
|
||||||
|
col = (60, 165, 255) if kind == 1 else (55, 240, 100)
|
||||||
|
draw_circle(cov_rgb, pw, ph, x, y, 2, col, fill=True)
|
||||||
|
# Direction tick pointing toward blocked threat
|
||||||
|
x2, y2 = world_to_px(px_w + dx * 8.0, pz_w + dz * 8.0)
|
||||||
|
draw_line(cov_rgb, pw, ph, x, y, x2, y2, col, thick=1)
|
||||||
|
if has_pl:
|
||||||
|
lx, ly = world_to_px(*peek_l)
|
||||||
|
draw_circle(cov_rgb, pw, ph, lx, ly, 1, (255, 240, 60), fill=True)
|
||||||
|
if has_pr:
|
||||||
|
rx2, ry2 = world_to_px(*peek_r)
|
||||||
|
draw_circle(cov_rgb, pw, ph, rx2, ry2, 1, (255, 240, 60), fill=True)
|
||||||
|
|
||||||
|
nav_out = os.path.join(args.out_dir, f"{args.name}_nav.png")
|
||||||
|
cov_out = os.path.join(args.out_dir, f"{args.name}_cover.png")
|
||||||
|
write_png(nav_out, pw, ph, nav_rgb)
|
||||||
|
write_png(cov_out, pw, ph, cov_rgb)
|
||||||
|
print(f"Rendered {nav_out} and {cov_out} (covers={len(covers)}, paths={len(paths)})")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in new issue
Block a user