2007-04-16

This commit is contained in:
Anonymous Maarten committed 2015-12-03 01:37:37 +01:00
1 parent 78c27f03c8
commit e20673c2cd
120 files changed
+9578 -1036

No files matched your search

+205
View File
@@ -0,0 +1,205 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// discrete time simulation clock for OpenSteerDemo
//
// Keeps track of real clock time and simulation time. Encapsulates the time
// API of the underlying operating system. Can be put in either "as fast as
// possible" variable time step mode (where simulation time steps are based on
// real time elapsed between updates), or in fixed "target FPS" mode where the
// simulation steps are constrained to start on 1/FPS boundaries (e.g. on a 60
// hertz video game console). Also handles the notion of "pausing" simulation
// time.
//
// Usage: allocate a clock, set its "paused" or "targetFPS" parameters, then
// call updateGlobalSimulationClock before each simulation step.
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 11-11-03 cwr: another overhaul: support aniamtion mode, switch to
// functional API, move smoothed stats inside this class
// 09-24-02 cwr: major overhaul
// 06-26-02 cwr: created
//
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_CLOCK_H
#define OPENSTEER_CLOCK_H
#include "OpenSteer/Utilities.h"
#if defined (_XBOX)
#include <xtl.h>
#elif defined (_WIN32)
#include <windows.h>
#endif
namespace OpenSteer {
class Clock
{
public:
// constructor
Clock ();
// update this clock, called exactly once per simulation step ("frame")
void update (void);
// returns the number of seconds of real time (represented as a float)
// since the clock was first updated.
float realTimeSinceFirstClockUpdate (void);
// force simulation time ahead, ignoring passage of real time.
// Used for OpenSteerDemo's "single step forward" and animation mode
float advanceSimulationTimeOneFrame (void);
void advanceSimulationTime (const float seconds);
// "wait" until next frame time
void frameRateSync (void);
// main clock modes: variable or fixed frame rate, real-time or animation
// mode, running or paused.
private:
// run as fast as possible, simulation time is based on real time
bool variableFrameRateMode;
// fixed frame rate (ignored when in variable frame rate mode) in
// real-time mode this is a "target", in animation mode it is absolute
int fixedFrameRate;
// used for offline, non-real-time applications
bool animationMode;
// is simulation running or paused?
bool paused;
public:
int getFixedFrameRate (void) {return fixedFrameRate;}
int setFixedFrameRate (int ffr) {return fixedFrameRate = ffr;}
bool getAnimationMode (void) {return animationMode;}
bool setAnimationMode (bool am) {return animationMode = am;}
bool getVariableFrameRateMode (void) {return variableFrameRateMode;}
bool setVariableFrameRateMode (bool vfrm)
{return variableFrameRateMode = vfrm;}
bool togglePausedState (void) {return (paused = !paused);};
bool getPausedState (void) {return paused;};
bool setPausedState (bool newPS) {return paused = newPS;};
// clock keeps track of "smoothed" running average of recent frame rates.
// When a fixed frame rate is used, a running average of "CPU load" is
// kept (aka "non-wait time", the percentage of each frame time (time
// step) that the CPU is busy).
private:
float smoothedFPS;
float smoothedUsage;
void updateSmoothedRegisters (void)
{
const float rate = getSmoothingRate ();
if (elapsedRealTime > 0)
blendIntoAccumulator (rate, 1 / elapsedRealTime, smoothedFPS);
if (! getVariableFrameRateMode ())
blendIntoAccumulator (rate, getUsage (), smoothedUsage);
}
public:
float getSmoothedFPS (void) const {return smoothedFPS;}
float getSmoothedUsage (void) const {return smoothedUsage;}
float getSmoothingRate (void) const
{
if (smoothedFPS == 0) return 1; else return elapsedRealTime * 1.5f;
}
float getUsage (void)
{
// run time per frame over target frame time (as a percentage)
return ((100 * elapsedNonWaitRealTime) / (1.0f / fixedFrameRate));
}
// clock state member variables and public accessors for them
private:
// real "wall clock" time since launch
float totalRealTime;
// total time simulation has run
float totalSimulationTime;
// total time spent paused
float totalPausedTime;
// sum of (non-realtime driven) advances to simulation time
float totalAdvanceTime;
// interval since last simulation time
// (xxx does this need to be stored in the instance? xxx)
float elapsedSimulationTime;
// interval since last clock update time
// (xxx does this need to be stored in the instance? xxx)
float elapsedRealTime;
// interval since last clock update,
// exclusive of time spent waiting for frame boundary when targetFPS>0
float elapsedNonWaitRealTime;
public:
float getTotalRealTime (void) {return totalRealTime;}
float getTotalSimulationTime (void) {return totalSimulationTime;}
float getTotalPausedTime (void) {return totalPausedTime;}
float getTotalAdvanceTime (void) {return totalAdvanceTime;}
float getElapsedSimulationTime (void) {return elapsedSimulationTime;}
float getElapsedRealTime (void) {return elapsedRealTime;}
float getElapsedNonWaitRealTime (void) {return elapsedNonWaitRealTime;}
private:
// "manually" advance clock by this amount on next update
float newAdvanceTime;
// "Calendar time" when this clock was first updated
#ifdef _WIN32
// from QueryPerformanceCounter on Windows
LONGLONG basePerformanceCounter;
#else
// from gettimeofday on Linux and Mac OS X
int baseRealTimeSec;
int baseRealTimeUsec;
#endif
};
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_CLOCK_H
+337
View File
@@ -0,0 +1,337 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// Proximity
//
// Data structures for accelerating proximity/locality/neighborhood queries
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 06-20-01 cwr: created
//
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_PROXIMITY_H
#define OPENSTEER_PROXIMITY_H
#include <algorithm>
#include <vector>
#include "OpenSteer/Vec3.h"
#include "OpenSteer/lq.h" // XXX temp?
namespace OpenSteer {
// ----------------------------------------------------------------------------
// "tokens" are the objects manipulated by the spatial database
template <class ContentType>
class AbstractTokenForProximityDatabase
{
public:
virtual ~AbstractTokenForProximityDatabase () {}
// the client object calls this each time its position changes
virtual void updateForNewPosition (const Vec3& position) = 0;
// find all neighbors within the given sphere (as center and radius)
virtual void findNeighbors (const Vec3& center,
const float radius,
std::vector<ContentType>& results) = 0;
#ifndef NO_LQ_BIN_STATS
// only meaningful for LQProximityDatabase, provide dummy default
virtual void getBinPopulationStats (int& min, int& max, float& average)
{min=max=0; average=0.0;}
#endif // NO_LQ_BIN_STATS
};
// ----------------------------------------------------------------------------
// abstract type for all kinds of proximity databases
template <class ContentType>
class AbstractProximityDatabase
{
public:
// type for the "tokens" manipulated by this spatial database
typedef AbstractTokenForProximityDatabase<ContentType> tokenType;
virtual ~AbstractProximityDatabase() { /* Nothing to do? */ }
// allocate a token to represent a given client object in this database
virtual tokenType* allocateToken (ContentType parentObject) = 0;
// insert
// XXX maybe this should return an iterator?
// XXX see http://www.sgi.com/tech/stl/set.html
// virtual void insert (const ContentType& x) = 0;
// XXX name?
// returns the number of tokens in the proximity database
virtual int getPopulation (void) = 0;
};
// ----------------------------------------------------------------------------
// This is the "brute force" O(n^2) approach implemented in terms of the
// AbstractProximityDatabase protocol so it can be compared directly to other
// approaches. (e.g. the Boids plugin allows switching at runtime.)
template <class ContentType>
class BruteForceProximityDatabase
: public AbstractProximityDatabase<ContentType>
{
public:
// constructor
BruteForceProximityDatabase (void)
{
}
// destructor
virtual ~BruteForceProximityDatabase ()
{
}
// "token" to represent objects stored in the database
class tokenType : public AbstractTokenForProximityDatabase<ContentType>
{
public:
// constructor
tokenType (ContentType parentObject, BruteForceProximityDatabase& pd)
{
// store pointer to our associated database and the object this
// token represents, and store this token on the database's vector
bfpd = &pd;
object = parentObject;
bfpd->group.push_back (this);
}
// destructor
virtual ~tokenType ()
{
// remove this token from the database's vector
bfpd->group.erase (std::find (bfpd->group.begin(),
bfpd->group.end(),
this));
}
// the client object calls this each time its position changes
void updateForNewPosition (const Vec3& newPosition)
{
position = newPosition;
}
// find all neighbors within the given sphere (as center and radius)
void findNeighbors (const Vec3& center,
const float radius,
std::vector<ContentType>& results)
{
// loop over all tokens
const float r2 = radius * radius;
for (tokenIterator i = bfpd->group.begin();
i != bfpd->group.end();
i++)
{
const Vec3 offset = center - (**i).position;
const float d2 = offset.lengthSquared();
// push onto result vector when within given radius
if (d2 < r2) results.push_back ((**i).object);
}
}
private:
BruteForceProximityDatabase* bfpd;
ContentType object;
Vec3 position;
};
typedef std::vector<tokenType*> tokenVector;
typedef typename tokenVector::const_iterator tokenIterator;
// allocate a token to represent a given client object in this database
tokenType* allocateToken (ContentType parentObject)
{
return new tokenType (parentObject, *this);
}
// return the number of tokens currently in the database
int getPopulation (void)
{
return (int) group.size();
}
private:
// STL vector containing all tokens in database
tokenVector group;
};
// ----------------------------------------------------------------------------
// A AbstractProximityDatabase-style wrapper for the LQ bin lattice system
template <class ContentType>
class LQProximityDatabase : public AbstractProximityDatabase<ContentType>
{
public:
// constructor
LQProximityDatabase (const Vec3& center,
const Vec3& dimensions,
const Vec3& divisions)
{
const Vec3 halfsize (dimensions * 0.5f);
const Vec3 origin (center - halfsize);
lq = lqCreateDatabase (origin.x, origin.y, origin.z,
dimensions.x, dimensions.y, dimensions.z,
(int) round (divisions.x),
(int) round (divisions.y),
(int) round (divisions.z));
}
// destructor
virtual ~LQProximityDatabase ()
{
lqDeleteDatabase (lq);
lq = NULL;
}
// "token" to represent objects stored in the database
class tokenType : public AbstractTokenForProximityDatabase<ContentType>
{
public:
// constructor
tokenType (ContentType parentObject, LQProximityDatabase& lqsd)
{
lqInitClientProxy (&proxy, parentObject);
lq = lqsd.lq;
}
// destructor
virtual ~tokenType (void)
{
lqRemoveFromBin (&proxy);
}
// the client object calls this each time its position changes
void updateForNewPosition (const Vec3& p)
{
lqUpdateForNewLocation (lq, &proxy, p.x, p.y, p.z);
}
// find all neighbors within the given sphere (as center and radius)
void findNeighbors (const Vec3& center,
const float radius,
std::vector<ContentType>& results)
{
lqMapOverAllObjectsInLocality (lq,
center.x, center.y, center.z,
radius,
perNeighborCallBackFunction,
(void*)&results);
}
// called by LQ for each clientObject in the specified neighborhood:
// push that clientObject onto the ContentType vector in void*
// clientQueryState
// (parameter names commented out to prevent compiler warning from "-W")
static void perNeighborCallBackFunction (void* clientObject,
float /*distanceSquared*/,
void* clientQueryState)
{
typedef std::vector<ContentType> ctv;
ctv& results = *((ctv*) clientQueryState);
results.push_back ((ContentType) clientObject);
}
#ifndef NO_LQ_BIN_STATS
// Get statistics about bin populations: min, max and
// average of non-empty bins.
void getBinPopulationStats (int& min, int& max, float& average)
{
lqGetBinPopulationStats (lq, &min, &max, &average);
}
#endif // NO_LQ_BIN_STATS
private:
lqClientProxy proxy;
lqDB* lq;
};
// allocate a token to represent a given client object in this database
tokenType* allocateToken (ContentType parentObject)
{
return new tokenType (parentObject, *this);
}
// count the number of tokens currently in the database
int getPopulation (void)
{
int count = 0;
lqMapOverAllObjects (lq, counterCallBackFunction, &count);
return count;
}
// (parameter names commented out to prevent compiler warning from "-W")
static void counterCallBackFunction (void* /*clientObject*/,
float /*distanceSquared*/,
void* clientQueryState)
{
int& counter = *(int*)clientQueryState;
counter++;
}
private:
lqDB* lq;
};
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_PROXIMITY_H
+514
View File
@@ -0,0 +1,514 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
//
// Utilities for OpenSteering
//
// 08-06-05 bk: added functions to clamp values to a certain value range, to
// compare values using a tolerance, and so on.
// 10-04-04 bk: put everything into the OpenSteer namespace
// 07-09-02 cwr: created
//
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_UTILITIES_H
#define OPENSTEER_UTILITIES_H
#include <iostream> // for ostream, <<, etc.
#include <cstdlib> // for rand, etc.
#include <cfloat> // for FLT_MAX, etc.
#include <cmath> // for sqrt, etc.
#include <vector> // for std::vector
#include <cassert> // for assert
#include <limits> // for numeric_limits
// ----------------------------------------------------------------------------
// For the sake of Windows, apparently this is a "Linux/Unix thing"
#ifndef OPENSTEER_M_PI
#define OPENSTEER_M_PI 3.14159265358979323846f
#endif
#ifdef _MSC_VER
#undef min
#undef max
#endif
namespace OpenSteer {
// ----------------------------------------------------------------------------
// Generic interpolation
template<class T> inline T interpolate (float alpha, const T& x0, const T& x1)
{
return x0 + ((x1 - x0) * alpha);
}
// ----------------------------------------------------------------------------
// Random number utilities
// Returns a float randomly distributed between 0 and 1
inline float frandom01 (void)
{
return (((float) rand ()) / ((float) RAND_MAX));
}
// Returns a float randomly distributed between lowerBound and upperBound
inline float frandom2 (float lowerBound, float upperBound)
{
return lowerBound + (frandom01 () * (upperBound - lowerBound));
}
// ----------------------------------------------------------------------------
// Constrain a given value (x) to be between two (ordered) bounds: min
// and max. Returns x if it is between the bounds, otherwise returns
// the nearer bound.
inline float clip (const float x, const float min, const float max)
{
if (x < min) return min;
if (x > max) return max;
return x;
}
// ----------------------------------------------------------------------------
// remap a value specified relative to a pair of bounding values
// to the corresponding value relative to another pair of bounds.
// Inspired by (dyna:remap-interval y y0 y1 z0 z1)
inline float remapInterval (float x,
float in0, float in1,
float out0, float out1)
{
// uninterpolate: what is x relative to the interval in0:in1?
float relative = (x - in0) / (in1 - in0);
// now interpolate between output interval based on relative x
return interpolate (relative, out0, out1);
}
// Like remapInterval but the result is clipped to remain between
// out0 and out1
inline float remapIntervalClip (float x,
float in0, float in1,
float out0, float out1)
{
// uninterpolate: what is x relative to the interval in0:in1?
float relative = (x - in0) / (in1 - in0);
// now interpolate between output interval based on relative x
return interpolate (clip (relative, 0, 1), out0, out1);
}
// ----------------------------------------------------------------------------
// classify a value relative to the interval between two bounds:
// returns -1 when below the lower bound
// returns 0 when between the bounds (inside the interval)
// returns +1 when above the upper bound
inline int intervalComparison (float x, float lowerBound, float upperBound)
{
if (x < lowerBound) return -1;
if (x > upperBound) return +1;
return 0;
}
// ----------------------------------------------------------------------------
inline float scalarRandomWalk (const float initial,
const float walkspeed,
const float min,
const float max)
{
const float next = initial + (((frandom01() * 2) - 1) * walkspeed);
if (next < min) return min;
if (next > max) return max;
return next;
}
// ----------------------------------------------------------------------------
inline float square (float x)
{
return x * x;
}
// ----------------------------------------------------------------------------
// for debugging: prints one line with a given C expression, an equals sign,
// and the value of the expression. For example "angle = 35.6"
#define debugPrint(e) (std::cout << #e" = " << (e) << std::endl << std::flush)
// ----------------------------------------------------------------------------
// blends new values into an accumulator to produce a smoothed time series
//
// Modifies its third argument, a reference to the float accumulator holding
// the "smoothed time series."
//
// The first argument (smoothRate) is typically made proportional to "dt" the
// simulation time step. If smoothRate is 0 the accumulator will not change,
// if smoothRate is 1 the accumulator will be set to the new value with no
// smoothing. Useful values are "near zero".
//
// Usage:
// blendIntoAccumulator (dt * 0.4f, currentFPS, smoothedFPS);
template<class T>
inline void blendIntoAccumulator (const float smoothRate,
const T& newValue,
T& smoothedAccumulator)
{
smoothedAccumulator = interpolate (clip (smoothRate, 0, 1),
smoothedAccumulator,
newValue);
}
// ----------------------------------------------------------------------------
// given a new Angle and an old angle, adjust the new for angle wraparound (the
// 0->360 flip), returning a value equivalent to newAngle, but closest in
// absolute value to oldAngle. For radians fullCircle = OPENSTEER_M_PI*2, for degrees
// fullCircle = 360. Based on code in stuart/bird/fish demo's camera.cc
//
// (not currently used)
/*
inline float distance1D (const float a, const float b)
{
const float d = a - b;
return (d > 0) ? d : -d;
}
float adjustForAngleWraparound (float newAngle,
float oldAngle,
float fullCircle)
{
// adjust newAngle for angle wraparound: consider its current value (a)
// as well as the angle 2pi larger (b) and 2pi smaller (c). Select the
// one closer (magnitude of difference) to the current value of oldAngle.
const float a = newAngle;
const float b = newAngle + fullCircle;
const float c = newAngle - fullCircle;
const float ad = distance1D (a, oldAngle);
const float bd = distance1D (b, oldAngle);
const float cd = distance1D (c, oldAngle);
if ((bd < ad) && (bd < cd)) return b;
if ((cd < ad) && (cd < bd)) return c;
return a;
}
*/
// ----------------------------------------------------------------------------
// Functions to encapsulate cross-platform differences for several <cmath>
// functions. Specifically, the C++ standard says that these functions are
// in the std namespace (std::sqrt, etc.) Apparently the MS VC6 compiler (or
// its header files) do not implement this correctly and the function names
// are in the global namespace. We hope these -XXX versions are a temporary
// expedient, to be removed later.
#ifdef _WIN32
inline float floorXXX (float x) {return ::floor (x);}
inline float sqrtXXX (float x) {return ::sqrt (x);}
inline float sinXXX (float x) {return ::sin (x);}
inline float cosXXX (float x) {return ::cos (x);}
inline float absXXX (float x) {return ::abs (x);}
inline int absXXX (int x) {return ::abs (x);}
inline float maxXXX (float x, float y) {if (x > y) return x; else return y;}
inline float minXXX (float x, float y) {if (x < y) return x; else return y;}
#else
inline float floorXXX (float x) {return std::floor (x);}
inline float sqrtXXX (float x) {return std::sqrt (x);}
inline float sinXXX (float x) {return std::sin (x);}
inline float cosXXX (float x) {return std::cos (x);}
inline float absXXX (float x) {return std::abs (x);}
inline int absXXX (int x) {return std::abs (x);}
inline float maxXXX (float x, float y) {return std::max (x, y);}
inline float minXXX (float x, float y) {return std::min (x, y);}
#endif
// ----------------------------------------------------------------------------
// round (x) "round off" x to the nearest integer (as a float value)
//
// This is a Gnu-sanctioned(?) post-ANSI-Standard(?) extension (as in
// http://www.opengroup.org/onlinepubs/007904975/basedefs/math.h.html)
// which may not be present in all C++ environments. It is defined in
// math.h headers in Linux and Mac OS X, but apparently not in Win32:
#ifdef _WIN32
inline float round (float x)
{
if (x < 0)
return -floorXXX (0.5f - x);
else
return floorXXX (0.5f + x);
}
#else
inline float round( float x )
{
return ::round( x );
}
#endif
/**
* Returns @a valueToClamp clamped to the range @a minValue - @a maxValue.
*/
template< typename T >
T
clamp( T const& valueToClamp, T const& minValue, T const& maxValue) {
assert( minValue <= maxValue && "minValue must be lesser or equal to maxValue." );
if ( valueToClamp < minValue ) {
return minValue;
} else if ( valueToClamp > maxValue ) {
return maxValue;
}
return valueToClamp;
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline float modulo( float x, float y ) {
assert( 0.0f != y && "Division by zero." );
return std::fmod( x, y );
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline double modulo( double x, double y ) {
assert( 0.0 != y && "Division by zero." );
return std::fmod( x, y );
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline long double modulo( long double x, long double y ) {
assert( 0.0 != y && "Division by zero." );
return std::fmod( x, y );
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline short modulo( short x, short y ) {
assert( 0 != y && "Division by zero." );
return x % y;
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline int modulo( int x, int y ) {
assert( 0 != y && "Division by zero." );
return x % y;
}
/**
* Returns the floating point remainder of the division of @a x by @a y.
* If @a y is @c 0 the behavior is undefined.
*/
inline long modulo( long x, long y ) {
assert( 0 != y && "Division by zero." );
return x % y;
}
/**
* Returns <code>value</code> if <code>value >= 0 </code>, otherwise
* <code>-value</code>.
*/
template< typename T >
T abs( T const& value ) {
return absXXX( value );
}
/**
* Returns the maximum of the three values @a v0, @a v1, and @a v2.
*
* @todo Write a unit test.
*/
template< typename T >
T
max( T const& v0, T const& v1, T const& v2 ) {
return maxXXX( v0, maxXXX( v1, v2 ) );
}
/**
* Returns the minimum of the three values @a v0, @a v1, and @a v2.
*
* @todo Write a unit test.
*/
template< typename T >
T
min( T const& v0, T const& v1, T const& v2 ) {
return minXXX( v0, minXXX( v1, v2 ) );
}
/**
* Compares the absolute value of @a v with @a tolerance.
*
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @todo Write a unit test.
*/
template< typename T >
bool
isZero( T const& v, T const& tolerance = std::numeric_limits< T >::epsilon() ) {
return abs( v ) <= tolerance;
}
/**
* Compares @a lhs with @a rhs given a specific @a tolerance.
*
* @attention Adapt @a tolerance to the range of values of @a lhs and
* @a rhs.
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @return <code>abs( lhs - rhs ) <= tolerance</code>
*
* @todo Write a unit test.
*/
template< typename T >
bool
equalsAbsolute( T const& lhs, T const& rhs, T const& tolerance = std::numeric_limits< T >::epsilon() ) {
return isZero( lhs - rhs, tolerance );
}
/**
* Compares @a lhs with @a rhs given a specific @a tolerance taking the
* range of values into account.
*
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @return <code>abs( lhs - rhs ) <= tolerance * max( abs( lhs ), abs( rhs ), 1 )</code>
*
* @todo Write a unit test.
*/
template< typename T >
bool
equalsRelative( T const& lhs, T const& rhs, T const& tolerance = std::numeric_limits< T >::epsilon() ) {
return isZero( lhs - rhs, tolerance * max( abs( lhs ), abs( rhs ), T( 1 ) ) );
}
/**
* Approximately compares @a lhs with @a rhs given a specific @a tolerance
* taking the range of values into account.
*
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @return <code>abs( lhs - rhs ) <= tolerance * ( abs( lhs ) + abs( rhs ) + 1 )</code>
*
* @todo Write a unit test.
*/
template< typename T >
bool
equalsRelativeApproximately( T const& lhs, T const& rhs, T const& tolerance = std::numeric_limits< T >::epsilon() ) {
return isZero( lhs - rhs, tolerance * ( abs( lhs ) + abs( rhs ) + T( 1 ) ) );
}
/**
* Shrinks the capacity of a std::vector to fit its content.
*
* See Scott Meyer, Effective STL, Addison-Wesley, 2001, pp. 77--79.
*/
template< typename T >
void shrinkToFit( std::vector< T >& v ) {
std::vector< T >( v ).swap( v );
}
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_UTILITIES_H
+382
View File
@@ -0,0 +1,382 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
// Vec3: OpenSteer's generic type for 3d vectors
//
// This file defines the class Vec3, which is used throughout OpenSteer to
// manipulate 3d geometric data. It includes standard vector operations (like
// vector addition, subtraction, scale, dot, cross...) and more idiosyncratic
// utility functions.
//
// When integrating OpenSteer into a preexisting 3d application, it may be
// important to use the 3d vector type of that application. In that case Vec3
// can be changed to inherit from the preexisting application' vector type and
// to match the interface used by OpenSteer to the interface provided by the
// preexisting 3d vector type.
//
// 10-04-04 bk: put everything into the OpenSteer namespace
// 03-26-03 cwr: created to replace for Hiranabe-san's execellent but larger
// vecmath package (http://objectclub.esm.co.jp/vecmath/)
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_VEC3_H
#define OPENSTEER_VEC3_H
#include "OpenSteer/Utilities.h" // for interpolate, etc.
namespace OpenSteer {
// ----------------------------------------------------------------------------
class Vec3
{
public:
// ----------------------------------------- generic 3d vector operations
// three-dimensional Cartesian coordinates
float x, y, z;
// constructors
Vec3 (void): x( 0.0f ), y( 0.0f ), z( 0.0f ) {}
Vec3 (float X, float Y, float Z) : x( X ), y( Y ), z( Z ) {}
// vector addition
Vec3 operator+ (const Vec3& v) const {return Vec3 (x+v.x, y+v.y, z+v.z);}
// vector subtraction
Vec3 operator- (const Vec3& v) const {return Vec3 (x-v.x, y-v.y, z-v.z);}
// unary minus
Vec3 operator- (void) const {return Vec3 (-x, -y, -z);}
// vector times scalar product (scale length of vector times argument)
Vec3 operator* (const float s) const {return Vec3 (x * s, y * s, z * s);}
// vector divided by a scalar (divide length of vector by argument)
Vec3 operator/ (const float s) const {return Vec3 (x / s, y / s, z / s);}
// dot product
float dot (const Vec3& v) const {return (x * v.x) + (y * v.y) + (z * v.z);}
// length
float length (void) const {return sqrtXXX (lengthSquared ());}
// length squared
float lengthSquared (void) const {return this->dot (*this);}
// normalize: returns normalized version (parallel to this, length = 1)
Vec3 normalize (void) const
{
// skip divide if length is zero
const float len = length ();
return (len>0) ? (*this)/len : (*this);
}
// cross product (modify "*this" to be A x B)
// [XXX side effecting -- deprecate this function? XXX]
void cross(const Vec3& a, const Vec3& b)
{
*this = Vec3 ((a.y * b.z) - (a.z * b.y),
(a.z * b.x) - (a.x * b.z),
(a.x * b.y) - (a.y * b.x));
}
// assignment
Vec3 operator= (const Vec3& v) {x=v.x; y=v.y; z=v.z; return *this;}
// set XYZ coordinates to given three floats
Vec3 set (const float _x, const float _y, const float _z)
{x = _x; y = _y; z = _z; return *this;}
// +=
Vec3 operator+= (const Vec3& v) {return *this = (*this + v);}
// -=
Vec3 operator-= (const Vec3& v) {return *this = (*this - v);}
// *=
Vec3 operator*= (const float& s) {return *this = (*this * s);}
Vec3 operator/=( float d ) { return *this = (*this / d); }
// equality/inequality
bool operator== (const Vec3& v) const {return x==v.x && y==v.y && z==v.z;}
bool operator!= (const Vec3& v) const {return !(*this == v);}
// @todo Remove - use @c distance from the Vec3Utilitites header instead.
// XXX experimental (4-1-03 cwr): is this the right approach? defining
// XXX "Vec3 distance (vec3, Vec3)" collided with STL's distance template.
static float distance (const Vec3& a, const Vec3& b){ return(a-b).length();}
// --------------------------- utility member functions used in OpenSteer
// return component of vector parallel to a unit basis vector
// (IMPORTANT NOTE: assumes "basis" has unit magnitude (length==1))
inline Vec3 parallelComponent (const Vec3& unitBasis) const
{
const float projection = this->dot (unitBasis);
return unitBasis * projection;
}
// return component of vector perpendicular to a unit basis vector
// (IMPORTANT NOTE: assumes "basis" has unit magnitude (length==1))
inline Vec3 perpendicularComponent (const Vec3& unitBasis) const
{
return (*this) - parallelComponent (unitBasis);
}
// clamps the length of a given vector to maxLength. If the vector is
// shorter its value is returned unaltered, if the vector is longer
// the value returned has length of maxLength and is paralle to the
// original input.
Vec3 truncateLength (const float maxLength) const
{
const float maxLengthSquared = maxLength * maxLength;
const float vecLengthSquared = this->lengthSquared ();
if (vecLengthSquared <= maxLengthSquared)
return *this;
else
return (*this) * (maxLength / sqrtXXX (vecLengthSquared));
}
// forces a 3d position onto the XZ (aka y=0) plane
Vec3 setYtoZero (void) const {return Vec3 (this->x, 0, this->z);}
// rotate this vector about the global Y (up) axis by the given angle
Vec3 rotateAboutGlobalY (float angle) const
{
const float s = sinXXX (angle);
const float c = cosXXX (angle);
return Vec3 ((this->x * c) + (this->z * s),
(this->y),
(this->z * c) - (this->x * s));
}
// version for caching sin/cos computation
Vec3 rotateAboutGlobalY (float angle, float& sin, float& cos) const
{
// is both are zero, they have not be initialized yet
if (sin==0 && cos==0)
{
sin = sinXXX (angle);
cos = cosXXX (angle);
}
return Vec3 ((this->x * cos) + (this->z * sin),
(this->y),
(this->z * cos) - (this->x * sin));
}
// if this position is outside sphere, push it back in by one diameter
Vec3 sphericalWrapAround (const Vec3& center, float radius)
{
const Vec3 offset = *this - center;
const float r = offset.length();
if (r > radius)
return *this + ((offset/r) * radius * -2);
else
return *this;
}
// names for frequently used vector constants
static const Vec3 zero;
static const Vec3 side;
static const Vec3 up;
static const Vec3 forward;
};
// ----------------------------------------------------------------------------
// scalar times vector product ("float * Vec3")
inline Vec3 operator* (float s, const Vec3& v) {return v*s;}
// return cross product a x b
inline Vec3 crossProduct(const Vec3& a, const Vec3& b)
{
Vec3 result((a.y * b.z) - (a.z * b.y),
(a.z * b.x) - (a.x * b.z),
(a.x * b.y) - (a.y * b.x));
return result;
}
// ----------------------------------------------------------------------------
// default character stream output method
#ifndef NOT_OPENSTEERDEMO // only when building OpenSteerDemo
inline std::ostream& operator<< (std::ostream& o, const Vec3& v)
{
return o << "(" << v.x << "," << v.y << "," << v.z << ")";
}
#endif // NOT_OPENSTEERDEMO
// ----------------------------------------------------------------------------
// Returns a position randomly distributed inside a sphere of unit radius
// centered at the origin. Orientation will be random and length will range
// between 0 and 1
Vec3 RandomVectorInUnitRadiusSphere (void);
// ----------------------------------------------------------------------------
// Returns a position randomly distributed on a disk of unit radius
// on the XZ (Y=0) plane, centered at the origin. Orientation will be
// random and length will range between 0 and 1
Vec3 randomVectorOnUnitRadiusXZDisk (void);
// ----------------------------------------------------------------------------
// Returns a position randomly distributed on the surface of a sphere
// of unit radius centered at the origin. Orientation will be random
// and length will be 1
inline Vec3 RandomUnitVector (void)
{
return RandomVectorInUnitRadiusSphere().normalize();
}
// ----------------------------------------------------------------------------
// Returns a position randomly distributed on a circle of unit radius
// on the XZ (Y=0) plane, centered at the origin. Orientation will be
// random and length will be 1
inline Vec3 RandomUnitVectorOnXZPlane (void)
{
return RandomVectorInUnitRadiusSphere().setYtoZero().normalize();
}
// ----------------------------------------------------------------------------
// used by limitMaxDeviationAngle / limitMinDeviationAngle below
Vec3 vecLimitDeviationAngleUtility (const bool insideOrOutside,
const Vec3& source,
const float cosineOfConeAngle,
const Vec3& basis);
// ----------------------------------------------------------------------------
// Enforce an upper bound on the angle by which a given arbitrary vector
// diviates from a given reference direction (specified by a unit basis
// vector). The effect is to clip the "source" vector to be inside a cone
// defined by the basis and an angle.
inline Vec3 limitMaxDeviationAngle (const Vec3& source,
const float cosineOfConeAngle,
const Vec3& basis)
{
return vecLimitDeviationAngleUtility (true, // force source INSIDE cone
source,
cosineOfConeAngle,
basis);
}
// ----------------------------------------------------------------------------
// Enforce a lower bound on the angle by which a given arbitrary vector
// diviates from a given reference direction (specified by a unit basis
// vector). The effect is to clip the "source" vector to be outside a cone
// defined by the basis and an angle.
inline Vec3 limitMinDeviationAngle (const Vec3& source,
const float cosineOfConeAngle,
const Vec3& basis)
{
return vecLimitDeviationAngleUtility (false, // force source OUTSIDE cone
source,
cosineOfConeAngle,
basis);
}
// ----------------------------------------------------------------------------
// Returns the distance between a point and a line. The line is defined in
// terms of a point on the line ("lineOrigin") and a UNIT vector parallel to
// the line ("lineUnitTangent")
inline float distanceFromLine (const Vec3& point,
const Vec3& lineOrigin,
const Vec3& lineUnitTangent)
{
const Vec3 offset = point - lineOrigin;
const Vec3 perp = offset.perpendicularComponent (lineUnitTangent);
return perp.length();
}
// ----------------------------------------------------------------------------
// given a vector, return a vector perpendicular to it (note that this
// arbitrarily selects one of the infinitude of perpendicular vectors)
Vec3 findPerpendicularIn3d (const Vec3& direction);
// ----------------------------------------------------------------------------
// candidates for global utility functions
//
// dot
// cross
// length
// distance
// normalized
} // namespace OpenSteer
// ----------------------------------------------------------------------------
#endif // OPENSTEER_VEC3_H
@@ -0,0 +1,96 @@
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
//
// ----------------------------------------------------------------------------
//
// Utilities to work with Vec3.
//
// 05-12-05 bk: Created based on code of PolylinePathway.
//
// ----------------------------------------------------------------------------
#ifndef OPENSTEER_VEC3UTILITIES_H
#define OPENSTEER_VEC3UTILITIES_H
// Include OpenSteer::Vec3
#include "OpenSteer/Vec3.h"
// Include OpenSteer::size_t
#include "OpenSteer/StandardTypes.h"
// Include OpenSteer::equalsRelative
#include "OpenSteer/Utilities.h"
namespace OpenSteer {
/**
* Returns the nearest point on the segment @a segmentPoint0 to
* @a segmentPoint1 from @a point.
*/
OpenSteer::Vec3 nearestPointOnSegment( const Vec3& point,
const Vec3& segmentPoint0,
const Vec3& segmentPoint1 );
/**
* Computes minimum distance from @a point to the line segment defined by
* @a segmentPoint0 and @a segmentPoint1.
*/
float pointToSegmentDistance( const Vec3& point,
const Vec3& segmentPoint0,
const Vec3& segmentPoint1);
/**
* Retuns distance between @a a and @a b.
*/
inline float distance (const Vec3& a, const Vec3& b) {
return (a-b).length();
}
/**
* Elementwise relative tolerance comparison of @a lhs and @a rhs taking
* the range of the elements into account.
*
* See Christer Ericson, Real-Time Collision Detection, Morgan Kaufmann,
* 2005, pp. 441--443.
*
* @todo Rewrite using the stl or providing an own range based function.
*/
inline
bool
equalsRelative( Vec3 const& lhs,
Vec3 const& rhs,
float const& tolerance = std::numeric_limits< float >::epsilon() ) {
return equalsRelative( lhs.x, rhs.x, tolerance ) && equalsRelative( lhs.y, rhs.y ) && equalsRelative( lhs.z, rhs.z );
}
} // namespace OpenSteer
#endif // OPENSTEER_VEC3UTILITIES_H
+323
View File
@@ -0,0 +1,323 @@
/*
// ----------------------------------------------------------------------------
//
//
// OpenSteer -- Steering Behaviors for Autonomous Characters
//
// Copyright (c) 2002-2005, Sony Computer Entertainment America
// Original author: Craig Reynolds <craig_reynolds@playstation.sony.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
// ----------------------------------------------------------------------------
*/
/* ------------------------------------------------------------------ */
/* */
/* Locality Query (LQ) Facility */
/* */
/* ------------------------------------------------------------------ */
/*
This utility is a spatial database which stores objects each of
which is associated with a 3d point (a location in a 3d space).
The points serve as the "search key" for the associated object.
It is intended to efficiently answer "sphere inclusion" queries,
also known as range queries: basically questions like:
Which objects are within a radius R of the location L?
In this context, "efficiently" means significantly faster than the
naive, brute force O(n) testing of all known points. Additionally
it is assumed that the objects move along unpredictable paths, so
that extensive preprocessing (for example, constructing a Delaunay
triangulation of the point set) may not be practical.
The implementation is a "bin lattice": a 3d rectangular array of
brick-shaped (rectangular parallelepipeds) regions of space. Each
region is represented by a pointer to a (possibly empty) doubly-
linked list of objects. All of these sub-bricks are the same
size. All bricks are aligned with the global coordinate axes.
Terminology used here: the region of space associated with a bin
is called a sub-brick. The collection of all sub-bricks is called
the super-brick. The super-brick should be specified to surround
the region of space in which (almost) all the key-points will
exist. If key-points move outside the super-brick everything will
continue to work, but without the speed advantage provided by the
spatial subdivision. For more details about how to specify the
super-brick's position, size and subdivisions see lqCreateDatabase
below.
Overview of usage: an application using this facility would first
create a database with lqCreateDatabase. For each client object
the application wants to put in the database it creates a
lqClientProxy and initializes it with lqInitClientProxy. When a
client object moves, the application calls lqUpdateForNewLocation.
To perform a query lqMapOverAllObjectsInLocality is passed an
application-supplied call-back function to be applied to all
client objects in the locality. See lqCallBackFunction below for
more detail. The lqFindNearestNeighborWithinRadius function can
be used to find a single nearest neighbor using the database.
Note that "locality query" is also known as neighborhood query,
neighborhood search, near neighbor search, and range query. For
additional information on this and related topics see:
http://www.red3d.com/cwr/boids/ips.html
For some description and illustrations of this database in use,
see this paper: http://www.red3d.com/cwr/papers/2000/pip.html
*/
#ifndef _lq_h
#define _lq_h
#ifdef __cplusplus
extern "C"
{
#endif
/* ------------------------------------------------------------------ */
/* */
/* Data types use by LQ */
/* */
/* ------------------------------------------------------------------ */
/* This structure represents the spatial database. Typically one of
these would be created (by a call to lqCreateDatabase) for a given
application. */
typedef struct lqInternalDB lqDB;
/* ------------------------------------------------------------------ */
/* This structure is a proxy for (and contains a pointer to) a client
(application) object in the spatial database. One of these exists
for each client object. This might be included within the
structure of a client object, or could be allocated separately. */
typedef struct lqClientProxy
{
/* previous object in this bin, or NULL */
struct lqClientProxy* prev;
/* next object in this bin, or NULL */
struct lqClientProxy* next;
/* bin ID (pointer to pointer to bin contents list) */
struct lqClientProxy** bin;
/* pointer to client object */
void* object;
/* the object's location ("key point") used for spatial sorting */
float x;
float y;
float z;
} lqClientProxy;
/* ------------------------------------------------------------------ */
/* */
/* Basic API */
/* */
/* ------------------------------------------------------------------ */
/* Allocate and initialize an LQ database, returns a pointer to it.
The application needs to call this before using the LQ facility.
The nine parameters define the properties of the "super-brick":
(1) origin: coordinates of one corner of the super-brick, its
minimum x, y and z extent.
(2) size: the width, height and depth of the super-brick.
(3) the number of subdivisions (sub-bricks) along each axis.
This routine also allocates the bin array, and initialize its
contents. */
lqDB* lqCreateDatabase (float originx, float originy, float originz,
float sizex, float sizey, float sizez,
int divx, int divy, int divz);
/* ------------------------------------------------------------------ */
/* Deallocates the LQ database */
void lqDeleteDatabase (lqDB*);
/* ------------------------------------------------------------------ */
/* The application needs to call this once on each lqClientProxy at
setup time to initialize its list pointers and associate the proxy
with its client object. */
void lqInitClientProxy (lqClientProxy* proxy, void* clientObject);
/* ------------------------------------------------------------------ */
/* Call for each client object every time its location changes. For
example, in an animation application, this would be called each
frame for every moving object. */
void lqUpdateForNewLocation (lqDB* lq,
lqClientProxy* object,
float x, float y, float z);
/* ------------------------------------------------------------------ */
/* Apply an application-specific function to all objects in a certain
locality. The locality is specified as a sphere with a given
center and radius. All objects whose location (key-point) is
within this sphere are identified and the function is applied to
them. The application-supplied function takes three arguments:
(1) a void* pointer to an lqClientProxy's "object".
(2) the square of the distance from the center of the search
locality sphere (x,y,z) to object's key-point.
(3) a void* pointer to the caller-supplied "client query state"
object -- typically NULL, but can be used to store state
between calls to the lqCallBackFunction.
This routine uses the LQ database to quickly reject any objects in
bins which do not overlap with the sphere of interest. Incremental
calculation of index values is used to efficiently traverse the
bins of interest. */
/* type for a pointer to a function used to map over client objects */
typedef void (* lqCallBackFunction) (void* clientObject,
float distanceSquared,
void* clientQueryState);
void lqMapOverAllObjectsInLocality (lqDB* lq,
float x, float y, float z,
float radius,
lqCallBackFunction func,
void* clientQueryState);
/* ------------------------------------------------------------------ */
/* */
/* Other API */
/* */
/* ------------------------------------------------------------------ */
/* Search the database to find the object whose key-point is nearest
to a given location yet within a given radius. That is, it finds
the object (if any) within a given search sphere which is nearest
to the sphere's center. The ignoreObject argument can be used to
exclude an object from consideration (or it can be NULL). This is
useful when looking for the nearest neighbor of an object in the
database, since otherwise it would be its own nearest neighbor.
The function returns a void* pointer to the nearest object, or
NULL if none is found. */
void* lqFindNearestNeighborWithinRadius (lqDB* lq,
float x, float y, float z,
float radius,
void* ignoreObject);
/* ------------------------------------------------------------------ */
/* Adds a given client object to a given bin, linking it into the bin
contents list. */
void lqAddToBin (lqClientProxy* object, lqClientProxy** bin);
/* ------------------------------------------------------------------ */
/* Removes a given client object from its current bin, unlinking it
from the bin contents list. */
void lqRemoveFromBin (lqClientProxy* object);
/* ------------------------------------------------------------------ */
/* Given an LQ database object and the nine basic parameters: fill in
the object's slots, allocate the bin array, and initialize its
contents. Normally the application does NOT call this directly, it
is called by lqCreateDatabase. */
void lqInitDatabase (lqDB* lq,
float originx, float originy, float originz,
float sizex, float sizey, float sizez,
int divx, int divy, int divz);
/* ------------------------------------------------------------------ */
/* Find the bin ID for a location in space. The location is given in
terms of its XYZ coordinates. The bin ID is a pointer to a pointer
to the bin contents list. */
lqClientProxy** lqBinForLocation (lqDB* lq, float x, float y, float z);
/* ------------------------------------------------------------------ */
/* Apply a user-supplied function to all objects in the database,
regardless of locality (cf lqMapOverAllObjectsInLocality) */
void lqMapOverAllObjects (lqDB* lq,
lqCallBackFunction func,
void* clientQueryState);
/* ------------------------------------------------------------------ */
/* Removes (all proxies for) all objects from all bins */
void lqRemoveAllObjects (lqDB* lq);
/* ------------------------------------------------------------------ */
/* Get statistics about bin populations: min, max and average of
non-empty bins. */
#ifndef NO_LQ_BIN_STATS
void lqGetBinPopulationStats (lqDB* lq,
int* min,
int* max,
float* average);
#endif /* NO_LQ_BIN_STATS */
/* ------------------------------------------------------------------ */
#ifndef NULL
#define NULL 0
#endif
/* ------------------------------------------------------------------ */
#ifdef __cplusplus
}
#endif
#endif /* _lq_h */