diff options
author | chai <chaifix@163.com> | 2018-08-24 20:28:40 +0800 |
---|---|---|
committer | chai <chaifix@163.com> | 2018-08-24 20:28:40 +0800 |
commit | 6c4ea0d2270630ca44e5e078d16df0aab684688f (patch) | |
tree | c4b0a97bcdaa32b7be0efdf8955766ccdc8e8270 | |
parent | 42981e814b60007732c05129f1f7a32dda85c7bf (diff) |
*keep light
145 files changed, 158 insertions, 36296 deletions
diff --git a/libjin/3rdparty/Box2D/Box2D.h b/libjin/3rdparty/Box2D/Box2D.h deleted file mode 100644 index 28ae428..0000000 --- a/libjin/3rdparty/Box2D/Box2D.h +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 BOX2D_H -#define BOX2D_H - -/** -\mainpage Box2D API Documentation - -\section intro_sec Getting Started - -For documentation please see http://box2d.org/documentation.html - -For discussion please visit http://box2d.org/forum -*/ - -// These include files constitute the main Box2D API - -#include "Box2D/Common/b2Settings.h" -#include "Box2D/Common/b2Draw.h" -#include "Box2D/Common/b2Timer.h" - -#include "Box2D/Collision/Shapes/b2CircleShape.h" -#include "Box2D/Collision/Shapes/b2EdgeShape.h" -#include "Box2D/Collision/Shapes/b2ChainShape.h" -#include "Box2D/Collision/Shapes/b2PolygonShape.h" - -#include "Box2D/Collision/b2BroadPhase.h" -#include "Box2D/Collision/b2Distance.h" -#include "Box2D/Collision/b2DynamicTree.h" -#include "Box2D/Collision/b2TimeOfImpact.h" - -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2WorldCallbacks.h" -#include "Box2D/Dynamics/b2TimeStep.h" -#include "Box2D/Dynamics/b2World.h" - -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -#include "Box2D/Dynamics/Joints/b2DistanceJoint.h" -#include "Box2D/Dynamics/Joints/b2FrictionJoint.h" -#include "Box2D/Dynamics/Joints/b2GearJoint.h" -#include "Box2D/Dynamics/Joints/b2MotorJoint.h" -#include "Box2D/Dynamics/Joints/b2MouseJoint.h" -#include "Box2D/Dynamics/Joints/b2PrismaticJoint.h" -#include "Box2D/Dynamics/Joints/b2PulleyJoint.h" -#include "Box2D/Dynamics/Joints/b2RevoluteJoint.h" -#include "Box2D/Dynamics/Joints/b2RopeJoint.h" -#include "Box2D/Dynamics/Joints/b2WeldJoint.h" -#include "Box2D/Dynamics/Joints/b2WheelJoint.h" - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2ChainShape.cpp b/libjin/3rdparty/Box2D/Collision/Shapes/b2ChainShape.cpp deleted file mode 100644 index a709585..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2ChainShape.cpp +++ /dev/null @@ -1,198 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/Shapes/b2ChainShape.h" -#include "Box2D/Collision/Shapes/b2EdgeShape.h" -#include <new> -#include <string.h> - -b2ChainShape::~b2ChainShape() -{ - Clear(); -} - -void b2ChainShape::Clear() -{ - b2Free(m_vertices); - m_vertices = nullptr; - m_count = 0; -} - -void b2ChainShape::CreateLoop(const b2Vec2* vertices, int32 count) -{ - b2Assert(m_vertices == nullptr && m_count == 0); - b2Assert(count >= 3); - if (count < 3) - { - return; - } - - for (int32 i = 1; i < count; ++i) - { - b2Vec2 v1 = vertices[i-1]; - b2Vec2 v2 = vertices[i]; - // If the code crashes here, it means your vertices are too close together. - b2Assert(b2DistanceSquared(v1, v2) > b2_linearSlop * b2_linearSlop); - } - - m_count = count + 1; - m_vertices = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - memcpy(m_vertices, vertices, count * sizeof(b2Vec2)); - m_vertices[count] = m_vertices[0]; - m_prevVertex = m_vertices[m_count - 2]; - m_nextVertex = m_vertices[1]; - m_hasPrevVertex = true; - m_hasNextVertex = true; -} - -void b2ChainShape::CreateChain(const b2Vec2* vertices, int32 count) -{ - b2Assert(m_vertices == nullptr && m_count == 0); - b2Assert(count >= 2); - for (int32 i = 1; i < count; ++i) - { - // If the code crashes here, it means your vertices are too close together. - b2Assert(b2DistanceSquared(vertices[i-1], vertices[i]) > b2_linearSlop * b2_linearSlop); - } - - m_count = count; - m_vertices = (b2Vec2*)b2Alloc(count * sizeof(b2Vec2)); - memcpy(m_vertices, vertices, m_count * sizeof(b2Vec2)); - - m_hasPrevVertex = false; - m_hasNextVertex = false; - - m_prevVertex.SetZero(); - m_nextVertex.SetZero(); -} - -void b2ChainShape::SetPrevVertex(const b2Vec2& prevVertex) -{ - m_prevVertex = prevVertex; - m_hasPrevVertex = true; -} - -void b2ChainShape::SetNextVertex(const b2Vec2& nextVertex) -{ - m_nextVertex = nextVertex; - m_hasNextVertex = true; -} - -b2Shape* b2ChainShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2ChainShape)); - b2ChainShape* clone = new (mem) b2ChainShape; - clone->CreateChain(m_vertices, m_count); - clone->m_prevVertex = m_prevVertex; - clone->m_nextVertex = m_nextVertex; - clone->m_hasPrevVertex = m_hasPrevVertex; - clone->m_hasNextVertex = m_hasNextVertex; - return clone; -} - -int32 b2ChainShape::GetChildCount() const -{ - // edge count = vertex count - 1 - return m_count - 1; -} - -void b2ChainShape::GetChildEdge(b2EdgeShape* edge, int32 index) const -{ - b2Assert(0 <= index && index < m_count - 1); - edge->m_type = b2Shape::e_edge; - edge->m_radius = m_radius; - - edge->m_vertex1 = m_vertices[index + 0]; - edge->m_vertex2 = m_vertices[index + 1]; - - if (index > 0) - { - edge->m_vertex0 = m_vertices[index - 1]; - edge->m_hasVertex0 = true; - } - else - { - edge->m_vertex0 = m_prevVertex; - edge->m_hasVertex0 = m_hasPrevVertex; - } - - if (index < m_count - 2) - { - edge->m_vertex3 = m_vertices[index + 2]; - edge->m_hasVertex3 = true; - } - else - { - edge->m_vertex3 = m_nextVertex; - edge->m_hasVertex3 = m_hasNextVertex; - } -} - -bool b2ChainShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - B2_NOT_USED(xf); - B2_NOT_USED(p); - return false; -} - -bool b2ChainShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - b2Assert(childIndex < m_count); - - b2EdgeShape edgeShape; - - int32 i1 = childIndex; - int32 i2 = childIndex + 1; - if (i2 == m_count) - { - i2 = 0; - } - - edgeShape.m_vertex1 = m_vertices[i1]; - edgeShape.m_vertex2 = m_vertices[i2]; - - return edgeShape.RayCast(output, input, xf, 0); -} - -void b2ChainShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - b2Assert(childIndex < m_count); - - int32 i1 = childIndex; - int32 i2 = childIndex + 1; - if (i2 == m_count) - { - i2 = 0; - } - - b2Vec2 v1 = b2Mul(xf, m_vertices[i1]); - b2Vec2 v2 = b2Mul(xf, m_vertices[i2]); - - aabb->lowerBound = b2Min(v1, v2); - aabb->upperBound = b2Max(v1, v2); -} - -void b2ChainShape::ComputeMass(b2MassData* massData, float32 density) const -{ - B2_NOT_USED(density); - - massData->mass = 0.0f; - massData->center.SetZero(); - massData->I = 0.0f; -} diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2ChainShape.h b/libjin/3rdparty/Box2D/Collision/Shapes/b2ChainShape.h deleted file mode 100644 index 7c8c1a8..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2ChainShape.h +++ /dev/null @@ -1,105 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* 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 B2_CHAIN_SHAPE_H -#define B2_CHAIN_SHAPE_H - -#include "Box2D/Collision/Shapes/b2Shape.h" - -class b2EdgeShape; - -/// A chain shape is a free form sequence of line segments. -/// The chain has two-sided collision, so you can use inside and outside collision. -/// Therefore, you may use any winding order. -/// Since there may be many vertices, they are allocated using b2Alloc. -/// Connectivity information is used to create smooth collisions. -/// WARNING: The chain will not collide properly if there are self-intersections. -class b2ChainShape : public b2Shape -{ -public: - b2ChainShape(); - - /// The destructor frees the vertices using b2Free. - ~b2ChainShape(); - - /// Clear all data. - void Clear(); - - /// Create a loop. This automatically adjusts connectivity. - /// @param vertices an array of vertices, these are copied - /// @param count the vertex count - void CreateLoop(const b2Vec2* vertices, int32 count); - - /// Create a chain with isolated end vertices. - /// @param vertices an array of vertices, these are copied - /// @param count the vertex count - void CreateChain(const b2Vec2* vertices, int32 count); - - /// Establish connectivity to a vertex that precedes the first vertex. - /// Don't call this for loops. - void SetPrevVertex(const b2Vec2& prevVertex); - - /// Establish connectivity to a vertex that follows the last vertex. - /// Don't call this for loops. - void SetNextVertex(const b2Vec2& nextVertex); - - /// Implement b2Shape. Vertices are cloned using b2Alloc. - b2Shape* Clone(b2BlockAllocator* allocator) const override; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const override; - - /// Get a child edge. - void GetChildEdge(b2EdgeShape* edge, int32 index) const; - - /// This always return false. - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const override; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override; - - /// Chains have zero mass. - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const override; - - /// The vertices. Owned by this class. - b2Vec2* m_vertices; - - /// The vertex count. - int32 m_count; - - b2Vec2 m_prevVertex, m_nextVertex; - bool m_hasPrevVertex, m_hasNextVertex; -}; - -inline b2ChainShape::b2ChainShape() -{ - m_type = e_chain; - m_radius = b2_polygonRadius; - m_vertices = nullptr; - m_count = 0; - m_hasPrevVertex = false; - m_hasNextVertex = false; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2CircleShape.cpp b/libjin/3rdparty/Box2D/Collision/Shapes/b2CircleShape.cpp deleted file mode 100644 index fa24dc8..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2CircleShape.cpp +++ /dev/null @@ -1,99 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/Shapes/b2CircleShape.h" -#include <new> - -b2Shape* b2CircleShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2CircleShape)); - b2CircleShape* clone = new (mem) b2CircleShape; - *clone = *this; - return clone; -} - -int32 b2CircleShape::GetChildCount() const -{ - return 1; -} - -bool b2CircleShape::TestPoint(const b2Transform& transform, const b2Vec2& p) const -{ - b2Vec2 center = transform.p + b2Mul(transform.q, m_p); - b2Vec2 d = p - center; - return b2Dot(d, d) <= m_radius * m_radius; -} - -// Collision Detection in Interactive 3D Environments by Gino van den Bergen -// From Section 3.1.2 -// x = s + a * r -// norm(x) = radius -bool b2CircleShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 position = transform.p + b2Mul(transform.q, m_p); - b2Vec2 s = input.p1 - position; - float32 b = b2Dot(s, s) - m_radius * m_radius; - - // Solve quadratic equation. - b2Vec2 r = input.p2 - input.p1; - float32 c = b2Dot(s, r); - float32 rr = b2Dot(r, r); - float32 sigma = c * c - rr * b; - - // Check for negative discriminant and short segment. - if (sigma < 0.0f || rr < b2_epsilon) - { - return false; - } - - // Find the point of intersection of the line with the circle. - float32 a = -(c + b2Sqrt(sigma)); - - // Is the intersection point on the segment? - if (0.0f <= a && a <= input.maxFraction * rr) - { - a /= rr; - output->fraction = a; - output->normal = s + a * r; - output->normal.Normalize(); - return true; - } - - return false; -} - -void b2CircleShape::ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 p = transform.p + b2Mul(transform.q, m_p); - aabb->lowerBound.Set(p.x - m_radius, p.y - m_radius); - aabb->upperBound.Set(p.x + m_radius, p.y + m_radius); -} - -void b2CircleShape::ComputeMass(b2MassData* massData, float32 density) const -{ - massData->mass = density * b2_pi * m_radius * m_radius; - massData->center = m_p; - - // inertia about the local origin - massData->I = massData->mass * (0.5f * m_radius * m_radius + b2Dot(m_p, m_p)); -} diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2CircleShape.h b/libjin/3rdparty/Box2D/Collision/Shapes/b2CircleShape.h deleted file mode 100644 index d2c646e..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2CircleShape.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_CIRCLE_SHAPE_H -#define B2_CIRCLE_SHAPE_H - -#include "Box2D/Collision/Shapes/b2Shape.h" - -/// A circle shape. -class b2CircleShape : public b2Shape -{ -public: - b2CircleShape(); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const override; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const override; - - /// Implement b2Shape. - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const override; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const override; - - /// Position - b2Vec2 m_p; -}; - -inline b2CircleShape::b2CircleShape() -{ - m_type = e_circle; - m_radius = 0.0f; - m_p.SetZero(); -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2EdgeShape.cpp b/libjin/3rdparty/Box2D/Collision/Shapes/b2EdgeShape.cpp deleted file mode 100644 index 7b8dd57..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2EdgeShape.cpp +++ /dev/null @@ -1,138 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/Shapes/b2EdgeShape.h" -#include <new> - -void b2EdgeShape::Set(const b2Vec2& v1, const b2Vec2& v2) -{ - m_vertex1 = v1; - m_vertex2 = v2; - m_hasVertex0 = false; - m_hasVertex3 = false; -} - -b2Shape* b2EdgeShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2EdgeShape)); - b2EdgeShape* clone = new (mem) b2EdgeShape; - *clone = *this; - return clone; -} - -int32 b2EdgeShape::GetChildCount() const -{ - return 1; -} - -bool b2EdgeShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - B2_NOT_USED(xf); - B2_NOT_USED(p); - return false; -} - -// p = p1 + t * d -// v = v1 + s * e -// p1 + t * d = v1 + s * e -// s * e - t * d = p1 - v1 -bool b2EdgeShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - // Put the ray into the edge's frame of reference. - b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - b2Vec2 d = p2 - p1; - - b2Vec2 v1 = m_vertex1; - b2Vec2 v2 = m_vertex2; - b2Vec2 e = v2 - v1; - b2Vec2 normal(e.y, -e.x); - normal.Normalize(); - - // q = p1 + t * d - // dot(normal, q - v1) = 0 - // dot(normal, p1 - v1) + t * dot(normal, d) = 0 - float32 numerator = b2Dot(normal, v1 - p1); - float32 denominator = b2Dot(normal, d); - - if (denominator == 0.0f) - { - return false; - } - - float32 t = numerator / denominator; - if (t < 0.0f || input.maxFraction < t) - { - return false; - } - - b2Vec2 q = p1 + t * d; - - // q = v1 + s * r - // s = dot(q - v1, r) / dot(r, r) - b2Vec2 r = v2 - v1; - float32 rr = b2Dot(r, r); - if (rr == 0.0f) - { - return false; - } - - float32 s = b2Dot(q - v1, r) / rr; - if (s < 0.0f || 1.0f < s) - { - return false; - } - - output->fraction = t; - if (numerator > 0.0f) - { - output->normal = -b2Mul(xf.q, normal); - } - else - { - output->normal = b2Mul(xf.q, normal); - } - return true; -} - -void b2EdgeShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 v1 = b2Mul(xf, m_vertex1); - b2Vec2 v2 = b2Mul(xf, m_vertex2); - - b2Vec2 lower = b2Min(v1, v2); - b2Vec2 upper = b2Max(v1, v2); - - b2Vec2 r(m_radius, m_radius); - aabb->lowerBound = lower - r; - aabb->upperBound = upper + r; -} - -void b2EdgeShape::ComputeMass(b2MassData* massData, float32 density) const -{ - B2_NOT_USED(density); - - massData->mass = 0.0f; - massData->center = 0.5f * (m_vertex1 + m_vertex2); - massData->I = 0.0f; -} diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2EdgeShape.h b/libjin/3rdparty/Box2D/Collision/Shapes/b2EdgeShape.h deleted file mode 100644 index 63b1a56..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2EdgeShape.h +++ /dev/null @@ -1,74 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* 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 B2_EDGE_SHAPE_H -#define B2_EDGE_SHAPE_H - -#include "Box2D/Collision/Shapes/b2Shape.h" - -/// A line segment (edge) shape. These can be connected in chains or loops -/// to other edge shapes. The connectivity information is used to ensure -/// correct contact normals. -class b2EdgeShape : public b2Shape -{ -public: - b2EdgeShape(); - - /// Set this as an isolated edge. - void Set(const b2Vec2& v1, const b2Vec2& v2); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const override; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const override; - - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const override; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const override; - - /// These are the edge vertices - b2Vec2 m_vertex1, m_vertex2; - - /// Optional adjacent vertices. These are used for smooth collision. - b2Vec2 m_vertex0, m_vertex3; - bool m_hasVertex0, m_hasVertex3; -}; - -inline b2EdgeShape::b2EdgeShape() -{ - m_type = e_edge; - m_radius = b2_polygonRadius; - m_vertex0.x = 0.0f; - m_vertex0.y = 0.0f; - m_vertex3.x = 0.0f; - m_vertex3.y = 0.0f; - m_hasVertex0 = false; - m_hasVertex3 = false; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2PolygonShape.cpp b/libjin/3rdparty/Box2D/Collision/Shapes/b2PolygonShape.cpp deleted file mode 100644 index 3c8c47d..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2PolygonShape.cpp +++ /dev/null @@ -1,468 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/Shapes/b2PolygonShape.h" -#include <new> - -b2Shape* b2PolygonShape::Clone(b2BlockAllocator* allocator) const -{ - void* mem = allocator->Allocate(sizeof(b2PolygonShape)); - b2PolygonShape* clone = new (mem) b2PolygonShape; - *clone = *this; - return clone; -} - -void b2PolygonShape::SetAsBox(float32 hx, float32 hy) -{ - m_count = 4; - m_vertices[0].Set(-hx, -hy); - m_vertices[1].Set( hx, -hy); - m_vertices[2].Set( hx, hy); - m_vertices[3].Set(-hx, hy); - m_normals[0].Set(0.0f, -1.0f); - m_normals[1].Set(1.0f, 0.0f); - m_normals[2].Set(0.0f, 1.0f); - m_normals[3].Set(-1.0f, 0.0f); - m_centroid.SetZero(); -} - -void b2PolygonShape::SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle) -{ - m_count = 4; - m_vertices[0].Set(-hx, -hy); - m_vertices[1].Set( hx, -hy); - m_vertices[2].Set( hx, hy); - m_vertices[3].Set(-hx, hy); - m_normals[0].Set(0.0f, -1.0f); - m_normals[1].Set(1.0f, 0.0f); - m_normals[2].Set(0.0f, 1.0f); - m_normals[3].Set(-1.0f, 0.0f); - m_centroid = center; - - b2Transform xf; - xf.p = center; - xf.q.Set(angle); - - // Transform vertices and normals. - for (int32 i = 0; i < m_count; ++i) - { - m_vertices[i] = b2Mul(xf, m_vertices[i]); - m_normals[i] = b2Mul(xf.q, m_normals[i]); - } -} - -int32 b2PolygonShape::GetChildCount() const -{ - return 1; -} - -static b2Vec2 ComputeCentroid(const b2Vec2* vs, int32 count) -{ - b2Assert(count >= 3); - - b2Vec2 c; c.Set(0.0f, 0.0f); - float32 area = 0.0f; - - // pRef is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 pRef(0.0f, 0.0f); -#if 0 - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < count; ++i) - { - pRef += vs[i]; - } - pRef *= 1.0f / count; -#endif - - const float32 inv3 = 1.0f / 3.0f; - - for (int32 i = 0; i < count; ++i) - { - // Triangle vertices. - b2Vec2 p1 = pRef; - b2Vec2 p2 = vs[i]; - b2Vec2 p3 = i + 1 < count ? vs[i+1] : vs[0]; - - b2Vec2 e1 = p2 - p1; - b2Vec2 e2 = p3 - p1; - - float32 D = b2Cross(e1, e2); - - float32 triangleArea = 0.5f * D; - area += triangleArea; - - // Area weighted centroid - c += triangleArea * inv3 * (p1 + p2 + p3); - } - - // Centroid - b2Assert(area > b2_epsilon); - c *= 1.0f / area; - return c; -} - -void b2PolygonShape::Set(const b2Vec2* vertices, int32 count) -{ - b2Assert(3 <= count && count <= b2_maxPolygonVertices); - if (count < 3) - { - SetAsBox(1.0f, 1.0f); - return; - } - - int32 n = b2Min(count, b2_maxPolygonVertices); - - // Perform welding and copy vertices into local buffer. - b2Vec2 ps[b2_maxPolygonVertices]; - int32 tempCount = 0; - for (int32 i = 0; i < n; ++i) - { - b2Vec2 v = vertices[i]; - - bool unique = true; - for (int32 j = 0; j < tempCount; ++j) - { - if (b2DistanceSquared(v, ps[j]) < ((0.5f * b2_linearSlop) * (0.5f * b2_linearSlop))) - { - unique = false; - break; - } - } - - if (unique) - { - ps[tempCount++] = v; - } - } - - n = tempCount; - if (n < 3) - { - // Polygon is degenerate. - b2Assert(false); - SetAsBox(1.0f, 1.0f); - return; - } - - // Create the convex hull using the Gift wrapping algorithm - // http://en.wikipedia.org/wiki/Gift_wrapping_algorithm - - // Find the right most point on the hull - int32 i0 = 0; - float32 x0 = ps[0].x; - for (int32 i = 1; i < n; ++i) - { - float32 x = ps[i].x; - if (x > x0 || (x == x0 && ps[i].y < ps[i0].y)) - { - i0 = i; - x0 = x; - } - } - - int32 hull[b2_maxPolygonVertices]; - int32 m = 0; - int32 ih = i0; - - for (;;) - { - b2Assert(m < b2_maxPolygonVertices); - hull[m] = ih; - - int32 ie = 0; - for (int32 j = 1; j < n; ++j) - { - if (ie == ih) - { - ie = j; - continue; - } - - b2Vec2 r = ps[ie] - ps[hull[m]]; - b2Vec2 v = ps[j] - ps[hull[m]]; - float32 c = b2Cross(r, v); - if (c < 0.0f) - { - ie = j; - } - - // Collinearity check - if (c == 0.0f && v.LengthSquared() > r.LengthSquared()) - { - ie = j; - } - } - - ++m; - ih = ie; - - if (ie == i0) - { - break; - } - } - - if (m < 3) - { - // Polygon is degenerate. - b2Assert(false); - SetAsBox(1.0f, 1.0f); - return; - } - - m_count = m; - - // Copy vertices. - for (int32 i = 0; i < m; ++i) - { - m_vertices[i] = ps[hull[i]]; - } - - // Compute normals. Ensure the edges have non-zero length. - for (int32 i = 0; i < m; ++i) - { - int32 i1 = i; - int32 i2 = i + 1 < m ? i + 1 : 0; - b2Vec2 edge = m_vertices[i2] - m_vertices[i1]; - b2Assert(edge.LengthSquared() > b2_epsilon * b2_epsilon); - m_normals[i] = b2Cross(edge, 1.0f); - m_normals[i].Normalize(); - } - - // Compute the polygon centroid. - m_centroid = ComputeCentroid(m_vertices, m); -} - -bool b2PolygonShape::TestPoint(const b2Transform& xf, const b2Vec2& p) const -{ - b2Vec2 pLocal = b2MulT(xf.q, p - xf.p); - - for (int32 i = 0; i < m_count; ++i) - { - float32 dot = b2Dot(m_normals[i], pLocal - m_vertices[i]); - if (dot > 0.0f) - { - return false; - } - } - - return true; -} - -bool b2PolygonShape::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - // Put the ray into the polygon's frame of reference. - b2Vec2 p1 = b2MulT(xf.q, input.p1 - xf.p); - b2Vec2 p2 = b2MulT(xf.q, input.p2 - xf.p); - b2Vec2 d = p2 - p1; - - float32 lower = 0.0f, upper = input.maxFraction; - - int32 index = -1; - - for (int32 i = 0; i < m_count; ++i) - { - // p = p1 + a * d - // dot(normal, p - v) = 0 - // dot(normal, p1 - v) + a * dot(normal, d) = 0 - float32 numerator = b2Dot(m_normals[i], m_vertices[i] - p1); - float32 denominator = b2Dot(m_normals[i], d); - - if (denominator == 0.0f) - { - if (numerator < 0.0f) - { - return false; - } - } - else - { - // Note: we want this predicate without division: - // lower < numerator / denominator, where denominator < 0 - // Since denominator < 0, we have to flip the inequality: - // lower < numerator / denominator <==> denominator * lower > numerator. - if (denominator < 0.0f && numerator < lower * denominator) - { - // Increase lower. - // The segment enters this half-space. - lower = numerator / denominator; - index = i; - } - else if (denominator > 0.0f && numerator < upper * denominator) - { - // Decrease upper. - // The segment exits this half-space. - upper = numerator / denominator; - } - } - - // The use of epsilon here causes the assert on lower to trip - // in some cases. Apparently the use of epsilon was to make edge - // shapes work, but now those are handled separately. - //if (upper < lower - b2_epsilon) - if (upper < lower) - { - return false; - } - } - - b2Assert(0.0f <= lower && lower <= input.maxFraction); - - if (index >= 0) - { - output->fraction = lower; - output->normal = b2Mul(xf.q, m_normals[index]); - return true; - } - - return false; -} - -void b2PolygonShape::ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const -{ - B2_NOT_USED(childIndex); - - b2Vec2 lower = b2Mul(xf, m_vertices[0]); - b2Vec2 upper = lower; - - for (int32 i = 1; i < m_count; ++i) - { - b2Vec2 v = b2Mul(xf, m_vertices[i]); - lower = b2Min(lower, v); - upper = b2Max(upper, v); - } - - b2Vec2 r(m_radius, m_radius); - aabb->lowerBound = lower - r; - aabb->upperBound = upper + r; -} - -void b2PolygonShape::ComputeMass(b2MassData* massData, float32 density) const -{ - // Polygon mass, centroid, and inertia. - // Let rho be the polygon density in mass per unit area. - // Then: - // mass = rho * int(dA) - // centroid.x = (1/mass) * rho * int(x * dA) - // centroid.y = (1/mass) * rho * int(y * dA) - // I = rho * int((x*x + y*y) * dA) - // - // We can compute these integrals by summing all the integrals - // for each triangle of the polygon. To evaluate the integral - // for a single triangle, we make a change of variables to - // the (u,v) coordinates of the triangle: - // x = x0 + e1x * u + e2x * v - // y = y0 + e1y * u + e2y * v - // where 0 <= u && 0 <= v && u + v <= 1. - // - // We integrate u from [0,1-v] and then v from [0,1]. - // We also need to use the Jacobian of the transformation: - // D = cross(e1, e2) - // - // Simplification: triangle centroid = (1/3) * (p1 + p2 + p3) - // - // The rest of the derivation is handled by computer algebra. - - b2Assert(m_count >= 3); - - b2Vec2 center; center.Set(0.0f, 0.0f); - float32 area = 0.0f; - float32 I = 0.0f; - - // s is the reference point for forming triangles. - // It's location doesn't change the result (except for rounding error). - b2Vec2 s(0.0f, 0.0f); - - // This code would put the reference point inside the polygon. - for (int32 i = 0; i < m_count; ++i) - { - s += m_vertices[i]; - } - s *= 1.0f / m_count; - - const float32 k_inv3 = 1.0f / 3.0f; - - for (int32 i = 0; i < m_count; ++i) - { - // Triangle vertices. - b2Vec2 e1 = m_vertices[i] - s; - b2Vec2 e2 = i + 1 < m_count ? m_vertices[i+1] - s : m_vertices[0] - s; - - float32 D = b2Cross(e1, e2); - - float32 triangleArea = 0.5f * D; - area += triangleArea; - - // Area weighted centroid - center += triangleArea * k_inv3 * (e1 + e2); - - float32 ex1 = e1.x, ey1 = e1.y; - float32 ex2 = e2.x, ey2 = e2.y; - - float32 intx2 = ex1*ex1 + ex2*ex1 + ex2*ex2; - float32 inty2 = ey1*ey1 + ey2*ey1 + ey2*ey2; - - I += (0.25f * k_inv3 * D) * (intx2 + inty2); - } - - // Total mass - massData->mass = density * area; - - // Center of mass - b2Assert(area > b2_epsilon); - center *= 1.0f / area; - massData->center = center + s; - - // Inertia tensor relative to the local origin (point s). - massData->I = density * I; - - // Shift to center of mass then to original body origin. - massData->I += massData->mass * (b2Dot(massData->center, massData->center) - b2Dot(center, center)); -} - -bool b2PolygonShape::Validate() const -{ - for (int32 i = 0; i < m_count; ++i) - { - int32 i1 = i; - int32 i2 = i < m_count - 1 ? i1 + 1 : 0; - b2Vec2 p = m_vertices[i1]; - b2Vec2 e = m_vertices[i2] - p; - - for (int32 j = 0; j < m_count; ++j) - { - if (j == i1 || j == i2) - { - continue; - } - - b2Vec2 v = m_vertices[j] - p; - float32 c = b2Cross(e, v); - if (c < 0.0f) - { - return false; - } - } - } - - return true; -} diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2PolygonShape.h b/libjin/3rdparty/Box2D/Collision/Shapes/b2PolygonShape.h deleted file mode 100644 index 26c5e61..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2PolygonShape.h +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_POLYGON_SHAPE_H -#define B2_POLYGON_SHAPE_H - -#include "Box2D/Collision/Shapes/b2Shape.h" - -/// A convex polygon. It is assumed that the interior of the polygon is to -/// the left of each edge. -/// Polygons have a maximum number of vertices equal to b2_maxPolygonVertices. -/// In most cases you should not need many vertices for a convex polygon. -class b2PolygonShape : public b2Shape -{ -public: - b2PolygonShape(); - - /// Implement b2Shape. - b2Shape* Clone(b2BlockAllocator* allocator) const override; - - /// @see b2Shape::GetChildCount - int32 GetChildCount() const override; - - /// Create a convex hull from the given array of local points. - /// The count must be in the range [3, b2_maxPolygonVertices]. - /// @warning the points may be re-ordered, even if they form a convex polygon - /// @warning collinear points are handled but not removed. Collinear points - /// may lead to poor stacking behavior. - void Set(const b2Vec2* points, int32 count); - - /// Build vertices to represent an axis-aligned box centered on the local origin. - /// @param hx the half-width. - /// @param hy the half-height. - void SetAsBox(float32 hx, float32 hy); - - /// Build vertices to represent an oriented box. - /// @param hx the half-width. - /// @param hy the half-height. - /// @param center the center of the box in local coordinates. - /// @param angle the rotation of the box in local coordinates. - void SetAsBox(float32 hx, float32 hy, const b2Vec2& center, float32 angle); - - /// @see b2Shape::TestPoint - bool TestPoint(const b2Transform& transform, const b2Vec2& p) const override; - - /// Implement b2Shape. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const override; - - /// @see b2Shape::ComputeAABB - void ComputeAABB(b2AABB* aabb, const b2Transform& transform, int32 childIndex) const override; - - /// @see b2Shape::ComputeMass - void ComputeMass(b2MassData* massData, float32 density) const override; - - /// Validate convexity. This is a very time consuming operation. - /// @returns true if valid - bool Validate() const; - - b2Vec2 m_centroid; - b2Vec2 m_vertices[b2_maxPolygonVertices]; - b2Vec2 m_normals[b2_maxPolygonVertices]; - int32 m_count; -}; - -inline b2PolygonShape::b2PolygonShape() -{ - m_type = e_polygon; - m_radius = b2_polygonRadius; - m_count = 0; - m_centroid.SetZero(); -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/Shapes/b2Shape.h b/libjin/3rdparty/Box2D/Collision/Shapes/b2Shape.h deleted file mode 100644 index 653e362..0000000 --- a/libjin/3rdparty/Box2D/Collision/Shapes/b2Shape.h +++ /dev/null @@ -1,104 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_SHAPE_H -#define B2_SHAPE_H - -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Common/b2Math.h" -#include "Box2D/Collision/b2Collision.h" - -/// This holds the mass data computed for a shape. -struct b2MassData -{ - /// The mass of the shape, usually in kilograms. - float32 mass; - - /// The position of the shape's centroid relative to the shape's origin. - b2Vec2 center; - - /// The rotational inertia of the shape about the local origin. - float32 I; -}; - -/// A shape is used for collision detection. You can create a shape however you like. -/// Shapes used for simulation in b2World are created automatically when a b2Fixture -/// is created. Shapes may encapsulate a one or more child shapes. -class b2Shape -{ -public: - - enum Type - { - e_circle = 0, - e_edge = 1, - e_polygon = 2, - e_chain = 3, - e_typeCount = 4 - }; - - virtual ~b2Shape() {} - - /// Clone the concrete shape using the provided allocator. - virtual b2Shape* Clone(b2BlockAllocator* allocator) const = 0; - - /// Get the type of this shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - Type GetType() const; - - /// Get the number of child primitives. - virtual int32 GetChildCount() const = 0; - - /// Test a point for containment in this shape. This only works for convex shapes. - /// @param xf the shape world transform. - /// @param p a point in world coordinates. - virtual bool TestPoint(const b2Transform& xf, const b2Vec2& p) const = 0; - - /// Cast a ray against a child shape. - /// @param output the ray-cast results. - /// @param input the ray-cast input parameters. - /// @param transform the transform to be applied to the shape. - /// @param childIndex the child shape index - virtual bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, - const b2Transform& transform, int32 childIndex) const = 0; - - /// Given a transform, compute the associated axis aligned bounding box for a child shape. - /// @param aabb returns the axis aligned box. - /// @param xf the world transform of the shape. - /// @param childIndex the child shape - virtual void ComputeAABB(b2AABB* aabb, const b2Transform& xf, int32 childIndex) const = 0; - - /// Compute the mass properties of this shape using its dimensions and density. - /// The inertia tensor is computed about the local origin. - /// @param massData returns the mass data for this shape. - /// @param density the density in kilograms per meter squared. - virtual void ComputeMass(b2MassData* massData, float32 density) const = 0; - - Type m_type; - - /// Radius of a shape. For polygonal shapes this must be b2_polygonRadius. There is no support for - /// making rounded polygons. - float32 m_radius; -}; - -inline b2Shape::Type b2Shape::GetType() const -{ - return m_type; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/b2BroadPhase.cpp b/libjin/3rdparty/Box2D/Collision/b2BroadPhase.cpp deleted file mode 100644 index e96339d..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2BroadPhase.cpp +++ /dev/null @@ -1,119 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/b2BroadPhase.h" - -b2BroadPhase::b2BroadPhase() -{ - m_proxyCount = 0; - - m_pairCapacity = 16; - m_pairCount = 0; - m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); - - m_moveCapacity = 16; - m_moveCount = 0; - m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); -} - -b2BroadPhase::~b2BroadPhase() -{ - b2Free(m_moveBuffer); - b2Free(m_pairBuffer); -} - -int32 b2BroadPhase::CreateProxy(const b2AABB& aabb, void* userData) -{ - int32 proxyId = m_tree.CreateProxy(aabb, userData); - ++m_proxyCount; - BufferMove(proxyId); - return proxyId; -} - -void b2BroadPhase::DestroyProxy(int32 proxyId) -{ - UnBufferMove(proxyId); - --m_proxyCount; - m_tree.DestroyProxy(proxyId); -} - -void b2BroadPhase::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) -{ - bool buffer = m_tree.MoveProxy(proxyId, aabb, displacement); - if (buffer) - { - BufferMove(proxyId); - } -} - -void b2BroadPhase::TouchProxy(int32 proxyId) -{ - BufferMove(proxyId); -} - -void b2BroadPhase::BufferMove(int32 proxyId) -{ - if (m_moveCount == m_moveCapacity) - { - int32* oldBuffer = m_moveBuffer; - m_moveCapacity *= 2; - m_moveBuffer = (int32*)b2Alloc(m_moveCapacity * sizeof(int32)); - memcpy(m_moveBuffer, oldBuffer, m_moveCount * sizeof(int32)); - b2Free(oldBuffer); - } - - m_moveBuffer[m_moveCount] = proxyId; - ++m_moveCount; -} - -void b2BroadPhase::UnBufferMove(int32 proxyId) -{ - for (int32 i = 0; i < m_moveCount; ++i) - { - if (m_moveBuffer[i] == proxyId) - { - m_moveBuffer[i] = e_nullProxy; - } - } -} - -// This is called from b2DynamicTree::Query when we are gathering pairs. -bool b2BroadPhase::QueryCallback(int32 proxyId) -{ - // A proxy cannot form a pair with itself. - if (proxyId == m_queryProxyId) - { - return true; - } - - // Grow the pair buffer as needed. - if (m_pairCount == m_pairCapacity) - { - b2Pair* oldBuffer = m_pairBuffer; - m_pairCapacity *= 2; - m_pairBuffer = (b2Pair*)b2Alloc(m_pairCapacity * sizeof(b2Pair)); - memcpy(m_pairBuffer, oldBuffer, m_pairCount * sizeof(b2Pair)); - b2Free(oldBuffer); - } - - m_pairBuffer[m_pairCount].proxyIdA = b2Min(proxyId, m_queryProxyId); - m_pairBuffer[m_pairCount].proxyIdB = b2Max(proxyId, m_queryProxyId); - ++m_pairCount; - - return true; -} diff --git a/libjin/3rdparty/Box2D/Collision/b2BroadPhase.h b/libjin/3rdparty/Box2D/Collision/b2BroadPhase.h deleted file mode 100644 index d2965ed..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2BroadPhase.h +++ /dev/null @@ -1,257 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_BROAD_PHASE_H -#define B2_BROAD_PHASE_H - -#include "Box2D/Common/b2Settings.h" -#include "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/b2DynamicTree.h" -#include <algorithm> - -struct b2Pair -{ - int32 proxyIdA; - int32 proxyIdB; -}; - -/// The broad-phase is used for computing pairs and performing volume queries and ray casts. -/// This broad-phase does not persist pairs. Instead, this reports potentially new pairs. -/// It is up to the client to consume the new pairs and to track subsequent overlap. -class b2BroadPhase -{ -public: - - enum - { - e_nullProxy = -1 - }; - - b2BroadPhase(); - ~b2BroadPhase(); - - /// Create a proxy with an initial AABB. Pairs are not reported until - /// UpdatePairs is called. - int32 CreateProxy(const b2AABB& aabb, void* userData); - - /// Destroy a proxy. It is up to the client to remove any pairs. - void DestroyProxy(int32 proxyId); - - /// Call MoveProxy as many times as you like, then when you are done - /// call UpdatePairs to finalized the proxy pairs (for your time step). - void MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement); - - /// Call to trigger a re-processing of it's pairs on the next call to UpdatePairs. - void TouchProxy(int32 proxyId); - - /// Get the fat AABB for a proxy. - const b2AABB& GetFatAABB(int32 proxyId) const; - - /// Get user data from a proxy. Returns nullptr if the id is invalid. - void* GetUserData(int32 proxyId) const; - - /// Test overlap of fat AABBs. - bool TestOverlap(int32 proxyIdA, int32 proxyIdB) const; - - /// Get the number of proxies. - int32 GetProxyCount() const; - - /// Update the pairs. This results in pair callbacks. This can only add pairs. - template <typename T> - void UpdatePairs(T* callback); - - /// Query an AABB for overlapping proxies. The callback class - /// is called for each proxy that overlaps the supplied AABB. - template <typename T> - void Query(T* callback, const b2AABB& aabb) const; - - /// Ray-cast against the proxies in the tree. This relies on the callback - /// to perform a exact ray-cast in the case were the proxy contains a shape. - /// The callback also performs the any collision filtering. This has performance - /// roughly equal to k * log(n), where k is the number of collisions and n is the - /// number of proxies in the tree. - /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - /// @param callback a callback class that is called for each proxy that is hit by the ray. - template <typename T> - void RayCast(T* callback, const b2RayCastInput& input) const; - - /// Get the height of the embedded tree. - int32 GetTreeHeight() const; - - /// Get the balance of the embedded tree. - int32 GetTreeBalance() const; - - /// Get the quality metric of the embedded tree. - float32 GetTreeQuality() const; - - /// Shift the world origin. Useful for large worlds. - /// The shift formula is: position -= newOrigin - /// @param newOrigin the new origin with respect to the old origin - void ShiftOrigin(const b2Vec2& newOrigin); - -private: - - friend class b2DynamicTree; - - void BufferMove(int32 proxyId); - void UnBufferMove(int32 proxyId); - - bool QueryCallback(int32 proxyId); - - b2DynamicTree m_tree; - - int32 m_proxyCount; - - int32* m_moveBuffer; - int32 m_moveCapacity; - int32 m_moveCount; - - b2Pair* m_pairBuffer; - int32 m_pairCapacity; - int32 m_pairCount; - - int32 m_queryProxyId; -}; - -/// This is used to sort pairs. -inline bool b2PairLessThan(const b2Pair& pair1, const b2Pair& pair2) -{ - if (pair1.proxyIdA < pair2.proxyIdA) - { - return true; - } - - if (pair1.proxyIdA == pair2.proxyIdA) - { - return pair1.proxyIdB < pair2.proxyIdB; - } - - return false; -} - -inline void* b2BroadPhase::GetUserData(int32 proxyId) const -{ - return m_tree.GetUserData(proxyId); -} - -inline bool b2BroadPhase::TestOverlap(int32 proxyIdA, int32 proxyIdB) const -{ - const b2AABB& aabbA = m_tree.GetFatAABB(proxyIdA); - const b2AABB& aabbB = m_tree.GetFatAABB(proxyIdB); - return b2TestOverlap(aabbA, aabbB); -} - -inline const b2AABB& b2BroadPhase::GetFatAABB(int32 proxyId) const -{ - return m_tree.GetFatAABB(proxyId); -} - -inline int32 b2BroadPhase::GetProxyCount() const -{ - return m_proxyCount; -} - -inline int32 b2BroadPhase::GetTreeHeight() const -{ - return m_tree.GetHeight(); -} - -inline int32 b2BroadPhase::GetTreeBalance() const -{ - return m_tree.GetMaxBalance(); -} - -inline float32 b2BroadPhase::GetTreeQuality() const -{ - return m_tree.GetAreaRatio(); -} - -template <typename T> -void b2BroadPhase::UpdatePairs(T* callback) -{ - // Reset pair buffer - m_pairCount = 0; - - // Perform tree queries for all moving proxies. - for (int32 i = 0; i < m_moveCount; ++i) - { - m_queryProxyId = m_moveBuffer[i]; - if (m_queryProxyId == e_nullProxy) - { - continue; - } - - // We have to query the tree with the fat AABB so that - // we don't fail to create a pair that may touch later. - const b2AABB& fatAABB = m_tree.GetFatAABB(m_queryProxyId); - - // Query tree, create pairs and add them pair buffer. - m_tree.Query(this, fatAABB); - } - - // Reset move buffer - m_moveCount = 0; - - // Sort the pair buffer to expose duplicates. - std::sort(m_pairBuffer, m_pairBuffer + m_pairCount, b2PairLessThan); - - // Send the pairs back to the client. - int32 i = 0; - while (i < m_pairCount) - { - b2Pair* primaryPair = m_pairBuffer + i; - void* userDataA = m_tree.GetUserData(primaryPair->proxyIdA); - void* userDataB = m_tree.GetUserData(primaryPair->proxyIdB); - - callback->AddPair(userDataA, userDataB); - ++i; - - // Skip any duplicate pairs. - while (i < m_pairCount) - { - b2Pair* pair = m_pairBuffer + i; - if (pair->proxyIdA != primaryPair->proxyIdA || pair->proxyIdB != primaryPair->proxyIdB) - { - break; - } - ++i; - } - } - - // Try to keep the tree balanced. - //m_tree.Rebalance(4); -} - -template <typename T> -inline void b2BroadPhase::Query(T* callback, const b2AABB& aabb) const -{ - m_tree.Query(callback, aabb); -} - -template <typename T> -inline void b2BroadPhase::RayCast(T* callback, const b2RayCastInput& input) const -{ - m_tree.RayCast(callback, input); -} - -inline void b2BroadPhase::ShiftOrigin(const b2Vec2& newOrigin) -{ - m_tree.ShiftOrigin(newOrigin); -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/b2CollideCircle.cpp b/libjin/3rdparty/Box2D/Collision/b2CollideCircle.cpp deleted file mode 100644 index f39f057..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2CollideCircle.cpp +++ /dev/null @@ -1,154 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/Shapes/b2CircleShape.h" -#include "Box2D/Collision/Shapes/b2PolygonShape.h" - -void b2CollideCircles( - b2Manifold* manifold, - const b2CircleShape* circleA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - b2Vec2 pA = b2Mul(xfA, circleA->m_p); - b2Vec2 pB = b2Mul(xfB, circleB->m_p); - - b2Vec2 d = pB - pA; - float32 distSqr = b2Dot(d, d); - float32 rA = circleA->m_radius, rB = circleB->m_radius; - float32 radius = rA + rB; - if (distSqr > radius * radius) - { - return; - } - - manifold->type = b2Manifold::e_circles; - manifold->localPoint = circleA->m_p; - manifold->localNormal.SetZero(); - manifold->pointCount = 1; - - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; -} - -void b2CollidePolygonAndCircle( - b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - // Compute circle position in the frame of the polygon. - b2Vec2 c = b2Mul(xfB, circleB->m_p); - b2Vec2 cLocal = b2MulT(xfA, c); - - // Find the min separating edge. - int32 normalIndex = 0; - float32 separation = -b2_maxFloat; - float32 radius = polygonA->m_radius + circleB->m_radius; - int32 vertexCount = polygonA->m_count; - const b2Vec2* vertices = polygonA->m_vertices; - const b2Vec2* normals = polygonA->m_normals; - - for (int32 i = 0; i < vertexCount; ++i) - { - float32 s = b2Dot(normals[i], cLocal - vertices[i]); - - if (s > radius) - { - // Early out. - return; - } - - if (s > separation) - { - separation = s; - normalIndex = i; - } - } - - // Vertices that subtend the incident face. - int32 vertIndex1 = normalIndex; - int32 vertIndex2 = vertIndex1 + 1 < vertexCount ? vertIndex1 + 1 : 0; - b2Vec2 v1 = vertices[vertIndex1]; - b2Vec2 v2 = vertices[vertIndex2]; - - // If the center is inside the polygon ... - if (separation < b2_epsilon) - { - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = normals[normalIndex]; - manifold->localPoint = 0.5f * (v1 + v2); - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - return; - } - - // Compute barycentric coordinates - float32 u1 = b2Dot(cLocal - v1, v2 - v1); - float32 u2 = b2Dot(cLocal - v2, v1 - v2); - if (u1 <= 0.0f) - { - if (b2DistanceSquared(cLocal, v1) > radius * radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = cLocal - v1; - manifold->localNormal.Normalize(); - manifold->localPoint = v1; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } - else if (u2 <= 0.0f) - { - if (b2DistanceSquared(cLocal, v2) > radius * radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = cLocal - v2; - manifold->localNormal.Normalize(); - manifold->localPoint = v2; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } - else - { - b2Vec2 faceCenter = 0.5f * (v1 + v2); - float32 s = b2Dot(cLocal - faceCenter, normals[vertIndex1]); - if (s > radius) - { - return; - } - - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = normals[vertIndex1]; - manifold->localPoint = faceCenter; - manifold->points[0].localPoint = circleB->m_p; - manifold->points[0].id.key = 0; - } -} diff --git a/libjin/3rdparty/Box2D/Collision/b2CollideEdge.cpp b/libjin/3rdparty/Box2D/Collision/b2CollideEdge.cpp deleted file mode 100644 index 793d714..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2CollideEdge.cpp +++ /dev/null @@ -1,698 +0,0 @@ -/* - * Copyright (c) 2007-2009 Erin Catto http://www.box2d.org - * - * 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 "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/Shapes/b2CircleShape.h" -#include "Box2D/Collision/Shapes/b2EdgeShape.h" -#include "Box2D/Collision/Shapes/b2PolygonShape.h" - - -// Compute contact points for edge versus circle. -// This accounts for edge connectivity. -void b2CollideEdgeAndCircle(b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - - // Compute circle in frame of edge - b2Vec2 Q = b2MulT(xfA, b2Mul(xfB, circleB->m_p)); - - b2Vec2 A = edgeA->m_vertex1, B = edgeA->m_vertex2; - b2Vec2 e = B - A; - - // Barycentric coordinates - float32 u = b2Dot(e, B - Q); - float32 v = b2Dot(e, Q - A); - - float32 radius = edgeA->m_radius + circleB->m_radius; - - b2ContactFeature cf; - cf.indexB = 0; - cf.typeB = b2ContactFeature::e_vertex; - - // Region A - if (v <= 0.0f) - { - b2Vec2 P = A; - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - // Is there an edge connected to A? - if (edgeA->m_hasVertex0) - { - b2Vec2 A1 = edgeA->m_vertex0; - b2Vec2 B1 = A; - b2Vec2 e1 = B1 - A1; - float32 u1 = b2Dot(e1, B1 - Q); - - // Is the circle in Region AB of the previous edge? - if (u1 > 0.0f) - { - return; - } - } - - cf.indexA = 0; - cf.typeA = b2ContactFeature::e_vertex; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_circles; - manifold->localNormal.SetZero(); - manifold->localPoint = P; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; - return; - } - - // Region B - if (u <= 0.0f) - { - b2Vec2 P = B; - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - // Is there an edge connected to B? - if (edgeA->m_hasVertex3) - { - b2Vec2 B2 = edgeA->m_vertex3; - b2Vec2 A2 = B; - b2Vec2 e2 = B2 - A2; - float32 v2 = b2Dot(e2, Q - A2); - - // Is the circle in Region AB of the next edge? - if (v2 > 0.0f) - { - return; - } - } - - cf.indexA = 1; - cf.typeA = b2ContactFeature::e_vertex; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_circles; - manifold->localNormal.SetZero(); - manifold->localPoint = P; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; - return; - } - - // Region AB - float32 den = b2Dot(e, e); - b2Assert(den > 0.0f); - b2Vec2 P = (1.0f / den) * (u * A + v * B); - b2Vec2 d = Q - P; - float32 dd = b2Dot(d, d); - if (dd > radius * radius) - { - return; - } - - b2Vec2 n(-e.y, e.x); - if (b2Dot(n, Q - A) < 0.0f) - { - n.Set(-n.x, -n.y); - } - n.Normalize(); - - cf.indexA = 0; - cf.typeA = b2ContactFeature::e_face; - manifold->pointCount = 1; - manifold->type = b2Manifold::e_faceA; - manifold->localNormal = n; - manifold->localPoint = A; - manifold->points[0].id.key = 0; - manifold->points[0].id.cf = cf; - manifold->points[0].localPoint = circleB->m_p; -} - -// This structure is used to keep track of the best separating axis. -struct b2EPAxis -{ - enum Type - { - e_unknown, - e_edgeA, - e_edgeB - }; - - Type type; - int32 index; - float32 separation; -}; - -// This holds polygon B expressed in frame A. -struct b2TempPolygon -{ - b2Vec2 vertices[b2_maxPolygonVertices]; - b2Vec2 normals[b2_maxPolygonVertices]; - int32 count; -}; - -// Reference face used for clipping -struct b2ReferenceFace -{ - int32 i1, i2; - - b2Vec2 v1, v2; - - b2Vec2 normal; - - b2Vec2 sideNormal1; - float32 sideOffset1; - - b2Vec2 sideNormal2; - float32 sideOffset2; -}; - -// This class collides and edge and a polygon, taking into account edge adjacency. -struct b2EPCollider -{ - void Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB); - b2EPAxis ComputeEdgeSeparation(); - b2EPAxis ComputePolygonSeparation(); - - enum VertexType - { - e_isolated, - e_concave, - e_convex - }; - - b2TempPolygon m_polygonB; - - b2Transform m_xf; - b2Vec2 m_centroidB; - b2Vec2 m_v0, m_v1, m_v2, m_v3; - b2Vec2 m_normal0, m_normal1, m_normal2; - b2Vec2 m_normal; - VertexType m_type1, m_type2; - b2Vec2 m_lowerLimit, m_upperLimit; - float32 m_radius; - bool m_front; -}; - -// Algorithm: -// 1. Classify v1 and v2 -// 2. Classify polygon centroid as front or back -// 3. Flip normal if necessary -// 4. Initialize normal range to [-pi, pi] about face normal -// 5. Adjust normal range according to adjacent edges -// 6. Visit each separating axes, only accept axes within the range -// 7. Return if _any_ axis indicates separation -// 8. Clip -void b2EPCollider::Collide(b2Manifold* manifold, const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB) -{ - m_xf = b2MulT(xfA, xfB); - - m_centroidB = b2Mul(m_xf, polygonB->m_centroid); - - m_v0 = edgeA->m_vertex0; - m_v1 = edgeA->m_vertex1; - m_v2 = edgeA->m_vertex2; - m_v3 = edgeA->m_vertex3; - - bool hasVertex0 = edgeA->m_hasVertex0; - bool hasVertex3 = edgeA->m_hasVertex3; - - b2Vec2 edge1 = m_v2 - m_v1; - edge1.Normalize(); - m_normal1.Set(edge1.y, -edge1.x); - float32 offset1 = b2Dot(m_normal1, m_centroidB - m_v1); - float32 offset0 = 0.0f, offset2 = 0.0f; - bool convex1 = false, convex2 = false; - - // Is there a preceding edge? - if (hasVertex0) - { - b2Vec2 edge0 = m_v1 - m_v0; - edge0.Normalize(); - m_normal0.Set(edge0.y, -edge0.x); - convex1 = b2Cross(edge0, edge1) >= 0.0f; - offset0 = b2Dot(m_normal0, m_centroidB - m_v0); - } - - // Is there a following edge? - if (hasVertex3) - { - b2Vec2 edge2 = m_v3 - m_v2; - edge2.Normalize(); - m_normal2.Set(edge2.y, -edge2.x); - convex2 = b2Cross(edge1, edge2) > 0.0f; - offset2 = b2Dot(m_normal2, m_centroidB - m_v2); - } - - // Determine front or back collision. Determine collision normal limits. - if (hasVertex0 && hasVertex3) - { - if (convex1 && convex2) - { - m_front = offset0 >= 0.0f || offset1 >= 0.0f || offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal1; - } - } - else if (convex1) - { - m_front = offset0 >= 0.0f || (offset1 >= 0.0f && offset2 >= 0.0f); - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = -m_normal1; - } - } - else if (convex2) - { - m_front = offset2 >= 0.0f || (offset0 >= 0.0f && offset1 >= 0.0f); - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal0; - } - } - else - { - m_front = offset0 >= 0.0f && offset1 >= 0.0f && offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = -m_normal0; - } - } - } - else if (hasVertex0) - { - if (convex1) - { - m_front = offset0 >= 0.0f || offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal0; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal1; - } - } - else - { - m_front = offset0 >= 0.0f && offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = -m_normal0; - } - } - } - else if (hasVertex3) - { - if (convex2) - { - m_front = offset1 >= 0.0f || offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal2; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal1; - } - } - else - { - m_front = offset1 >= 0.0f && offset2 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = -m_normal2; - m_upperLimit = m_normal1; - } - } - } - else - { - m_front = offset1 >= 0.0f; - if (m_front) - { - m_normal = m_normal1; - m_lowerLimit = -m_normal1; - m_upperLimit = -m_normal1; - } - else - { - m_normal = -m_normal1; - m_lowerLimit = m_normal1; - m_upperLimit = m_normal1; - } - } - - // Get polygonB in frameA - m_polygonB.count = polygonB->m_count; - for (int32 i = 0; i < polygonB->m_count; ++i) - { - m_polygonB.vertices[i] = b2Mul(m_xf, polygonB->m_vertices[i]); - m_polygonB.normals[i] = b2Mul(m_xf.q, polygonB->m_normals[i]); - } - - m_radius = polygonB->m_radius + edgeA->m_radius; - - manifold->pointCount = 0; - - b2EPAxis edgeAxis = ComputeEdgeSeparation(); - - // If no valid normal can be found than this edge should not collide. - if (edgeAxis.type == b2EPAxis::e_unknown) - { - return; - } - - if (edgeAxis.separation > m_radius) - { - return; - } - - b2EPAxis polygonAxis = ComputePolygonSeparation(); - if (polygonAxis.type != b2EPAxis::e_unknown && polygonAxis.separation > m_radius) - { - return; - } - - // Use hysteresis for jitter reduction. - const float32 k_relativeTol = 0.98f; - const float32 k_absoluteTol = 0.001f; - - b2EPAxis primaryAxis; - if (polygonAxis.type == b2EPAxis::e_unknown) - { - primaryAxis = edgeAxis; - } - else if (polygonAxis.separation > k_relativeTol * edgeAxis.separation + k_absoluteTol) - { - primaryAxis = polygonAxis; - } - else - { - primaryAxis = edgeAxis; - } - - b2ClipVertex ie[2]; - b2ReferenceFace rf; - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - manifold->type = b2Manifold::e_faceA; - - // Search for the polygon normal that is most anti-parallel to the edge normal. - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_normal, m_polygonB.normals[0]); - for (int32 i = 1; i < m_polygonB.count; ++i) - { - float32 value = b2Dot(m_normal, m_polygonB.normals[i]); - if (value < bestValue) - { - bestValue = value; - bestIndex = i; - } - } - - int32 i1 = bestIndex; - int32 i2 = i1 + 1 < m_polygonB.count ? i1 + 1 : 0; - - ie[0].v = m_polygonB.vertices[i1]; - ie[0].id.cf.indexA = 0; - ie[0].id.cf.indexB = static_cast<uint8>(i1); - ie[0].id.cf.typeA = b2ContactFeature::e_face; - ie[0].id.cf.typeB = b2ContactFeature::e_vertex; - - ie[1].v = m_polygonB.vertices[i2]; - ie[1].id.cf.indexA = 0; - ie[1].id.cf.indexB = static_cast<uint8>(i2); - ie[1].id.cf.typeA = b2ContactFeature::e_face; - ie[1].id.cf.typeB = b2ContactFeature::e_vertex; - - if (m_front) - { - rf.i1 = 0; - rf.i2 = 1; - rf.v1 = m_v1; - rf.v2 = m_v2; - rf.normal = m_normal1; - } - else - { - rf.i1 = 1; - rf.i2 = 0; - rf.v1 = m_v2; - rf.v2 = m_v1; - rf.normal = -m_normal1; - } - } - else - { - manifold->type = b2Manifold::e_faceB; - - ie[0].v = m_v1; - ie[0].id.cf.indexA = 0; - ie[0].id.cf.indexB = static_cast<uint8>(primaryAxis.index); - ie[0].id.cf.typeA = b2ContactFeature::e_vertex; - ie[0].id.cf.typeB = b2ContactFeature::e_face; - - ie[1].v = m_v2; - ie[1].id.cf.indexA = 0; - ie[1].id.cf.indexB = static_cast<uint8>(primaryAxis.index); - ie[1].id.cf.typeA = b2ContactFeature::e_vertex; - ie[1].id.cf.typeB = b2ContactFeature::e_face; - - rf.i1 = primaryAxis.index; - rf.i2 = rf.i1 + 1 < m_polygonB.count ? rf.i1 + 1 : 0; - rf.v1 = m_polygonB.vertices[rf.i1]; - rf.v2 = m_polygonB.vertices[rf.i2]; - rf.normal = m_polygonB.normals[rf.i1]; - } - - rf.sideNormal1.Set(rf.normal.y, -rf.normal.x); - rf.sideNormal2 = -rf.sideNormal1; - rf.sideOffset1 = b2Dot(rf.sideNormal1, rf.v1); - rf.sideOffset2 = b2Dot(rf.sideNormal2, rf.v2); - - // Clip incident edge against extruded edge1 side edges. - b2ClipVertex clipPoints1[2]; - b2ClipVertex clipPoints2[2]; - int32 np; - - // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, ie, rf.sideNormal1, rf.sideOffset1, rf.i1); - - if (np < b2_maxManifoldPoints) - { - return; - } - - // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, rf.sideNormal2, rf.sideOffset2, rf.i2); - - if (np < b2_maxManifoldPoints) - { - return; - } - - // Now clipPoints2 contains the clipped points. - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - manifold->localNormal = rf.normal; - manifold->localPoint = rf.v1; - } - else - { - manifold->localNormal = polygonB->m_normals[rf.i1]; - manifold->localPoint = polygonB->m_vertices[rf.i1]; - } - - int32 pointCount = 0; - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - float32 separation; - - separation = b2Dot(rf.normal, clipPoints2[i].v - rf.v1); - - if (separation <= m_radius) - { - b2ManifoldPoint* cp = manifold->points + pointCount; - - if (primaryAxis.type == b2EPAxis::e_edgeA) - { - cp->localPoint = b2MulT(m_xf, clipPoints2[i].v); - cp->id = clipPoints2[i].id; - } - else - { - cp->localPoint = clipPoints2[i].v; - cp->id.cf.typeA = clipPoints2[i].id.cf.typeB; - cp->id.cf.typeB = clipPoints2[i].id.cf.typeA; - cp->id.cf.indexA = clipPoints2[i].id.cf.indexB; - cp->id.cf.indexB = clipPoints2[i].id.cf.indexA; - } - - ++pointCount; - } - } - - manifold->pointCount = pointCount; -} - -b2EPAxis b2EPCollider::ComputeEdgeSeparation() -{ - b2EPAxis axis; - axis.type = b2EPAxis::e_edgeA; - axis.index = m_front ? 0 : 1; - axis.separation = FLT_MAX; - - for (int32 i = 0; i < m_polygonB.count; ++i) - { - float32 s = b2Dot(m_normal, m_polygonB.vertices[i] - m_v1); - if (s < axis.separation) - { - axis.separation = s; - } - } - - return axis; -} - -b2EPAxis b2EPCollider::ComputePolygonSeparation() -{ - b2EPAxis axis; - axis.type = b2EPAxis::e_unknown; - axis.index = -1; - axis.separation = -FLT_MAX; - - b2Vec2 perp(-m_normal.y, m_normal.x); - - for (int32 i = 0; i < m_polygonB.count; ++i) - { - b2Vec2 n = -m_polygonB.normals[i]; - - float32 s1 = b2Dot(n, m_polygonB.vertices[i] - m_v1); - float32 s2 = b2Dot(n, m_polygonB.vertices[i] - m_v2); - float32 s = b2Min(s1, s2); - - if (s > m_radius) - { - // No collision - axis.type = b2EPAxis::e_edgeB; - axis.index = i; - axis.separation = s; - return axis; - } - - // Adjacency - if (b2Dot(n, perp) >= 0.0f) - { - if (b2Dot(n - m_upperLimit, m_normal) < -b2_angularSlop) - { - continue; - } - } - else - { - if (b2Dot(n - m_lowerLimit, m_normal) < -b2_angularSlop) - { - continue; - } - } - - if (s > axis.separation) - { - axis.type = b2EPAxis::e_edgeB; - axis.index = i; - axis.separation = s; - } - } - - return axis; -} - -void b2CollideEdgeAndPolygon( b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB) -{ - b2EPCollider collider; - collider.Collide(manifold, edgeA, xfA, polygonB, xfB); -} diff --git a/libjin/3rdparty/Box2D/Collision/b2CollidePolygon.cpp b/libjin/3rdparty/Box2D/Collision/b2CollidePolygon.cpp deleted file mode 100644 index 10211e7..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2CollidePolygon.cpp +++ /dev/null @@ -1,239 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/Shapes/b2PolygonShape.h" - -// Find the max separation between poly1 and poly2 using edge normals from poly1. -static float32 b2FindMaxSeparation(int32* edgeIndex, - const b2PolygonShape* poly1, const b2Transform& xf1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - int32 count1 = poly1->m_count; - int32 count2 = poly2->m_count; - const b2Vec2* n1s = poly1->m_normals; - const b2Vec2* v1s = poly1->m_vertices; - const b2Vec2* v2s = poly2->m_vertices; - b2Transform xf = b2MulT(xf2, xf1); - - int32 bestIndex = 0; - float32 maxSeparation = -b2_maxFloat; - for (int32 i = 0; i < count1; ++i) - { - // Get poly1 normal in frame2. - b2Vec2 n = b2Mul(xf.q, n1s[i]); - b2Vec2 v1 = b2Mul(xf, v1s[i]); - - // Find deepest point for normal i. - float32 si = b2_maxFloat; - for (int32 j = 0; j < count2; ++j) - { - float32 sij = b2Dot(n, v2s[j] - v1); - if (sij < si) - { - si = sij; - } - } - - if (si > maxSeparation) - { - maxSeparation = si; - bestIndex = i; - } - } - - *edgeIndex = bestIndex; - return maxSeparation; -} - -static void b2FindIncidentEdge(b2ClipVertex c[2], - const b2PolygonShape* poly1, const b2Transform& xf1, int32 edge1, - const b2PolygonShape* poly2, const b2Transform& xf2) -{ - const b2Vec2* normals1 = poly1->m_normals; - - int32 count2 = poly2->m_count; - const b2Vec2* vertices2 = poly2->m_vertices; - const b2Vec2* normals2 = poly2->m_normals; - - b2Assert(0 <= edge1 && edge1 < poly1->m_count); - - // Get the normal of the reference edge in poly2's frame. - b2Vec2 normal1 = b2MulT(xf2.q, b2Mul(xf1.q, normals1[edge1])); - - // Find the incident edge on poly2. - int32 index = 0; - float32 minDot = b2_maxFloat; - for (int32 i = 0; i < count2; ++i) - { - float32 dot = b2Dot(normal1, normals2[i]); - if (dot < minDot) - { - minDot = dot; - index = i; - } - } - - // Build the clip vertices for the incident edge. - int32 i1 = index; - int32 i2 = i1 + 1 < count2 ? i1 + 1 : 0; - - c[0].v = b2Mul(xf2, vertices2[i1]); - c[0].id.cf.indexA = (uint8)edge1; - c[0].id.cf.indexB = (uint8)i1; - c[0].id.cf.typeA = b2ContactFeature::e_face; - c[0].id.cf.typeB = b2ContactFeature::e_vertex; - - c[1].v = b2Mul(xf2, vertices2[i2]); - c[1].id.cf.indexA = (uint8)edge1; - c[1].id.cf.indexB = (uint8)i2; - c[1].id.cf.typeA = b2ContactFeature::e_face; - c[1].id.cf.typeB = b2ContactFeature::e_vertex; -} - -// Find edge normal of max separation on A - return if separating axis is found -// Find edge normal of max separation on B - return if separation axis is found -// Choose reference edge as min(minA, minB) -// Find incident edge -// Clip - -// The normal points from 1 to 2 -void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polyA, const b2Transform& xfA, - const b2PolygonShape* polyB, const b2Transform& xfB) -{ - manifold->pointCount = 0; - float32 totalRadius = polyA->m_radius + polyB->m_radius; - - int32 edgeA = 0; - float32 separationA = b2FindMaxSeparation(&edgeA, polyA, xfA, polyB, xfB); - if (separationA > totalRadius) - return; - - int32 edgeB = 0; - float32 separationB = b2FindMaxSeparation(&edgeB, polyB, xfB, polyA, xfA); - if (separationB > totalRadius) - return; - - const b2PolygonShape* poly1; // reference polygon - const b2PolygonShape* poly2; // incident polygon - b2Transform xf1, xf2; - int32 edge1; // reference edge - uint8 flip; - const float32 k_tol = 0.1f * b2_linearSlop; - - if (separationB > separationA + k_tol) - { - poly1 = polyB; - poly2 = polyA; - xf1 = xfB; - xf2 = xfA; - edge1 = edgeB; - manifold->type = b2Manifold::e_faceB; - flip = 1; - } - else - { - poly1 = polyA; - poly2 = polyB; - xf1 = xfA; - xf2 = xfB; - edge1 = edgeA; - manifold->type = b2Manifold::e_faceA; - flip = 0; - } - - b2ClipVertex incidentEdge[2]; - b2FindIncidentEdge(incidentEdge, poly1, xf1, edge1, poly2, xf2); - - int32 count1 = poly1->m_count; - const b2Vec2* vertices1 = poly1->m_vertices; - - int32 iv1 = edge1; - int32 iv2 = edge1 + 1 < count1 ? edge1 + 1 : 0; - - b2Vec2 v11 = vertices1[iv1]; - b2Vec2 v12 = vertices1[iv2]; - - b2Vec2 localTangent = v12 - v11; - localTangent.Normalize(); - - b2Vec2 localNormal = b2Cross(localTangent, 1.0f); - b2Vec2 planePoint = 0.5f * (v11 + v12); - - b2Vec2 tangent = b2Mul(xf1.q, localTangent); - b2Vec2 normal = b2Cross(tangent, 1.0f); - - v11 = b2Mul(xf1, v11); - v12 = b2Mul(xf1, v12); - - // Face offset. - float32 frontOffset = b2Dot(normal, v11); - - // Side offsets, extended by polytope skin thickness. - float32 sideOffset1 = -b2Dot(tangent, v11) + totalRadius; - float32 sideOffset2 = b2Dot(tangent, v12) + totalRadius; - - // Clip incident edge against extruded edge1 side edges. - b2ClipVertex clipPoints1[2]; - b2ClipVertex clipPoints2[2]; - int np; - - // Clip to box side 1 - np = b2ClipSegmentToLine(clipPoints1, incidentEdge, -tangent, sideOffset1, iv1); - - if (np < 2) - return; - - // Clip to negative box side 1 - np = b2ClipSegmentToLine(clipPoints2, clipPoints1, tangent, sideOffset2, iv2); - - if (np < 2) - { - return; - } - - // Now clipPoints2 contains the clipped points. - manifold->localNormal = localNormal; - manifold->localPoint = planePoint; - - int32 pointCount = 0; - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - float32 separation = b2Dot(normal, clipPoints2[i].v) - frontOffset; - - if (separation <= totalRadius) - { - b2ManifoldPoint* cp = manifold->points + pointCount; - cp->localPoint = b2MulT(xf2, clipPoints2[i].v); - cp->id = clipPoints2[i].id; - if (flip) - { - // Swap features - b2ContactFeature cf = cp->id.cf; - cp->id.cf.indexA = cf.indexB; - cp->id.cf.indexB = cf.indexA; - cp->id.cf.typeA = cf.typeB; - cp->id.cf.typeB = cf.typeA; - } - ++pointCount; - } - } - - manifold->pointCount = pointCount; -} diff --git a/libjin/3rdparty/Box2D/Collision/b2Collision.cpp b/libjin/3rdparty/Box2D/Collision/b2Collision.cpp deleted file mode 100644 index 10e0b59..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2Collision.cpp +++ /dev/null @@ -1,252 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/b2Distance.h" - -void b2WorldManifold::Initialize(const b2Manifold* manifold, - const b2Transform& xfA, float32 radiusA, - const b2Transform& xfB, float32 radiusB) -{ - if (manifold->pointCount == 0) - { - return; - } - - switch (manifold->type) - { - case b2Manifold::e_circles: - { - normal.Set(1.0f, 0.0f); - b2Vec2 pointA = b2Mul(xfA, manifold->localPoint); - b2Vec2 pointB = b2Mul(xfB, manifold->points[0].localPoint); - if (b2DistanceSquared(pointA, pointB) > b2_epsilon * b2_epsilon) - { - normal = pointB - pointA; - normal.Normalize(); - } - - b2Vec2 cA = pointA + radiusA * normal; - b2Vec2 cB = pointB - radiusB * normal; - points[0] = 0.5f * (cA + cB); - separations[0] = b2Dot(cB - cA, normal); - } - break; - - case b2Manifold::e_faceA: - { - normal = b2Mul(xfA.q, manifold->localNormal); - b2Vec2 planePoint = b2Mul(xfA, manifold->localPoint); - - for (int32 i = 0; i < manifold->pointCount; ++i) - { - b2Vec2 clipPoint = b2Mul(xfB, manifold->points[i].localPoint); - b2Vec2 cA = clipPoint + (radiusA - b2Dot(clipPoint - planePoint, normal)) * normal; - b2Vec2 cB = clipPoint - radiusB * normal; - points[i] = 0.5f * (cA + cB); - separations[i] = b2Dot(cB - cA, normal); - } - } - break; - - case b2Manifold::e_faceB: - { - normal = b2Mul(xfB.q, manifold->localNormal); - b2Vec2 planePoint = b2Mul(xfB, manifold->localPoint); - - for (int32 i = 0; i < manifold->pointCount; ++i) - { - b2Vec2 clipPoint = b2Mul(xfA, manifold->points[i].localPoint); - b2Vec2 cB = clipPoint + (radiusB - b2Dot(clipPoint - planePoint, normal)) * normal; - b2Vec2 cA = clipPoint - radiusA * normal; - points[i] = 0.5f * (cA + cB); - separations[i] = b2Dot(cA - cB, normal); - } - - // Ensure normal points from A to B. - normal = -normal; - } - break; - } -} - -void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], - const b2Manifold* manifold1, const b2Manifold* manifold2) -{ - for (int32 i = 0; i < b2_maxManifoldPoints; ++i) - { - state1[i] = b2_nullState; - state2[i] = b2_nullState; - } - - // Detect persists and removes. - for (int32 i = 0; i < manifold1->pointCount; ++i) - { - b2ContactID id = manifold1->points[i].id; - - state1[i] = b2_removeState; - - for (int32 j = 0; j < manifold2->pointCount; ++j) - { - if (manifold2->points[j].id.key == id.key) - { - state1[i] = b2_persistState; - break; - } - } - } - - // Detect persists and adds. - for (int32 i = 0; i < manifold2->pointCount; ++i) - { - b2ContactID id = manifold2->points[i].id; - - state2[i] = b2_addState; - - for (int32 j = 0; j < manifold1->pointCount; ++j) - { - if (manifold1->points[j].id.key == id.key) - { - state2[i] = b2_persistState; - break; - } - } - } -} - -// From Real-time Collision Detection, p179. -bool b2AABB::RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const -{ - float32 tmin = -b2_maxFloat; - float32 tmax = b2_maxFloat; - - b2Vec2 p = input.p1; - b2Vec2 d = input.p2 - input.p1; - b2Vec2 absD = b2Abs(d); - - b2Vec2 normal; - - for (int32 i = 0; i < 2; ++i) - { - if (absD(i) < b2_epsilon) - { - // Parallel. - if (p(i) < lowerBound(i) || upperBound(i) < p(i)) - { - return false; - } - } - else - { - float32 inv_d = 1.0f / d(i); - float32 t1 = (lowerBound(i) - p(i)) * inv_d; - float32 t2 = (upperBound(i) - p(i)) * inv_d; - - // Sign of the normal vector. - float32 s = -1.0f; - - if (t1 > t2) - { - b2Swap(t1, t2); - s = 1.0f; - } - - // Push the min up - if (t1 > tmin) - { - normal.SetZero(); - normal(i) = s; - tmin = t1; - } - - // Pull the max down - tmax = b2Min(tmax, t2); - - if (tmin > tmax) - { - return false; - } - } - } - - // Does the ray start inside the box? - // Does the ray intersect beyond the max fraction? - if (tmin < 0.0f || input.maxFraction < tmin) - { - return false; - } - - // Intersection. - output->fraction = tmin; - output->normal = normal; - return true; -} - -// Sutherland-Hodgman clipping. -int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset, int32 vertexIndexA) -{ - // Start with no output points - int32 numOut = 0; - - // Calculate the distance of end points to the line - float32 distance0 = b2Dot(normal, vIn[0].v) - offset; - float32 distance1 = b2Dot(normal, vIn[1].v) - offset; - - // If the points are behind the plane - if (distance0 <= 0.0f) vOut[numOut++] = vIn[0]; - if (distance1 <= 0.0f) vOut[numOut++] = vIn[1]; - - // If the points are on different sides of the plane - if (distance0 * distance1 < 0.0f) - { - // Find intersection point of edge and plane - float32 interp = distance0 / (distance0 - distance1); - vOut[numOut].v = vIn[0].v + interp * (vIn[1].v - vIn[0].v); - - // VertexA is hitting edgeB. - vOut[numOut].id.cf.indexA = static_cast<uint8>(vertexIndexA); - vOut[numOut].id.cf.indexB = vIn[0].id.cf.indexB; - vOut[numOut].id.cf.typeA = b2ContactFeature::e_vertex; - vOut[numOut].id.cf.typeB = b2ContactFeature::e_face; - ++numOut; - } - - return numOut; -} - -bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, - const b2Shape* shapeB, int32 indexB, - const b2Transform& xfA, const b2Transform& xfB) -{ - b2DistanceInput input; - input.proxyA.Set(shapeA, indexA); - input.proxyB.Set(shapeB, indexB); - input.transformA = xfA; - input.transformB = xfB; - input.useRadii = true; - - b2SimplexCache cache; - cache.count = 0; - - b2DistanceOutput output; - - b2Distance(&output, &cache, &input); - - return output.distance < 10.0f * b2_epsilon; -} diff --git a/libjin/3rdparty/Box2D/Collision/b2Collision.h b/libjin/3rdparty/Box2D/Collision/b2Collision.h deleted file mode 100644 index fe1f4cd..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2Collision.h +++ /dev/null @@ -1,277 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_COLLISION_H -#define B2_COLLISION_H - -#include "Box2D/Common/b2Math.h" -#include <limits.h> - -/// @file -/// Structures and functions used for computing contact points, distance -/// queries, and TOI queries. - -class b2Shape; -class b2CircleShape; -class b2EdgeShape; -class b2PolygonShape; - -const uint8 b2_nullFeature = UCHAR_MAX; - -/// The features that intersect to form the contact point -/// This must be 4 bytes or less. -struct b2ContactFeature -{ - enum Type - { - e_vertex = 0, - e_face = 1 - }; - - uint8 indexA; ///< Feature index on shapeA - uint8 indexB; ///< Feature index on shapeB - uint8 typeA; ///< The feature type on shapeA - uint8 typeB; ///< The feature type on shapeB -}; - -/// Contact ids to facilitate warm starting. -union b2ContactID -{ - b2ContactFeature cf; - uint32 key; ///< Used to quickly compare contact ids. -}; - -/// A manifold point is a contact point belonging to a contact -/// manifold. It holds details related to the geometry and dynamics -/// of the contact points. -/// The local point usage depends on the manifold type: -/// -e_circles: the local center of circleB -/// -e_faceA: the local center of cirlceB or the clip point of polygonB -/// -e_faceB: the clip point of polygonA -/// This structure is stored across time steps, so we keep it small. -/// Note: the impulses are used for internal caching and may not -/// provide reliable contact forces, especially for high speed collisions. -struct b2ManifoldPoint -{ - b2Vec2 localPoint; ///< usage depends on manifold type - float32 normalImpulse; ///< the non-penetration impulse - float32 tangentImpulse; ///< the friction impulse - b2ContactID id; ///< uniquely identifies a contact point between two shapes -}; - -/// A manifold for two touching convex shapes. -/// Box2D supports multiple types of contact: -/// - clip point versus plane with radius -/// - point versus point with radius (circles) -/// The local point usage depends on the manifold type: -/// -e_circles: the local center of circleA -/// -e_faceA: the center of faceA -/// -e_faceB: the center of faceB -/// Similarly the local normal usage: -/// -e_circles: not used -/// -e_faceA: the normal on polygonA -/// -e_faceB: the normal on polygonB -/// We store contacts in this way so that position correction can -/// account for movement, which is critical for continuous physics. -/// All contact scenarios must be expressed in one of these types. -/// This structure is stored across time steps, so we keep it small. -struct b2Manifold -{ - enum Type - { - e_circles, - e_faceA, - e_faceB - }; - - b2ManifoldPoint points[b2_maxManifoldPoints]; ///< the points of contact - b2Vec2 localNormal; ///< not use for Type::e_points - b2Vec2 localPoint; ///< usage depends on manifold type - Type type; - int32 pointCount; ///< the number of manifold points -}; - -/// This is used to compute the current state of a contact manifold. -struct b2WorldManifold -{ - /// Evaluate the manifold with supplied transforms. This assumes - /// modest motion from the original state. This does not change the - /// point count, impulses, etc. The radii must come from the shapes - /// that generated the manifold. - void Initialize(const b2Manifold* manifold, - const b2Transform& xfA, float32 radiusA, - const b2Transform& xfB, float32 radiusB); - - b2Vec2 normal; ///< world vector pointing from A to B - b2Vec2 points[b2_maxManifoldPoints]; ///< world contact point (point of intersection) - float32 separations[b2_maxManifoldPoints]; ///< a negative value indicates overlap, in meters -}; - -/// This is used for determining the state of contact points. -enum b2PointState -{ - b2_nullState, ///< point does not exist - b2_addState, ///< point was added in the update - b2_persistState, ///< point persisted across the update - b2_removeState ///< point was removed in the update -}; - -/// Compute the point states given two manifolds. The states pertain to the transition from manifold1 -/// to manifold2. So state1 is either persist or remove while state2 is either add or persist. -void b2GetPointStates(b2PointState state1[b2_maxManifoldPoints], b2PointState state2[b2_maxManifoldPoints], - const b2Manifold* manifold1, const b2Manifold* manifold2); - -/// Used for computing contact manifolds. -struct b2ClipVertex -{ - b2Vec2 v; - b2ContactID id; -}; - -/// Ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). -struct b2RayCastInput -{ - b2Vec2 p1, p2; - float32 maxFraction; -}; - -/// Ray-cast output data. The ray hits at p1 + fraction * (p2 - p1), where p1 and p2 -/// come from b2RayCastInput. -struct b2RayCastOutput -{ - b2Vec2 normal; - float32 fraction; -}; - -/// An axis aligned bounding box. -struct b2AABB -{ - /// Verify that the bounds are sorted. - bool IsValid() const; - - /// Get the center of the AABB. - b2Vec2 GetCenter() const - { - return 0.5f * (lowerBound + upperBound); - } - - /// Get the extents of the AABB (half-widths). - b2Vec2 GetExtents() const - { - return 0.5f * (upperBound - lowerBound); - } - - /// Get the perimeter length - float32 GetPerimeter() const - { - float32 wx = upperBound.x - lowerBound.x; - float32 wy = upperBound.y - lowerBound.y; - return 2.0f * (wx + wy); - } - - /// Combine an AABB into this one. - void Combine(const b2AABB& aabb) - { - lowerBound = b2Min(lowerBound, aabb.lowerBound); - upperBound = b2Max(upperBound, aabb.upperBound); - } - - /// Combine two AABBs into this one. - void Combine(const b2AABB& aabb1, const b2AABB& aabb2) - { - lowerBound = b2Min(aabb1.lowerBound, aabb2.lowerBound); - upperBound = b2Max(aabb1.upperBound, aabb2.upperBound); - } - - /// Does this aabb contain the provided AABB. - bool Contains(const b2AABB& aabb) const - { - bool result = true; - result = result && lowerBound.x <= aabb.lowerBound.x; - result = result && lowerBound.y <= aabb.lowerBound.y; - result = result && aabb.upperBound.x <= upperBound.x; - result = result && aabb.upperBound.y <= upperBound.y; - return result; - } - - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input) const; - - b2Vec2 lowerBound; ///< the lower vertex - b2Vec2 upperBound; ///< the upper vertex -}; - -/// Compute the collision manifold between two circles. -void b2CollideCircles(b2Manifold* manifold, - const b2CircleShape* circleA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between a polygon and a circle. -void b2CollidePolygonAndCircle(b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between two polygons. -void b2CollidePolygons(b2Manifold* manifold, - const b2PolygonShape* polygonA, const b2Transform& xfA, - const b2PolygonShape* polygonB, const b2Transform& xfB); - -/// Compute the collision manifold between an edge and a circle. -void b2CollideEdgeAndCircle(b2Manifold* manifold, - const b2EdgeShape* polygonA, const b2Transform& xfA, - const b2CircleShape* circleB, const b2Transform& xfB); - -/// Compute the collision manifold between an edge and a circle. -void b2CollideEdgeAndPolygon(b2Manifold* manifold, - const b2EdgeShape* edgeA, const b2Transform& xfA, - const b2PolygonShape* circleB, const b2Transform& xfB); - -/// Clipping for contact manifolds. -int32 b2ClipSegmentToLine(b2ClipVertex vOut[2], const b2ClipVertex vIn[2], - const b2Vec2& normal, float32 offset, int32 vertexIndexA); - -/// Determine if two generic shapes overlap. -bool b2TestOverlap( const b2Shape* shapeA, int32 indexA, - const b2Shape* shapeB, int32 indexB, - const b2Transform& xfA, const b2Transform& xfB); - -// ---------------- Inline Functions ------------------------------------------ - -inline bool b2AABB::IsValid() const -{ - b2Vec2 d = upperBound - lowerBound; - bool valid = d.x >= 0.0f && d.y >= 0.0f; - valid = valid && lowerBound.IsValid() && upperBound.IsValid(); - return valid; -} - -inline bool b2TestOverlap(const b2AABB& a, const b2AABB& b) -{ - b2Vec2 d1, d2; - d1 = b.lowerBound - a.upperBound; - d2 = a.lowerBound - b.upperBound; - - if (d1.x > 0.0f || d1.y > 0.0f) - return false; - - if (d2.x > 0.0f || d2.y > 0.0f) - return false; - - return true; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/b2Distance.cpp b/libjin/3rdparty/Box2D/Collision/b2Distance.cpp deleted file mode 100644 index 194d747..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2Distance.cpp +++ /dev/null @@ -1,737 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/b2Distance.h" -#include "Box2D/Collision/Shapes/b2CircleShape.h" -#include "Box2D/Collision/Shapes/b2EdgeShape.h" -#include "Box2D/Collision/Shapes/b2ChainShape.h" -#include "Box2D/Collision/Shapes/b2PolygonShape.h" - -// GJK using Voronoi regions (Christer Ericson) and Barycentric coordinates. -int32 b2_gjkCalls, b2_gjkIters, b2_gjkMaxIters; - -void b2DistanceProxy::Set(const b2Shape* shape, int32 index) -{ - switch (shape->GetType()) - { - case b2Shape::e_circle: - { - const b2CircleShape* circle = static_cast<const b2CircleShape*>(shape); - m_vertices = &circle->m_p; - m_count = 1; - m_radius = circle->m_radius; - } - break; - - case b2Shape::e_polygon: - { - const b2PolygonShape* polygon = static_cast<const b2PolygonShape*>(shape); - m_vertices = polygon->m_vertices; - m_count = polygon->m_count; - m_radius = polygon->m_radius; - } - break; - - case b2Shape::e_chain: - { - const b2ChainShape* chain = static_cast<const b2ChainShape*>(shape); - b2Assert(0 <= index && index < chain->m_count); - - m_buffer[0] = chain->m_vertices[index]; - if (index + 1 < chain->m_count) - { - m_buffer[1] = chain->m_vertices[index + 1]; - } - else - { - m_buffer[1] = chain->m_vertices[0]; - } - - m_vertices = m_buffer; - m_count = 2; - m_radius = chain->m_radius; - } - break; - - case b2Shape::e_edge: - { - const b2EdgeShape* edge = static_cast<const b2EdgeShape*>(shape); - m_vertices = &edge->m_vertex1; - m_count = 2; - m_radius = edge->m_radius; - } - break; - - default: - b2Assert(false); - } -} - -void b2DistanceProxy::Set(const b2Vec2* vertices, int32 count, float32 radius) -{ - m_vertices = vertices; - m_count = count; - m_radius = radius; -} - -struct b2SimplexVertex -{ - b2Vec2 wA; // support point in proxyA - b2Vec2 wB; // support point in proxyB - b2Vec2 w; // wB - wA - float32 a; // barycentric coordinate for closest point - int32 indexA; // wA index - int32 indexB; // wB index -}; - -struct b2Simplex -{ - void ReadCache( const b2SimplexCache* cache, - const b2DistanceProxy* proxyA, const b2Transform& transformA, - const b2DistanceProxy* proxyB, const b2Transform& transformB) - { - b2Assert(cache->count <= 3); - - // Copy data from cache. - m_count = cache->count; - b2SimplexVertex* vertices = &m_v1; - for (int32 i = 0; i < m_count; ++i) - { - b2SimplexVertex* v = vertices + i; - v->indexA = cache->indexA[i]; - v->indexB = cache->indexB[i]; - b2Vec2 wALocal = proxyA->GetVertex(v->indexA); - b2Vec2 wBLocal = proxyB->GetVertex(v->indexB); - v->wA = b2Mul(transformA, wALocal); - v->wB = b2Mul(transformB, wBLocal); - v->w = v->wB - v->wA; - v->a = 0.0f; - } - - // Compute the new simplex metric, if it is substantially different than - // old metric then flush the simplex. - if (m_count > 1) - { - float32 metric1 = cache->metric; - float32 metric2 = GetMetric(); - if (metric2 < 0.5f * metric1 || 2.0f * metric1 < metric2 || metric2 < b2_epsilon) - { - // Reset the simplex. - m_count = 0; - } - } - - // If the cache is empty or invalid ... - if (m_count == 0) - { - b2SimplexVertex* v = vertices + 0; - v->indexA = 0; - v->indexB = 0; - b2Vec2 wALocal = proxyA->GetVertex(0); - b2Vec2 wBLocal = proxyB->GetVertex(0); - v->wA = b2Mul(transformA, wALocal); - v->wB = b2Mul(transformB, wBLocal); - v->w = v->wB - v->wA; - v->a = 1.0f; - m_count = 1; - } - } - - void WriteCache(b2SimplexCache* cache) const - { - cache->metric = GetMetric(); - cache->count = uint16(m_count); - const b2SimplexVertex* vertices = &m_v1; - for (int32 i = 0; i < m_count; ++i) - { - cache->indexA[i] = uint8(vertices[i].indexA); - cache->indexB[i] = uint8(vertices[i].indexB); - } - } - - b2Vec2 GetSearchDirection() const - { - switch (m_count) - { - case 1: - return -m_v1.w; - - case 2: - { - b2Vec2 e12 = m_v2.w - m_v1.w; - float32 sgn = b2Cross(e12, -m_v1.w); - if (sgn > 0.0f) - { - // Origin is left of e12. - return b2Cross(1.0f, e12); - } - else - { - // Origin is right of e12. - return b2Cross(e12, 1.0f); - } - } - - default: - b2Assert(false); - return b2Vec2_zero; - } - } - - b2Vec2 GetClosestPoint() const - { - switch (m_count) - { - case 0: - b2Assert(false); - return b2Vec2_zero; - - case 1: - return m_v1.w; - - case 2: - return m_v1.a * m_v1.w + m_v2.a * m_v2.w; - - case 3: - return b2Vec2_zero; - - default: - b2Assert(false); - return b2Vec2_zero; - } - } - - void GetWitnessPoints(b2Vec2* pA, b2Vec2* pB) const - { - switch (m_count) - { - case 0: - b2Assert(false); - break; - - case 1: - *pA = m_v1.wA; - *pB = m_v1.wB; - break; - - case 2: - *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA; - *pB = m_v1.a * m_v1.wB + m_v2.a * m_v2.wB; - break; - - case 3: - *pA = m_v1.a * m_v1.wA + m_v2.a * m_v2.wA + m_v3.a * m_v3.wA; - *pB = *pA; - break; - - default: - b2Assert(false); - break; - } - } - - float32 GetMetric() const - { - switch (m_count) - { - case 0: - b2Assert(false); - return 0.0f; - - case 1: - return 0.0f; - - case 2: - return b2Distance(m_v1.w, m_v2.w); - - case 3: - return b2Cross(m_v2.w - m_v1.w, m_v3.w - m_v1.w); - - default: - b2Assert(false); - return 0.0f; - } - } - - void Solve2(); - void Solve3(); - - b2SimplexVertex m_v1, m_v2, m_v3; - int32 m_count; -}; - - -// Solve a line segment using barycentric coordinates. -// -// p = a1 * w1 + a2 * w2 -// a1 + a2 = 1 -// -// The vector from the origin to the closest point on the line is -// perpendicular to the line. -// e12 = w2 - w1 -// dot(p, e) = 0 -// a1 * dot(w1, e) + a2 * dot(w2, e) = 0 -// -// 2-by-2 linear system -// [1 1 ][a1] = [1] -// [w1.e12 w2.e12][a2] = [0] -// -// Define -// d12_1 = dot(w2, e12) -// d12_2 = -dot(w1, e12) -// d12 = d12_1 + d12_2 -// -// Solution -// a1 = d12_1 / d12 -// a2 = d12_2 / d12 -void b2Simplex::Solve2() -{ - b2Vec2 w1 = m_v1.w; - b2Vec2 w2 = m_v2.w; - b2Vec2 e12 = w2 - w1; - - // w1 region - float32 d12_2 = -b2Dot(w1, e12); - if (d12_2 <= 0.0f) - { - // a2 <= 0, so we clamp it to 0 - m_v1.a = 1.0f; - m_count = 1; - return; - } - - // w2 region - float32 d12_1 = b2Dot(w2, e12); - if (d12_1 <= 0.0f) - { - // a1 <= 0, so we clamp it to 0 - m_v2.a = 1.0f; - m_count = 1; - m_v1 = m_v2; - return; - } - - // Must be in e12 region. - float32 inv_d12 = 1.0f / (d12_1 + d12_2); - m_v1.a = d12_1 * inv_d12; - m_v2.a = d12_2 * inv_d12; - m_count = 2; -} - -// Possible regions: -// - points[2] -// - edge points[0]-points[2] -// - edge points[1]-points[2] -// - inside the triangle -void b2Simplex::Solve3() -{ - b2Vec2 w1 = m_v1.w; - b2Vec2 w2 = m_v2.w; - b2Vec2 w3 = m_v3.w; - - // Edge12 - // [1 1 ][a1] = [1] - // [w1.e12 w2.e12][a2] = [0] - // a3 = 0 - b2Vec2 e12 = w2 - w1; - float32 w1e12 = b2Dot(w1, e12); - float32 w2e12 = b2Dot(w2, e12); - float32 d12_1 = w2e12; - float32 d12_2 = -w1e12; - - // Edge13 - // [1 1 ][a1] = [1] - // [w1.e13 w3.e13][a3] = [0] - // a2 = 0 - b2Vec2 e13 = w3 - w1; - float32 w1e13 = b2Dot(w1, e13); - float32 w3e13 = b2Dot(w3, e13); - float32 d13_1 = w3e13; - float32 d13_2 = -w1e13; - - // Edge23 - // [1 1 ][a2] = [1] - // [w2.e23 w3.e23][a3] = [0] - // a1 = 0 - b2Vec2 e23 = w3 - w2; - float32 w2e23 = b2Dot(w2, e23); - float32 w3e23 = b2Dot(w3, e23); - float32 d23_1 = w3e23; - float32 d23_2 = -w2e23; - - // Triangle123 - float32 n123 = b2Cross(e12, e13); - - float32 d123_1 = n123 * b2Cross(w2, w3); - float32 d123_2 = n123 * b2Cross(w3, w1); - float32 d123_3 = n123 * b2Cross(w1, w2); - - // w1 region - if (d12_2 <= 0.0f && d13_2 <= 0.0f) - { - m_v1.a = 1.0f; - m_count = 1; - return; - } - - // e12 - if (d12_1 > 0.0f && d12_2 > 0.0f && d123_3 <= 0.0f) - { - float32 inv_d12 = 1.0f / (d12_1 + d12_2); - m_v1.a = d12_1 * inv_d12; - m_v2.a = d12_2 * inv_d12; - m_count = 2; - return; - } - - // e13 - if (d13_1 > 0.0f && d13_2 > 0.0f && d123_2 <= 0.0f) - { - float32 inv_d13 = 1.0f / (d13_1 + d13_2); - m_v1.a = d13_1 * inv_d13; - m_v3.a = d13_2 * inv_d13; - m_count = 2; - m_v2 = m_v3; - return; - } - - // w2 region - if (d12_1 <= 0.0f && d23_2 <= 0.0f) - { - m_v2.a = 1.0f; - m_count = 1; - m_v1 = m_v2; - return; - } - - // w3 region - if (d13_1 <= 0.0f && d23_1 <= 0.0f) - { - m_v3.a = 1.0f; - m_count = 1; - m_v1 = m_v3; - return; - } - - // e23 - if (d23_1 > 0.0f && d23_2 > 0.0f && d123_1 <= 0.0f) - { - float32 inv_d23 = 1.0f / (d23_1 + d23_2); - m_v2.a = d23_1 * inv_d23; - m_v3.a = d23_2 * inv_d23; - m_count = 2; - m_v1 = m_v3; - return; - } - - // Must be in triangle123 - float32 inv_d123 = 1.0f / (d123_1 + d123_2 + d123_3); - m_v1.a = d123_1 * inv_d123; - m_v2.a = d123_2 * inv_d123; - m_v3.a = d123_3 * inv_d123; - m_count = 3; -} - -void b2Distance(b2DistanceOutput* output, - b2SimplexCache* cache, - const b2DistanceInput* input) -{ - ++b2_gjkCalls; - - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; - - b2Transform transformA = input->transformA; - b2Transform transformB = input->transformB; - - // Initialize the simplex. - b2Simplex simplex; - simplex.ReadCache(cache, proxyA, transformA, proxyB, transformB); - - // Get simplex vertices as an array. - b2SimplexVertex* vertices = &simplex.m_v1; - const int32 k_maxIters = 20; - - // These store the vertices of the last simplex so that we - // can check for duplicates and prevent cycling. - int32 saveA[3], saveB[3]; - int32 saveCount = 0; - - // Main iteration loop. - int32 iter = 0; - while (iter < k_maxIters) - { - // Copy simplex so we can identify duplicates. - saveCount = simplex.m_count; - for (int32 i = 0; i < saveCount; ++i) - { - saveA[i] = vertices[i].indexA; - saveB[i] = vertices[i].indexB; - } - - switch (simplex.m_count) - { - case 1: - break; - - case 2: - simplex.Solve2(); - break; - - case 3: - simplex.Solve3(); - break; - - default: - b2Assert(false); - } - - // If we have 3 points, then the origin is in the corresponding triangle. - if (simplex.m_count == 3) - { - break; - } - - // Get search direction. - b2Vec2 d = simplex.GetSearchDirection(); - - // Ensure the search direction is numerically fit. - if (d.LengthSquared() < b2_epsilon * b2_epsilon) - { - // The origin is probably contained by a line segment - // or triangle. Thus the shapes are overlapped. - - // We can't return zero here even though there may be overlap. - // In case the simplex is a point, segment, or triangle it is difficult - // to determine if the origin is contained in the CSO or very close to it. - break; - } - - // Compute a tentative new simplex vertex using support points. - b2SimplexVertex* vertex = vertices + simplex.m_count; - vertex->indexA = proxyA->GetSupport(b2MulT(transformA.q, -d)); - vertex->wA = b2Mul(transformA, proxyA->GetVertex(vertex->indexA)); - b2Vec2 wBLocal; - vertex->indexB = proxyB->GetSupport(b2MulT(transformB.q, d)); - vertex->wB = b2Mul(transformB, proxyB->GetVertex(vertex->indexB)); - vertex->w = vertex->wB - vertex->wA; - - // Iteration count is equated to the number of support point calls. - ++iter; - ++b2_gjkIters; - - // Check for duplicate support points. This is the main termination criteria. - bool duplicate = false; - for (int32 i = 0; i < saveCount; ++i) - { - if (vertex->indexA == saveA[i] && vertex->indexB == saveB[i]) - { - duplicate = true; - break; - } - } - - // If we found a duplicate support point we must exit to avoid cycling. - if (duplicate) - { - break; - } - - // New vertex is ok and needed. - ++simplex.m_count; - } - - b2_gjkMaxIters = b2Max(b2_gjkMaxIters, iter); - - // Prepare output. - simplex.GetWitnessPoints(&output->pointA, &output->pointB); - output->distance = b2Distance(output->pointA, output->pointB); - output->iterations = iter; - - // Cache the simplex. - simplex.WriteCache(cache); - - // Apply radii if requested. - if (input->useRadii) - { - float32 rA = proxyA->m_radius; - float32 rB = proxyB->m_radius; - - if (output->distance > rA + rB && output->distance > b2_epsilon) - { - // Shapes are still no overlapped. - // Move the witness points to the outer surface. - output->distance -= rA + rB; - b2Vec2 normal = output->pointB - output->pointA; - normal.Normalize(); - output->pointA += rA * normal; - output->pointB -= rB * normal; - } - else - { - // Shapes are overlapped when radii are considered. - // Move the witness points to the middle. - b2Vec2 p = 0.5f * (output->pointA + output->pointB); - output->pointA = p; - output->pointB = p; - output->distance = 0.0f; - } - } -} - -// GJK-raycast -// Algorithm by Gino van den Bergen. -// "Smooth Mesh Contacts with GJK" in Game Physics Pearls. 2010 -bool b2ShapeCast(b2ShapeCastOutput * output, const b2ShapeCastInput * input) -{ - output->iterations = 0; - output->lambda = 1.0f; - output->normal.SetZero(); - output->point.SetZero(); - - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; - - float32 radiusA = b2Max(proxyA->m_radius, b2_polygonRadius); - float32 radiusB = b2Max(proxyB->m_radius, b2_polygonRadius); - float32 radius = radiusA + radiusB; - - b2Transform xfA = input->transformA; - b2Transform xfB = input->transformB; - - b2Vec2 r = input->translationB; - b2Vec2 n(0.0f, 0.0f); - float32 lambda = 0.0f; - - // Initial simplex - b2Simplex simplex; - simplex.m_count = 0; - - // Get simplex vertices as an array. - b2SimplexVertex* vertices = &simplex.m_v1; - - // Get support point in -r direction - int32 indexA = proxyA->GetSupport(b2MulT(xfA.q, -r)); - b2Vec2 wA = b2Mul(xfA, proxyA->GetVertex(indexA)); - int32 indexB = proxyB->GetSupport(b2MulT(xfB.q, r)); - b2Vec2 wB = b2Mul(xfB, proxyB->GetVertex(indexB)); - b2Vec2 v = wA - wB; - - // Sigma is the target distance between polygons - float32 sigma = b2Max(b2_polygonRadius, radius - b2_polygonRadius); - const float32 tolerance = 0.5f * b2_linearSlop; - - // Main iteration loop. - const int32 k_maxIters = 20; - int32 iter = 0; - while (iter < k_maxIters && b2Abs(v.Length() - sigma) > tolerance) - { - b2Assert(simplex.m_count < 3); - - output->iterations += 1; - - // Support in direction -v (A - B) - indexA = proxyA->GetSupport(b2MulT(xfA.q, -v)); - wA = b2Mul(xfA, proxyA->GetVertex(indexA)); - indexB = proxyB->GetSupport(b2MulT(xfB.q, v)); - wB = b2Mul(xfB, proxyB->GetVertex(indexB)); - b2Vec2 p = wA - wB; - - // -v is a normal at p - v.Normalize(); - - // Intersect ray with plane - float32 vp = b2Dot(v, p); - float32 vr = b2Dot(v, r); - if (vp - sigma > lambda * vr) - { - if (vr <= 0.0f) - { - return false; - } - - lambda = (vp - sigma) / vr; - if (lambda > 1.0f) - { - return false; - } - - n = -v; - simplex.m_count = 0; - } - - // Reverse simplex since it works with B - A. - // Shift by lambda * r because we want the closest point to the current clip point. - // Note that the support point p is not shifted because we want the plane equation - // to be formed in unshifted space. - b2SimplexVertex* vertex = vertices + simplex.m_count; - vertex->indexA = indexB; - vertex->wA = wB + lambda * r; - vertex->indexB = indexA; - vertex->wB = wA; - vertex->w = vertex->wB - vertex->wA; - vertex->a = 1.0f; - simplex.m_count += 1; - - switch (simplex.m_count) - { - case 1: - break; - - case 2: - simplex.Solve2(); - break; - - case 3: - simplex.Solve3(); - break; - - default: - b2Assert(false); - } - - // If we have 3 points, then the origin is in the corresponding triangle. - if (simplex.m_count == 3) - { - // Overlap - return false; - } - - // Get search direction. - v = simplex.GetClosestPoint(); - - // Iteration count is equated to the number of support point calls. - ++iter; - } - - // Prepare output. - b2Vec2 pointA, pointB; - simplex.GetWitnessPoints(&pointB, &pointA); - - if (v.LengthSquared() > 0.0f) - { - n = -v; - n.Normalize(); - } - - output->point = pointA + radiusA * n; - output->normal = n; - output->lambda = lambda; - output->iterations = iter; - return true; -} diff --git a/libjin/3rdparty/Box2D/Collision/b2Distance.h b/libjin/3rdparty/Box2D/Collision/b2Distance.h deleted file mode 100644 index d6eb985..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2Distance.h +++ /dev/null @@ -1,166 +0,0 @@ - -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_DISTANCE_H -#define B2_DISTANCE_H - -#include "Box2D/Common/b2Math.h" - -class b2Shape; - -/// A distance proxy is used by the GJK algorithm. -/// It encapsulates any shape. -struct b2DistanceProxy -{ - b2DistanceProxy() : m_vertices(nullptr), m_count(0), m_radius(0.0f) {} - - /// Initialize the proxy using the given shape. The shape - /// must remain in scope while the proxy is in use. - void Set(const b2Shape* shape, int32 index); - - /// Initialize the proxy using a vertex cloud and radius. The vertices - /// must remain in scope while the proxy is in use. - void Set(const b2Vec2* vertices, int32 count, float32 radius); - - /// Get the supporting vertex index in the given direction. - int32 GetSupport(const b2Vec2& d) const; - - /// Get the supporting vertex in the given direction. - const b2Vec2& GetSupportVertex(const b2Vec2& d) const; - - /// Get the vertex count. - int32 GetVertexCount() const; - - /// Get a vertex by index. Used by b2Distance. - const b2Vec2& GetVertex(int32 index) const; - - b2Vec2 m_buffer[2]; - const b2Vec2* m_vertices; - int32 m_count; - float32 m_radius; -}; - -/// Used to warm start b2Distance. -/// Set count to zero on first call. -struct b2SimplexCache -{ - float32 metric; ///< length or area - uint16 count; - uint8 indexA[3]; ///< vertices on shape A - uint8 indexB[3]; ///< vertices on shape B -}; - -/// Input for b2Distance. -/// You have to option to use the shape radii -/// in the computation. Even -struct b2DistanceInput -{ - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Transform transformA; - b2Transform transformB; - bool useRadii; -}; - -/// Output for b2Distance. -struct b2DistanceOutput -{ - b2Vec2 pointA; ///< closest point on shapeA - b2Vec2 pointB; ///< closest point on shapeB - float32 distance; - int32 iterations; ///< number of GJK iterations used -}; - -/// Compute the closest points between two shapes. Supports any combination of: -/// b2CircleShape, b2PolygonShape, b2EdgeShape. The simplex cache is input/output. -/// On the first call set b2SimplexCache.count to zero. -void b2Distance(b2DistanceOutput* output, - b2SimplexCache* cache, - const b2DistanceInput* input); - -/// Input parameters for b2ShapeCast -struct b2ShapeCastInput -{ - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Transform transformA; - b2Transform transformB; - b2Vec2 translationB; -}; - -/// Output results for b2ShapeCast -struct b2ShapeCastOutput -{ - b2Vec2 point; - b2Vec2 normal; - float32 lambda; - int32 iterations; -}; - -/// Perform a linear shape cast of shape B moving and shape A fixed. Determines the hit point, normal, and translation fraction. -bool b2ShapeCast(b2ShapeCastOutput* output, const b2ShapeCastInput* input); - -////////////////////////////////////////////////////////////////////////// - -inline int32 b2DistanceProxy::GetVertexCount() const -{ - return m_count; -} - -inline const b2Vec2& b2DistanceProxy::GetVertex(int32 index) const -{ - b2Assert(0 <= index && index < m_count); - return m_vertices[index]; -} - -inline int32 b2DistanceProxy::GetSupport(const b2Vec2& d) const -{ - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_count; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return bestIndex; -} - -inline const b2Vec2& b2DistanceProxy::GetSupportVertex(const b2Vec2& d) const -{ - int32 bestIndex = 0; - float32 bestValue = b2Dot(m_vertices[0], d); - for (int32 i = 1; i < m_count; ++i) - { - float32 value = b2Dot(m_vertices[i], d); - if (value > bestValue) - { - bestIndex = i; - bestValue = value; - } - } - - return m_vertices[bestIndex]; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/b2DynamicTree.cpp b/libjin/3rdparty/Box2D/Collision/b2DynamicTree.cpp deleted file mode 100644 index 4432ec1..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2DynamicTree.cpp +++ /dev/null @@ -1,780 +0,0 @@ -/* -* Copyright (c) 2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/b2DynamicTree.h" -#include <string.h> - -b2DynamicTree::b2DynamicTree() -{ - m_root = b2_nullNode; - - m_nodeCapacity = 16; - m_nodeCount = 0; - m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); - memset(m_nodes, 0, m_nodeCapacity * sizeof(b2TreeNode)); - - // Build a linked list for the free list. - for (int32 i = 0; i < m_nodeCapacity - 1; ++i) - { - m_nodes[i].next = i + 1; - m_nodes[i].height = -1; - } - m_nodes[m_nodeCapacity-1].next = b2_nullNode; - m_nodes[m_nodeCapacity-1].height = -1; - m_freeList = 0; - - m_path = 0; - - m_insertionCount = 0; -} - -b2DynamicTree::~b2DynamicTree() -{ - // This frees the entire tree in one shot. - b2Free(m_nodes); -} - -// Allocate a node from the pool. Grow the pool if necessary. -int32 b2DynamicTree::AllocateNode() -{ - // Expand the node pool as needed. - if (m_freeList == b2_nullNode) - { - b2Assert(m_nodeCount == m_nodeCapacity); - - // The free list is empty. Rebuild a bigger pool. - b2TreeNode* oldNodes = m_nodes; - m_nodeCapacity *= 2; - m_nodes = (b2TreeNode*)b2Alloc(m_nodeCapacity * sizeof(b2TreeNode)); - memcpy(m_nodes, oldNodes, m_nodeCount * sizeof(b2TreeNode)); - b2Free(oldNodes); - - // Build a linked list for the free list. The parent - // pointer becomes the "next" pointer. - for (int32 i = m_nodeCount; i < m_nodeCapacity - 1; ++i) - { - m_nodes[i].next = i + 1; - m_nodes[i].height = -1; - } - m_nodes[m_nodeCapacity-1].next = b2_nullNode; - m_nodes[m_nodeCapacity-1].height = -1; - m_freeList = m_nodeCount; - } - - // Peel a node off the free list. - int32 nodeId = m_freeList; - m_freeList = m_nodes[nodeId].next; - m_nodes[nodeId].parent = b2_nullNode; - m_nodes[nodeId].child1 = b2_nullNode; - m_nodes[nodeId].child2 = b2_nullNode; - m_nodes[nodeId].height = 0; - m_nodes[nodeId].userData = nullptr; - ++m_nodeCount; - return nodeId; -} - -// Return a node to the pool. -void b2DynamicTree::FreeNode(int32 nodeId) -{ - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2Assert(0 < m_nodeCount); - m_nodes[nodeId].next = m_freeList; - m_nodes[nodeId].height = -1; - m_freeList = nodeId; - --m_nodeCount; -} - -// Create a proxy in the tree as a leaf node. We return the index -// of the node instead of a pointer so that we can grow -// the node pool. -int32 b2DynamicTree::CreateProxy(const b2AABB& aabb, void* userData) -{ - int32 proxyId = AllocateNode(); - - // Fatten the aabb. - b2Vec2 r(b2_aabbExtension, b2_aabbExtension); - m_nodes[proxyId].aabb.lowerBound = aabb.lowerBound - r; - m_nodes[proxyId].aabb.upperBound = aabb.upperBound + r; - m_nodes[proxyId].userData = userData; - m_nodes[proxyId].height = 0; - - InsertLeaf(proxyId); - - return proxyId; -} - -void b2DynamicTree::DestroyProxy(int32 proxyId) -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - b2Assert(m_nodes[proxyId].IsLeaf()); - - RemoveLeaf(proxyId); - FreeNode(proxyId); -} - -bool b2DynamicTree::MoveProxy(int32 proxyId, const b2AABB& aabb, const b2Vec2& displacement) -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - - b2Assert(m_nodes[proxyId].IsLeaf()); - - if (m_nodes[proxyId].aabb.Contains(aabb)) - { - return false; - } - - RemoveLeaf(proxyId); - - // Extend AABB. - b2AABB b = aabb; - b2Vec2 r(b2_aabbExtension, b2_aabbExtension); - b.lowerBound = b.lowerBound - r; - b.upperBound = b.upperBound + r; - - // Predict AABB displacement. - b2Vec2 d = b2_aabbMultiplier * displacement; - - if (d.x < 0.0f) - { - b.lowerBound.x += d.x; - } - else - { - b.upperBound.x += d.x; - } - - if (d.y < 0.0f) - { - b.lowerBound.y += d.y; - } - else - { - b.upperBound.y += d.y; - } - - m_nodes[proxyId].aabb = b; - - InsertLeaf(proxyId); - return true; -} - -void b2DynamicTree::InsertLeaf(int32 leaf) -{ - ++m_insertionCount; - - if (m_root == b2_nullNode) - { - m_root = leaf; - m_nodes[m_root].parent = b2_nullNode; - return; - } - - // Find the best sibling for this node - b2AABB leafAABB = m_nodes[leaf].aabb; - int32 index = m_root; - while (m_nodes[index].IsLeaf() == false) - { - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - float32 area = m_nodes[index].aabb.GetPerimeter(); - - b2AABB combinedAABB; - combinedAABB.Combine(m_nodes[index].aabb, leafAABB); - float32 combinedArea = combinedAABB.GetPerimeter(); - - // Cost of creating a new parent for this node and the new leaf - float32 cost = 2.0f * combinedArea; - - // Minimum cost of pushing the leaf further down the tree - float32 inheritanceCost = 2.0f * (combinedArea - area); - - // Cost of descending into child1 - float32 cost1; - if (m_nodes[child1].IsLeaf()) - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child1].aabb); - cost1 = aabb.GetPerimeter() + inheritanceCost; - } - else - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child1].aabb); - float32 oldArea = m_nodes[child1].aabb.GetPerimeter(); - float32 newArea = aabb.GetPerimeter(); - cost1 = (newArea - oldArea) + inheritanceCost; - } - - // Cost of descending into child2 - float32 cost2; - if (m_nodes[child2].IsLeaf()) - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child2].aabb); - cost2 = aabb.GetPerimeter() + inheritanceCost; - } - else - { - b2AABB aabb; - aabb.Combine(leafAABB, m_nodes[child2].aabb); - float32 oldArea = m_nodes[child2].aabb.GetPerimeter(); - float32 newArea = aabb.GetPerimeter(); - cost2 = newArea - oldArea + inheritanceCost; - } - - // Descend according to the minimum cost. - if (cost < cost1 && cost < cost2) - { - break; - } - - // Descend - if (cost1 < cost2) - { - index = child1; - } - else - { - index = child2; - } - } - - int32 sibling = index; - - // Create a new parent. - int32 oldParent = m_nodes[sibling].parent; - int32 newParent = AllocateNode(); - m_nodes[newParent].parent = oldParent; - m_nodes[newParent].userData = nullptr; - m_nodes[newParent].aabb.Combine(leafAABB, m_nodes[sibling].aabb); - m_nodes[newParent].height = m_nodes[sibling].height + 1; - - if (oldParent != b2_nullNode) - { - // The sibling was not the root. - if (m_nodes[oldParent].child1 == sibling) - { - m_nodes[oldParent].child1 = newParent; - } - else - { - m_nodes[oldParent].child2 = newParent; - } - - m_nodes[newParent].child1 = sibling; - m_nodes[newParent].child2 = leaf; - m_nodes[sibling].parent = newParent; - m_nodes[leaf].parent = newParent; - } - else - { - // The sibling was the root. - m_nodes[newParent].child1 = sibling; - m_nodes[newParent].child2 = leaf; - m_nodes[sibling].parent = newParent; - m_nodes[leaf].parent = newParent; - m_root = newParent; - } - - // Walk back up the tree fixing heights and AABBs - index = m_nodes[leaf].parent; - while (index != b2_nullNode) - { - index = Balance(index); - - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - b2Assert(child1 != b2_nullNode); - b2Assert(child2 != b2_nullNode); - - m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); - m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - - index = m_nodes[index].parent; - } - - //Validate(); -} - -void b2DynamicTree::RemoveLeaf(int32 leaf) -{ - if (leaf == m_root) - { - m_root = b2_nullNode; - return; - } - - int32 parent = m_nodes[leaf].parent; - int32 grandParent = m_nodes[parent].parent; - int32 sibling; - if (m_nodes[parent].child1 == leaf) - { - sibling = m_nodes[parent].child2; - } - else - { - sibling = m_nodes[parent].child1; - } - - if (grandParent != b2_nullNode) - { - // Destroy parent and connect sibling to grandParent. - if (m_nodes[grandParent].child1 == parent) - { - m_nodes[grandParent].child1 = sibling; - } - else - { - m_nodes[grandParent].child2 = sibling; - } - m_nodes[sibling].parent = grandParent; - FreeNode(parent); - - // Adjust ancestor bounds. - int32 index = grandParent; - while (index != b2_nullNode) - { - index = Balance(index); - - int32 child1 = m_nodes[index].child1; - int32 child2 = m_nodes[index].child2; - - m_nodes[index].aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - m_nodes[index].height = 1 + b2Max(m_nodes[child1].height, m_nodes[child2].height); - - index = m_nodes[index].parent; - } - } - else - { - m_root = sibling; - m_nodes[sibling].parent = b2_nullNode; - FreeNode(parent); - } - - //Validate(); -} - -// Perform a left or right rotation if node A is imbalanced. -// Returns the new root index. -int32 b2DynamicTree::Balance(int32 iA) -{ - b2Assert(iA != b2_nullNode); - - b2TreeNode* A = m_nodes + iA; - if (A->IsLeaf() || A->height < 2) - { - return iA; - } - - int32 iB = A->child1; - int32 iC = A->child2; - b2Assert(0 <= iB && iB < m_nodeCapacity); - b2Assert(0 <= iC && iC < m_nodeCapacity); - - b2TreeNode* B = m_nodes + iB; - b2TreeNode* C = m_nodes + iC; - - int32 balance = C->height - B->height; - - // Rotate C up - if (balance > 1) - { - int32 iF = C->child1; - int32 iG = C->child2; - b2TreeNode* F = m_nodes + iF; - b2TreeNode* G = m_nodes + iG; - b2Assert(0 <= iF && iF < m_nodeCapacity); - b2Assert(0 <= iG && iG < m_nodeCapacity); - - // Swap A and C - C->child1 = iA; - C->parent = A->parent; - A->parent = iC; - - // A's old parent should point to C - if (C->parent != b2_nullNode) - { - if (m_nodes[C->parent].child1 == iA) - { - m_nodes[C->parent].child1 = iC; - } - else - { - b2Assert(m_nodes[C->parent].child2 == iA); - m_nodes[C->parent].child2 = iC; - } - } - else - { - m_root = iC; - } - - // Rotate - if (F->height > G->height) - { - C->child2 = iF; - A->child2 = iG; - G->parent = iA; - A->aabb.Combine(B->aabb, G->aabb); - C->aabb.Combine(A->aabb, F->aabb); - - A->height = 1 + b2Max(B->height, G->height); - C->height = 1 + b2Max(A->height, F->height); - } - else - { - C->child2 = iG; - A->child2 = iF; - F->parent = iA; - A->aabb.Combine(B->aabb, F->aabb); - C->aabb.Combine(A->aabb, G->aabb); - - A->height = 1 + b2Max(B->height, F->height); - C->height = 1 + b2Max(A->height, G->height); - } - - return iC; - } - - // Rotate B up - if (balance < -1) - { - int32 iD = B->child1; - int32 iE = B->child2; - b2TreeNode* D = m_nodes + iD; - b2TreeNode* E = m_nodes + iE; - b2Assert(0 <= iD && iD < m_nodeCapacity); - b2Assert(0 <= iE && iE < m_nodeCapacity); - - // Swap A and B - B->child1 = iA; - B->parent = A->parent; - A->parent = iB; - - // A's old parent should point to B - if (B->parent != b2_nullNode) - { - if (m_nodes[B->parent].child1 == iA) - { - m_nodes[B->parent].child1 = iB; - } - else - { - b2Assert(m_nodes[B->parent].child2 == iA); - m_nodes[B->parent].child2 = iB; - } - } - else - { - m_root = iB; - } - - // Rotate - if (D->height > E->height) - { - B->child2 = iD; - A->child1 = iE; - E->parent = iA; - A->aabb.Combine(C->aabb, E->aabb); - B->aabb.Combine(A->aabb, D->aabb); - - A->height = 1 + b2Max(C->height, E->height); - B->height = 1 + b2Max(A->height, D->height); - } - else - { - B->child2 = iE; - A->child1 = iD; - D->parent = iA; - A->aabb.Combine(C->aabb, D->aabb); - B->aabb.Combine(A->aabb, E->aabb); - - A->height = 1 + b2Max(C->height, D->height); - B->height = 1 + b2Max(A->height, E->height); - } - - return iB; - } - - return iA; -} - -int32 b2DynamicTree::GetHeight() const -{ - if (m_root == b2_nullNode) - { - return 0; - } - - return m_nodes[m_root].height; -} - -// -float32 b2DynamicTree::GetAreaRatio() const -{ - if (m_root == b2_nullNode) - { - return 0.0f; - } - - const b2TreeNode* root = m_nodes + m_root; - float32 rootArea = root->aabb.GetPerimeter(); - - float32 totalArea = 0.0f; - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - const b2TreeNode* node = m_nodes + i; - if (node->height < 0) - { - // Free node in pool - continue; - } - - totalArea += node->aabb.GetPerimeter(); - } - - return totalArea / rootArea; -} - -// Compute the height of a sub-tree. -int32 b2DynamicTree::ComputeHeight(int32 nodeId) const -{ - b2Assert(0 <= nodeId && nodeId < m_nodeCapacity); - b2TreeNode* node = m_nodes + nodeId; - - if (node->IsLeaf()) - { - return 0; - } - - int32 height1 = ComputeHeight(node->child1); - int32 height2 = ComputeHeight(node->child2); - return 1 + b2Max(height1, height2); -} - -int32 b2DynamicTree::ComputeHeight() const -{ - int32 height = ComputeHeight(m_root); - return height; -} - -void b2DynamicTree::ValidateStructure(int32 index) const -{ - if (index == b2_nullNode) - { - return; - } - - if (index == m_root) - { - b2Assert(m_nodes[index].parent == b2_nullNode); - } - - const b2TreeNode* node = m_nodes + index; - - int32 child1 = node->child1; - int32 child2 = node->child2; - - if (node->IsLeaf()) - { - b2Assert(child1 == b2_nullNode); - b2Assert(child2 == b2_nullNode); - b2Assert(node->height == 0); - return; - } - - b2Assert(0 <= child1 && child1 < m_nodeCapacity); - b2Assert(0 <= child2 && child2 < m_nodeCapacity); - - b2Assert(m_nodes[child1].parent == index); - b2Assert(m_nodes[child2].parent == index); - - ValidateStructure(child1); - ValidateStructure(child2); -} - -void b2DynamicTree::ValidateMetrics(int32 index) const -{ - if (index == b2_nullNode) - { - return; - } - - const b2TreeNode* node = m_nodes + index; - - int32 child1 = node->child1; - int32 child2 = node->child2; - - if (node->IsLeaf()) - { - b2Assert(child1 == b2_nullNode); - b2Assert(child2 == b2_nullNode); - b2Assert(node->height == 0); - return; - } - - b2Assert(0 <= child1 && child1 < m_nodeCapacity); - b2Assert(0 <= child2 && child2 < m_nodeCapacity); - - int32 height1 = m_nodes[child1].height; - int32 height2 = m_nodes[child2].height; - int32 height; - height = 1 + b2Max(height1, height2); - b2Assert(node->height == height); - - b2AABB aabb; - aabb.Combine(m_nodes[child1].aabb, m_nodes[child2].aabb); - - b2Assert(aabb.lowerBound == node->aabb.lowerBound); - b2Assert(aabb.upperBound == node->aabb.upperBound); - - ValidateMetrics(child1); - ValidateMetrics(child2); -} - -void b2DynamicTree::Validate() const -{ -#if defined(b2DEBUG) - ValidateStructure(m_root); - ValidateMetrics(m_root); - - int32 freeCount = 0; - int32 freeIndex = m_freeList; - while (freeIndex != b2_nullNode) - { - b2Assert(0 <= freeIndex && freeIndex < m_nodeCapacity); - freeIndex = m_nodes[freeIndex].next; - ++freeCount; - } - - b2Assert(GetHeight() == ComputeHeight()); - - b2Assert(m_nodeCount + freeCount == m_nodeCapacity); -#endif -} - -int32 b2DynamicTree::GetMaxBalance() const -{ - int32 maxBalance = 0; - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - const b2TreeNode* node = m_nodes + i; - if (node->height <= 1) - { - continue; - } - - b2Assert(node->IsLeaf() == false); - - int32 child1 = node->child1; - int32 child2 = node->child2; - int32 balance = b2Abs(m_nodes[child2].height - m_nodes[child1].height); - maxBalance = b2Max(maxBalance, balance); - } - - return maxBalance; -} - -void b2DynamicTree::RebuildBottomUp() -{ - int32* nodes = (int32*)b2Alloc(m_nodeCount * sizeof(int32)); - int32 count = 0; - - // Build array of leaves. Free the rest. - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - if (m_nodes[i].height < 0) - { - // free node in pool - continue; - } - - if (m_nodes[i].IsLeaf()) - { - m_nodes[i].parent = b2_nullNode; - nodes[count] = i; - ++count; - } - else - { - FreeNode(i); - } - } - - while (count > 1) - { - float32 minCost = b2_maxFloat; - int32 iMin = -1, jMin = -1; - for (int32 i = 0; i < count; ++i) - { - b2AABB aabbi = m_nodes[nodes[i]].aabb; - - for (int32 j = i + 1; j < count; ++j) - { - b2AABB aabbj = m_nodes[nodes[j]].aabb; - b2AABB b; - b.Combine(aabbi, aabbj); - float32 cost = b.GetPerimeter(); - if (cost < minCost) - { - iMin = i; - jMin = j; - minCost = cost; - } - } - } - - int32 index1 = nodes[iMin]; - int32 index2 = nodes[jMin]; - b2TreeNode* child1 = m_nodes + index1; - b2TreeNode* child2 = m_nodes + index2; - - int32 parentIndex = AllocateNode(); - b2TreeNode* parent = m_nodes + parentIndex; - parent->child1 = index1; - parent->child2 = index2; - parent->height = 1 + b2Max(child1->height, child2->height); - parent->aabb.Combine(child1->aabb, child2->aabb); - parent->parent = b2_nullNode; - - child1->parent = parentIndex; - child2->parent = parentIndex; - - nodes[jMin] = nodes[count-1]; - nodes[iMin] = parentIndex; - --count; - } - - m_root = nodes[0]; - b2Free(nodes); - - Validate(); -} - -void b2DynamicTree::ShiftOrigin(const b2Vec2& newOrigin) -{ - // Build array of leaves. Free the rest. - for (int32 i = 0; i < m_nodeCapacity; ++i) - { - m_nodes[i].aabb.lowerBound -= newOrigin; - m_nodes[i].aabb.upperBound -= newOrigin; - } -} diff --git a/libjin/3rdparty/Box2D/Collision/b2DynamicTree.h b/libjin/3rdparty/Box2D/Collision/b2DynamicTree.h deleted file mode 100644 index e52b44b..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2DynamicTree.h +++ /dev/null @@ -1,289 +0,0 @@ -/* -* Copyright (c) 2009 Erin Catto http://www.box2d.org -* -* 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 B2_DYNAMIC_TREE_H -#define B2_DYNAMIC_TREE_H - -#include "Box2D/Collision/b2Collision.h" -#include "Box2D/Common/b2GrowableStack.h" - -#define b2_nullNode (-1) - -/// A node in the dynamic tree. The client does not interact with this directly. -struct b2TreeNode -{ - bool IsLeaf() const - { - return child1 == b2_nullNode; - } - - /// Enlarged AABB - b2AABB aabb; - - void* userData; - - union - { - int32 parent; - int32 next; - }; - - int32 child1; - int32 child2; - - // leaf = 0, free node = -1 - int32 height; -}; - -/// A dynamic AABB tree broad-phase, inspired by Nathanael Presson's btDbvt. -/// A dynamic tree arranges data in a binary tree to accelerate -/// queries such as volume queries and ray casts. Leafs are proxies -/// with an AABB. In the tree we expand the proxy AABB by b2_fatAABBFactor -/// so that the proxy AABB is bigger than the client object. This allows the client -/// object to move by small amounts without triggering a tree update. -/// -/// Nodes are pooled and relocatable, so we use node indices rather than pointers. -class b2DynamicTree -{ -public: - /// Constructing the tree initializes the node pool. - b2DynamicTree(); - - /// Destroy the tree, freeing the node pool. - ~b2DynamicTree(); - - /// Create a proxy. Provide a tight fitting AABB and a userData pointer. - int32 CreateProxy(const b2AABB& aabb, void* userData); - - /// Destroy a proxy. This asserts if the id is invalid. - void DestroyProxy(int32 proxyId); - - /// Move a proxy with a swepted AABB. If the proxy has moved outside of its fattened AABB, - /// then the proxy is removed from the tree and re-inserted. Otherwise - /// the function returns immediately. - /// @return true if the proxy was re-inserted. - bool MoveProxy(int32 proxyId, const b2AABB& aabb1, const b2Vec2& displacement); - - /// Get proxy user data. - /// @return the proxy user data or 0 if the id is invalid. - void* GetUserData(int32 proxyId) const; - - /// Get the fat AABB for a proxy. - const b2AABB& GetFatAABB(int32 proxyId) const; - - /// Query an AABB for overlapping proxies. The callback class - /// is called for each proxy that overlaps the supplied AABB. - template <typename T> - void Query(T* callback, const b2AABB& aabb) const; - - /// Ray-cast against the proxies in the tree. This relies on the callback - /// to perform a exact ray-cast in the case were the proxy contains a shape. - /// The callback also performs the any collision filtering. This has performance - /// roughly equal to k * log(n), where k is the number of collisions and n is the - /// number of proxies in the tree. - /// @param input the ray-cast input data. The ray extends from p1 to p1 + maxFraction * (p2 - p1). - /// @param callback a callback class that is called for each proxy that is hit by the ray. - template <typename T> - void RayCast(T* callback, const b2RayCastInput& input) const; - - /// Validate this tree. For testing. - void Validate() const; - - /// Compute the height of the binary tree in O(N) time. Should not be - /// called often. - int32 GetHeight() const; - - /// Get the maximum balance of an node in the tree. The balance is the difference - /// in height of the two children of a node. - int32 GetMaxBalance() const; - - /// Get the ratio of the sum of the node areas to the root area. - float32 GetAreaRatio() const; - - /// Build an optimal tree. Very expensive. For testing. - void RebuildBottomUp(); - - /// Shift the world origin. Useful for large worlds. - /// The shift formula is: position -= newOrigin - /// @param newOrigin the new origin with respect to the old origin - void ShiftOrigin(const b2Vec2& newOrigin); - -private: - - int32 AllocateNode(); - void FreeNode(int32 node); - - void InsertLeaf(int32 node); - void RemoveLeaf(int32 node); - - int32 Balance(int32 index); - - int32 ComputeHeight() const; - int32 ComputeHeight(int32 nodeId) const; - - void ValidateStructure(int32 index) const; - void ValidateMetrics(int32 index) const; - - int32 m_root; - - b2TreeNode* m_nodes; - int32 m_nodeCount; - int32 m_nodeCapacity; - - int32 m_freeList; - - /// This is used to incrementally traverse the tree for re-balancing. - uint32 m_path; - - int32 m_insertionCount; -}; - -inline void* b2DynamicTree::GetUserData(int32 proxyId) const -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - return m_nodes[proxyId].userData; -} - -inline const b2AABB& b2DynamicTree::GetFatAABB(int32 proxyId) const -{ - b2Assert(0 <= proxyId && proxyId < m_nodeCapacity); - return m_nodes[proxyId].aabb; -} - -template <typename T> -inline void b2DynamicTree::Query(T* callback, const b2AABB& aabb) const -{ - b2GrowableStack<int32, 256> stack; - stack.Push(m_root); - - while (stack.GetCount() > 0) - { - int32 nodeId = stack.Pop(); - if (nodeId == b2_nullNode) - { - continue; - } - - const b2TreeNode* node = m_nodes + nodeId; - - if (b2TestOverlap(node->aabb, aabb)) - { - if (node->IsLeaf()) - { - bool proceed = callback->QueryCallback(nodeId); - if (proceed == false) - { - return; - } - } - else - { - stack.Push(node->child1); - stack.Push(node->child2); - } - } - } -} - -template <typename T> -inline void b2DynamicTree::RayCast(T* callback, const b2RayCastInput& input) const -{ - b2Vec2 p1 = input.p1; - b2Vec2 p2 = input.p2; - b2Vec2 r = p2 - p1; - b2Assert(r.LengthSquared() > 0.0f); - r.Normalize(); - - // v is perpendicular to the segment. - b2Vec2 v = b2Cross(1.0f, r); - b2Vec2 abs_v = b2Abs(v); - - // Separating axis for segment (Gino, p80). - // |dot(v, p1 - c)| > dot(|v|, h) - - float32 maxFraction = input.maxFraction; - - // Build a bounding box for the segment. - b2AABB segmentAABB; - { - b2Vec2 t = p1 + maxFraction * (p2 - p1); - segmentAABB.lowerBound = b2Min(p1, t); - segmentAABB.upperBound = b2Max(p1, t); - } - - b2GrowableStack<int32, 256> stack; - stack.Push(m_root); - - while (stack.GetCount() > 0) - { - int32 nodeId = stack.Pop(); - if (nodeId == b2_nullNode) - { - continue; - } - - const b2TreeNode* node = m_nodes + nodeId; - - if (b2TestOverlap(node->aabb, segmentAABB) == false) - { - continue; - } - - // Separating axis for segment (Gino, p80). - // |dot(v, p1 - c)| > dot(|v|, h) - b2Vec2 c = node->aabb.GetCenter(); - b2Vec2 h = node->aabb.GetExtents(); - float32 separation = b2Abs(b2Dot(v, p1 - c)) - b2Dot(abs_v, h); - if (separation > 0.0f) - { - continue; - } - - if (node->IsLeaf()) - { - b2RayCastInput subInput; - subInput.p1 = input.p1; - subInput.p2 = input.p2; - subInput.maxFraction = maxFraction; - - float32 value = callback->RayCastCallback(subInput, nodeId); - - if (value == 0.0f) - { - // The client has terminated the ray cast. - return; - } - - if (value > 0.0f) - { - // Update segment bounding box. - maxFraction = value; - b2Vec2 t = p1 + maxFraction * (p2 - p1); - segmentAABB.lowerBound = b2Min(p1, t); - segmentAABB.upperBound = b2Max(p1, t); - } - } - else - { - stack.Push(node->child1); - stack.Push(node->child2); - } - } -} - -#endif diff --git a/libjin/3rdparty/Box2D/Collision/b2TimeOfImpact.cpp b/libjin/3rdparty/Box2D/Collision/b2TimeOfImpact.cpp deleted file mode 100644 index 4bc1769..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2TimeOfImpact.cpp +++ /dev/null @@ -1,486 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/b2Distance.h" -#include "Box2D/Collision/b2TimeOfImpact.h" -#include "Box2D/Collision/Shapes/b2CircleShape.h" -#include "Box2D/Collision/Shapes/b2PolygonShape.h" -#include "Box2D/Common/b2Timer.h" - -#include <stdio.h> - -float32 b2_toiTime, b2_toiMaxTime; -int32 b2_toiCalls, b2_toiIters, b2_toiMaxIters; -int32 b2_toiRootIters, b2_toiMaxRootIters; - -// -struct b2SeparationFunction -{ - enum Type - { - e_points, - e_faceA, - e_faceB - }; - - // TODO_ERIN might not need to return the separation - - float32 Initialize(const b2SimplexCache* cache, - const b2DistanceProxy* proxyA, const b2Sweep& sweepA, - const b2DistanceProxy* proxyB, const b2Sweep& sweepB, - float32 t1) - { - m_proxyA = proxyA; - m_proxyB = proxyB; - int32 count = cache->count; - b2Assert(0 < count && count < 3); - - m_sweepA = sweepA; - m_sweepB = sweepB; - - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t1); - m_sweepB.GetTransform(&xfB, t1); - - if (count == 1) - { - m_type = e_points; - b2Vec2 localPointA = m_proxyA->GetVertex(cache->indexA[0]); - b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - m_axis = pointB - pointA; - float32 s = m_axis.Normalize(); - return s; - } - else if (cache->indexA[0] == cache->indexA[1]) - { - // Two points on B and one on A. - m_type = e_faceB; - b2Vec2 localPointB1 = proxyB->GetVertex(cache->indexB[0]); - b2Vec2 localPointB2 = proxyB->GetVertex(cache->indexB[1]); - - m_axis = b2Cross(localPointB2 - localPointB1, 1.0f); - m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfB.q, m_axis); - - m_localPoint = 0.5f * (localPointB1 + localPointB2); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 localPointA = proxyA->GetVertex(cache->indexA[0]); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 s = b2Dot(pointA - pointB, normal); - if (s < 0.0f) - { - m_axis = -m_axis; - s = -s; - } - return s; - } - else - { - // Two points on A and one or two points on B. - m_type = e_faceA; - b2Vec2 localPointA1 = m_proxyA->GetVertex(cache->indexA[0]); - b2Vec2 localPointA2 = m_proxyA->GetVertex(cache->indexA[1]); - - m_axis = b2Cross(localPointA2 - localPointA1, 1.0f); - m_axis.Normalize(); - b2Vec2 normal = b2Mul(xfA.q, m_axis); - - m_localPoint = 0.5f * (localPointA1 + localPointA2); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 localPointB = m_proxyB->GetVertex(cache->indexB[0]); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 s = b2Dot(pointB - pointA, normal); - if (s < 0.0f) - { - m_axis = -m_axis; - s = -s; - } - return s; - } - } - - // - float32 FindMinSeparation(int32* indexA, int32* indexB, float32 t) const - { - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t); - m_sweepB.GetTransform(&xfB, t); - - switch (m_type) - { - case e_points: - { - b2Vec2 axisA = b2MulT(xfA.q, m_axis); - b2Vec2 axisB = b2MulT(xfB.q, -m_axis); - - *indexA = m_proxyA->GetSupport(axisA); - *indexB = m_proxyB->GetSupport(axisB); - - b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); - b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); - - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, m_axis); - return separation; - } - - case e_faceA: - { - b2Vec2 normal = b2Mul(xfA.q, m_axis); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 axisB = b2MulT(xfB.q, -normal); - - *indexA = -1; - *indexB = m_proxyB->GetSupport(axisB); - - b2Vec2 localPointB = m_proxyB->GetVertex(*indexB); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, normal); - return separation; - } - - case e_faceB: - { - b2Vec2 normal = b2Mul(xfB.q, m_axis); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 axisA = b2MulT(xfA.q, -normal); - - *indexB = -1; - *indexA = m_proxyA->GetSupport(axisA); - - b2Vec2 localPointA = m_proxyA->GetVertex(*indexA); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 separation = b2Dot(pointA - pointB, normal); - return separation; - } - - default: - b2Assert(false); - *indexA = -1; - *indexB = -1; - return 0.0f; - } - } - - // - float32 Evaluate(int32 indexA, int32 indexB, float32 t) const - { - b2Transform xfA, xfB; - m_sweepA.GetTransform(&xfA, t); - m_sweepB.GetTransform(&xfB, t); - - switch (m_type) - { - case e_points: - { - b2Vec2 localPointA = m_proxyA->GetVertex(indexA); - b2Vec2 localPointB = m_proxyB->GetVertex(indexB); - - b2Vec2 pointA = b2Mul(xfA, localPointA); - b2Vec2 pointB = b2Mul(xfB, localPointB); - float32 separation = b2Dot(pointB - pointA, m_axis); - - return separation; - } - - case e_faceA: - { - b2Vec2 normal = b2Mul(xfA.q, m_axis); - b2Vec2 pointA = b2Mul(xfA, m_localPoint); - - b2Vec2 localPointB = m_proxyB->GetVertex(indexB); - b2Vec2 pointB = b2Mul(xfB, localPointB); - - float32 separation = b2Dot(pointB - pointA, normal); - return separation; - } - - case e_faceB: - { - b2Vec2 normal = b2Mul(xfB.q, m_axis); - b2Vec2 pointB = b2Mul(xfB, m_localPoint); - - b2Vec2 localPointA = m_proxyA->GetVertex(indexA); - b2Vec2 pointA = b2Mul(xfA, localPointA); - - float32 separation = b2Dot(pointA - pointB, normal); - return separation; - } - - default: - b2Assert(false); - return 0.0f; - } - } - - const b2DistanceProxy* m_proxyA; - const b2DistanceProxy* m_proxyB; - b2Sweep m_sweepA, m_sweepB; - Type m_type; - b2Vec2 m_localPoint; - b2Vec2 m_axis; -}; - -// CCD via the local separating axis method. This seeks progression -// by computing the largest time at which separation is maintained. -void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input) -{ - b2Timer timer; - - ++b2_toiCalls; - - output->state = b2TOIOutput::e_unknown; - output->t = input->tMax; - - const b2DistanceProxy* proxyA = &input->proxyA; - const b2DistanceProxy* proxyB = &input->proxyB; - - b2Sweep sweepA = input->sweepA; - b2Sweep sweepB = input->sweepB; - - // Large rotations can make the root finder fail, so we normalize the - // sweep angles. - sweepA.Normalize(); - sweepB.Normalize(); - - float32 tMax = input->tMax; - - float32 totalRadius = proxyA->m_radius + proxyB->m_radius; - float32 target = b2Max(b2_linearSlop, totalRadius - 3.0f * b2_linearSlop); - float32 tolerance = 0.25f * b2_linearSlop; - b2Assert(target > tolerance); - - float32 t1 = 0.0f; - const int32 k_maxIterations = 20; // TODO_ERIN b2Settings - int32 iter = 0; - - // Prepare input for distance query. - b2SimplexCache cache; - cache.count = 0; - b2DistanceInput distanceInput; - distanceInput.proxyA = input->proxyA; - distanceInput.proxyB = input->proxyB; - distanceInput.useRadii = false; - - // The outer loop progressively attempts to compute new separating axes. - // This loop terminates when an axis is repeated (no progress is made). - for(;;) - { - b2Transform xfA, xfB; - sweepA.GetTransform(&xfA, t1); - sweepB.GetTransform(&xfB, t1); - - // Get the distance between shapes. We can also use the results - // to get a separating axis. - distanceInput.transformA = xfA; - distanceInput.transformB = xfB; - b2DistanceOutput distanceOutput; - b2Distance(&distanceOutput, &cache, &distanceInput); - - // If the shapes are overlapped, we give up on continuous collision. - if (distanceOutput.distance <= 0.0f) - { - // Failure! - output->state = b2TOIOutput::e_overlapped; - output->t = 0.0f; - break; - } - - if (distanceOutput.distance < target + tolerance) - { - // Victory! - output->state = b2TOIOutput::e_touching; - output->t = t1; - break; - } - - // Initialize the separating axis. - b2SeparationFunction fcn; - fcn.Initialize(&cache, proxyA, sweepA, proxyB, sweepB, t1); -#if 0 - // Dump the curve seen by the root finder - { - const int32 N = 100; - float32 dx = 1.0f / N; - float32 xs[N+1]; - float32 fs[N+1]; - - float32 x = 0.0f; - - for (int32 i = 0; i <= N; ++i) - { - sweepA.GetTransform(&xfA, x); - sweepB.GetTransform(&xfB, x); - float32 f = fcn.Evaluate(xfA, xfB) - target; - - printf("%g %g\n", x, f); - - xs[i] = x; - fs[i] = f; - - x += dx; - } - } -#endif - - // Compute the TOI on the separating axis. We do this by successively - // resolving the deepest point. This loop is bounded by the number of vertices. - bool done = false; - float32 t2 = tMax; - int32 pushBackIter = 0; - for (;;) - { - // Find the deepest point at t2. Store the witness point indices. - int32 indexA, indexB; - float32 s2 = fcn.FindMinSeparation(&indexA, &indexB, t2); - - // Is the final configuration separated? - if (s2 > target + tolerance) - { - // Victory! - output->state = b2TOIOutput::e_separated; - output->t = tMax; - done = true; - break; - } - - // Has the separation reached tolerance? - if (s2 > target - tolerance) - { - // Advance the sweeps - t1 = t2; - break; - } - - // Compute the initial separation of the witness points. - float32 s1 = fcn.Evaluate(indexA, indexB, t1); - - // Check for initial overlap. This might happen if the root finder - // runs out of iterations. - if (s1 < target - tolerance) - { - output->state = b2TOIOutput::e_failed; - output->t = t1; - done = true; - break; - } - - // Check for touching - if (s1 <= target + tolerance) - { - // Victory! t1 should hold the TOI (could be 0.0). - output->state = b2TOIOutput::e_touching; - output->t = t1; - done = true; - break; - } - - // Compute 1D root of: f(x) - target = 0 - int32 rootIterCount = 0; - float32 a1 = t1, a2 = t2; - for (;;) - { - // Use a mix of the secant rule and bisection. - float32 t; - if (rootIterCount & 1) - { - // Secant rule to improve convergence. - t = a1 + (target - s1) * (a2 - a1) / (s2 - s1); - } - else - { - // Bisection to guarantee progress. - t = 0.5f * (a1 + a2); - } - - ++rootIterCount; - ++b2_toiRootIters; - - float32 s = fcn.Evaluate(indexA, indexB, t); - - if (b2Abs(s - target) < tolerance) - { - // t2 holds a tentative value for t1 - t2 = t; - break; - } - - // Ensure we continue to bracket the root. - if (s > target) - { - a1 = t; - s1 = s; - } - else - { - a2 = t; - s2 = s; - } - - if (rootIterCount == 50) - { - break; - } - } - - b2_toiMaxRootIters = b2Max(b2_toiMaxRootIters, rootIterCount); - - ++pushBackIter; - - if (pushBackIter == b2_maxPolygonVertices) - { - break; - } - } - - ++iter; - ++b2_toiIters; - - if (done) - { - break; - } - - if (iter == k_maxIterations) - { - // Root finder got stuck. Semi-victory. - output->state = b2TOIOutput::e_failed; - output->t = t1; - break; - } - } - - b2_toiMaxIters = b2Max(b2_toiMaxIters, iter); - - float32 time = timer.GetMilliseconds(); - b2_toiMaxTime = b2Max(b2_toiMaxTime, time); - b2_toiTime += time; -} diff --git a/libjin/3rdparty/Box2D/Collision/b2TimeOfImpact.h b/libjin/3rdparty/Box2D/Collision/b2TimeOfImpact.h deleted file mode 100644 index 3af2c32..0000000 --- a/libjin/3rdparty/Box2D/Collision/b2TimeOfImpact.h +++ /dev/null @@ -1,58 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_TIME_OF_IMPACT_H -#define B2_TIME_OF_IMPACT_H - -#include "Box2D/Common/b2Math.h" -#include "Box2D/Collision/b2Distance.h" - -/// Input parameters for b2TimeOfImpact -struct b2TOIInput -{ - b2DistanceProxy proxyA; - b2DistanceProxy proxyB; - b2Sweep sweepA; - b2Sweep sweepB; - float32 tMax; // defines sweep interval [0, tMax] -}; - -/// Output parameters for b2TimeOfImpact. -struct b2TOIOutput -{ - enum State - { - e_unknown, - e_failed, - e_overlapped, - e_touching, - e_separated - }; - - State state; - float32 t; -}; - -/// Compute the upper bound on time before two shapes penetrate. Time is represented as -/// a fraction between [0,tMax]. This uses a swept separating axis and may miss some intermediate, -/// non-tunneling collisions. If you change the time interval, you should call this function -/// again. -/// Note: use b2Distance to compute the contact point and normal at the time of impact. -void b2TimeOfImpact(b2TOIOutput* output, const b2TOIInput* input); - -#endif diff --git a/libjin/3rdparty/Box2D/Common/b2BlockAllocator.cpp b/libjin/3rdparty/Box2D/Common/b2BlockAllocator.cpp deleted file mode 100644 index b721de8..0000000 --- a/libjin/3rdparty/Box2D/Common/b2BlockAllocator.cpp +++ /dev/null @@ -1,215 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Common/b2BlockAllocator.h" -#include <limits.h> -#include <string.h> -#include <stddef.h> - -int32 b2BlockAllocator::s_blockSizes[b2_blockSizes] = -{ - 16, // 0 - 32, // 1 - 64, // 2 - 96, // 3 - 128, // 4 - 160, // 5 - 192, // 6 - 224, // 7 - 256, // 8 - 320, // 9 - 384, // 10 - 448, // 11 - 512, // 12 - 640, // 13 -}; -uint8 b2BlockAllocator::s_blockSizeLookup[b2_maxBlockSize + 1]; -bool b2BlockAllocator::s_blockSizeLookupInitialized; - -struct b2Chunk -{ - int32 blockSize; - b2Block* blocks; -}; - -struct b2Block -{ - b2Block* next; -}; - -b2BlockAllocator::b2BlockAllocator() -{ - b2Assert(b2_blockSizes < UCHAR_MAX); - - m_chunkSpace = b2_chunkArrayIncrement; - m_chunkCount = 0; - m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); - - memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); - memset(m_freeLists, 0, sizeof(m_freeLists)); - - if (s_blockSizeLookupInitialized == false) - { - int32 j = 0; - for (int32 i = 1; i <= b2_maxBlockSize; ++i) - { - b2Assert(j < b2_blockSizes); - if (i <= s_blockSizes[j]) - { - s_blockSizeLookup[i] = (uint8)j; - } - else - { - ++j; - s_blockSizeLookup[i] = (uint8)j; - } - } - - s_blockSizeLookupInitialized = true; - } -} - -b2BlockAllocator::~b2BlockAllocator() -{ - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Free(m_chunks[i].blocks); - } - - b2Free(m_chunks); -} - -void* b2BlockAllocator::Allocate(int32 size) -{ - if (size == 0) - return nullptr; - - b2Assert(0 < size); - - if (size > b2_maxBlockSize) - { - return b2Alloc(size); - } - - int32 index = s_blockSizeLookup[size]; - b2Assert(0 <= index && index < b2_blockSizes); - - if (m_freeLists[index]) - { - b2Block* block = m_freeLists[index]; - m_freeLists[index] = block->next; - return block; - } - else - { - if (m_chunkCount == m_chunkSpace) - { - b2Chunk* oldChunks = m_chunks; - m_chunkSpace += b2_chunkArrayIncrement; - m_chunks = (b2Chunk*)b2Alloc(m_chunkSpace * sizeof(b2Chunk)); - memcpy(m_chunks, oldChunks, m_chunkCount * sizeof(b2Chunk)); - memset(m_chunks + m_chunkCount, 0, b2_chunkArrayIncrement * sizeof(b2Chunk)); - b2Free(oldChunks); - } - - b2Chunk* chunk = m_chunks + m_chunkCount; - chunk->blocks = (b2Block*)b2Alloc(b2_chunkSize); -#if defined(_DEBUG) - memset(chunk->blocks, 0xcd, b2_chunkSize); -#endif - int32 blockSize = s_blockSizes[index]; - chunk->blockSize = blockSize; - int32 blockCount = b2_chunkSize / blockSize; - b2Assert(blockCount * blockSize <= b2_chunkSize); - for (int32 i = 0; i < blockCount - 1; ++i) - { - b2Block* block = (b2Block*)((int8*)chunk->blocks + blockSize * i); - b2Block* next = (b2Block*)((int8*)chunk->blocks + blockSize * (i + 1)); - block->next = next; - } - b2Block* last = (b2Block*)((int8*)chunk->blocks + blockSize * (blockCount - 1)); - last->next = nullptr; - - m_freeLists[index] = chunk->blocks->next; - ++m_chunkCount; - - return chunk->blocks; - } -} - -void b2BlockAllocator::Free(void* p, int32 size) -{ - if (size == 0) - { - return; - } - - b2Assert(0 < size); - - if (size > b2_maxBlockSize) - { - b2Free(p); - return; - } - - int32 index = s_blockSizeLookup[size]; - b2Assert(0 <= index && index < b2_blockSizes); - -#ifdef _DEBUG - // Verify the memory address and size is valid. - int32 blockSize = s_blockSizes[index]; - bool found = false; - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Chunk* chunk = m_chunks + i; - if (chunk->blockSize != blockSize) - { - b2Assert( (int8*)p + blockSize <= (int8*)chunk->blocks || - (int8*)chunk->blocks + b2_chunkSize <= (int8*)p); - } - else - { - if ((int8*)chunk->blocks <= (int8*)p && (int8*)p + blockSize <= (int8*)chunk->blocks + b2_chunkSize) - { - found = true; - } - } - } - - b2Assert(found); - - memset(p, 0xfd, blockSize); -#endif - - b2Block* block = (b2Block*)p; - block->next = m_freeLists[index]; - m_freeLists[index] = block; -} - -void b2BlockAllocator::Clear() -{ - for (int32 i = 0; i < m_chunkCount; ++i) - { - b2Free(m_chunks[i].blocks); - } - - m_chunkCount = 0; - memset(m_chunks, 0, m_chunkSpace * sizeof(b2Chunk)); - - memset(m_freeLists, 0, sizeof(m_freeLists)); -} diff --git a/libjin/3rdparty/Box2D/Common/b2BlockAllocator.h b/libjin/3rdparty/Box2D/Common/b2BlockAllocator.h deleted file mode 100644 index 8dfa254..0000000 --- a/libjin/3rdparty/Box2D/Common/b2BlockAllocator.h +++ /dev/null @@ -1,62 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_BLOCK_ALLOCATOR_H -#define B2_BLOCK_ALLOCATOR_H - -#include "Box2D/Common/b2Settings.h" - -const int32 b2_chunkSize = 16 * 1024; -const int32 b2_maxBlockSize = 640; -const int32 b2_blockSizes = 14; -const int32 b2_chunkArrayIncrement = 128; - -struct b2Block; -struct b2Chunk; - -/// This is a small object allocator used for allocating small -/// objects that persist for more than one time step. -/// See: http://www.codeproject.com/useritems/Small_Block_Allocator.asp -class b2BlockAllocator -{ -public: - b2BlockAllocator(); - ~b2BlockAllocator(); - - /// Allocate memory. This will use b2Alloc if the size is larger than b2_maxBlockSize. - void* Allocate(int32 size); - - /// Free memory. This will use b2Free if the size is larger than b2_maxBlockSize. - void Free(void* p, int32 size); - - void Clear(); - -private: - - b2Chunk* m_chunks; - int32 m_chunkCount; - int32 m_chunkSpace; - - b2Block* m_freeLists[b2_blockSizes]; - - static int32 s_blockSizes[b2_blockSizes]; - static uint8 s_blockSizeLookup[b2_maxBlockSize + 1]; - static bool s_blockSizeLookupInitialized; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Common/b2Draw.cpp b/libjin/3rdparty/Box2D/Common/b2Draw.cpp deleted file mode 100644 index 4d412cd..0000000 --- a/libjin/3rdparty/Box2D/Common/b2Draw.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* 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 "Box2D/Common/b2Draw.h" - -b2Draw::b2Draw() -{ - m_drawFlags = 0; -} - -void b2Draw::SetFlags(uint32 flags) -{ - m_drawFlags = flags; -} - -uint32 b2Draw::GetFlags() const -{ - return m_drawFlags; -} - -void b2Draw::AppendFlags(uint32 flags) -{ - m_drawFlags |= flags; -} - -void b2Draw::ClearFlags(uint32 flags) -{ - m_drawFlags &= ~flags; -} diff --git a/libjin/3rdparty/Box2D/Common/b2Draw.h b/libjin/3rdparty/Box2D/Common/b2Draw.h deleted file mode 100644 index ef81826..0000000 --- a/libjin/3rdparty/Box2D/Common/b2Draw.h +++ /dev/null @@ -1,97 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* 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 B2_DRAW_H -#define B2_DRAW_H - -#include "Box2D/Common/b2Math.h" - -/// Color for debug drawing. Each value has the range [0,1]. -struct b2Color -{ - b2Color() {} - b2Color(float32 rIn, float32 gIn, float32 bIn, float32 aIn = 1.0f) - { - r = rIn; g = gIn; b = bIn; a = aIn; - } - - void Set(float32 rIn, float32 gIn, float32 bIn, float32 aIn = 1.0f) - { - r = rIn; g = gIn; b = bIn; a = aIn; - } - - float32 r, g, b, a; -}; - -/// Implement and register this class with a b2World to provide debug drawing of physics -/// entities in your game. -class b2Draw -{ -public: - b2Draw(); - - virtual ~b2Draw() {} - - enum - { - e_shapeBit = 0x0001, ///< draw shapes - e_jointBit = 0x0002, ///< draw joint connections - e_aabbBit = 0x0004, ///< draw axis aligned bounding boxes - e_pairBit = 0x0008, ///< draw broad-phase pairs - e_centerOfMassBit = 0x0010 ///< draw center of mass frame - }; - - /// Set the drawing flags. - void SetFlags(uint32 flags); - - /// Get the drawing flags. - uint32 GetFlags() const; - - /// Append flags to the current flags. - void AppendFlags(uint32 flags); - - /// Clear flags from the current flags. - void ClearFlags(uint32 flags); - - /// Draw a closed polygon provided in CCW order. - virtual void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - - /// Draw a solid closed polygon provided in CCW order. - virtual void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color) = 0; - - /// Draw a circle. - virtual void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color) = 0; - - /// Draw a solid circle. - virtual void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color) = 0; - - /// Draw a line segment. - virtual void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color) = 0; - - /// Draw a transform. Choose your own length scale. - /// @param xf a transform. - virtual void DrawTransform(const b2Transform& xf) = 0; - - /// Draw a point. - virtual void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color) = 0; - -protected: - uint32 m_drawFlags; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Common/b2GrowableStack.h b/libjin/3rdparty/Box2D/Common/b2GrowableStack.h deleted file mode 100644 index 8d239c7..0000000 --- a/libjin/3rdparty/Box2D/Common/b2GrowableStack.h +++ /dev/null @@ -1,85 +0,0 @@ -/* -* Copyright (c) 2010 Erin Catto http://www.box2d.org -* -* 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 B2_GROWABLE_STACK_H -#define B2_GROWABLE_STACK_H -#include "Box2D/Common/b2Settings.h" -#include <string.h> - -/// This is a growable LIFO stack with an initial capacity of N. -/// If the stack size exceeds the initial capacity, the heap is used -/// to increase the size of the stack. -template <typename T, int32 N> -class b2GrowableStack -{ -public: - b2GrowableStack() - { - m_stack = m_array; - m_count = 0; - m_capacity = N; - } - - ~b2GrowableStack() - { - if (m_stack != m_array) - { - b2Free(m_stack); - m_stack = nullptr; - } - } - - void Push(const T& element) - { - if (m_count == m_capacity) - { - T* old = m_stack; - m_capacity *= 2; - m_stack = (T*)b2Alloc(m_capacity * sizeof(T)); - memcpy(m_stack, old, m_count * sizeof(T)); - if (old != m_array) - { - b2Free(old); - } - } - - m_stack[m_count] = element; - ++m_count; - } - - T Pop() - { - b2Assert(m_count > 0); - --m_count; - return m_stack[m_count]; - } - - int32 GetCount() - { - return m_count; - } - -private: - T* m_stack; - T m_array[N]; - int32 m_count; - int32 m_capacity; -}; - - -#endif diff --git a/libjin/3rdparty/Box2D/Common/b2Math.cpp b/libjin/3rdparty/Box2D/Common/b2Math.cpp deleted file mode 100644 index f9f5f39..0000000 --- a/libjin/3rdparty/Box2D/Common/b2Math.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* -* Copyright (c) 2007-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Common/b2Math.h" - -const b2Vec2 b2Vec2_zero(0.0f, 0.0f); - -/// Solve A * x = b, where b is a column vector. This is more efficient -/// than computing the inverse in one-shot cases. -b2Vec3 b2Mat33::Solve33(const b2Vec3& b) const -{ - float32 det = b2Dot(ex, b2Cross(ey, ez)); - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec3 x; - x.x = det * b2Dot(b, b2Cross(ey, ez)); - x.y = det * b2Dot(ex, b2Cross(b, ez)); - x.z = det * b2Dot(ex, b2Cross(ey, b)); - return x; -} - -/// Solve A * x = b, where b is a column vector. This is more efficient -/// than computing the inverse in one-shot cases. -b2Vec2 b2Mat33::Solve22(const b2Vec2& b) const -{ - float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; - float32 det = a11 * a22 - a12 * a21; - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec2 x; - x.x = det * (a22 * b.x - a12 * b.y); - x.y = det * (a11 * b.y - a21 * b.x); - return x; -} - -/// -void b2Mat33::GetInverse22(b2Mat33* M) const -{ - float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; - float32 det = a * d - b * c; - if (det != 0.0f) - { - det = 1.0f / det; - } - - M->ex.x = det * d; M->ey.x = -det * b; M->ex.z = 0.0f; - M->ex.y = -det * c; M->ey.y = det * a; M->ey.z = 0.0f; - M->ez.x = 0.0f; M->ez.y = 0.0f; M->ez.z = 0.0f; -} - -/// Returns the zero matrix if singular. -void b2Mat33::GetSymInverse33(b2Mat33* M) const -{ - float32 det = b2Dot(ex, b2Cross(ey, ez)); - if (det != 0.0f) - { - det = 1.0f / det; - } - - float32 a11 = ex.x, a12 = ey.x, a13 = ez.x; - float32 a22 = ey.y, a23 = ez.y; - float32 a33 = ez.z; - - M->ex.x = det * (a22 * a33 - a23 * a23); - M->ex.y = det * (a13 * a23 - a12 * a33); - M->ex.z = det * (a12 * a23 - a13 * a22); - - M->ey.x = M->ex.y; - M->ey.y = det * (a11 * a33 - a13 * a13); - M->ey.z = det * (a13 * a12 - a11 * a23); - - M->ez.x = M->ex.z; - M->ez.y = M->ey.z; - M->ez.z = det * (a11 * a22 - a12 * a12); -} diff --git a/libjin/3rdparty/Box2D/Common/b2Math.h b/libjin/3rdparty/Box2D/Common/b2Math.h deleted file mode 100644 index 7a816e5..0000000 --- a/libjin/3rdparty/Box2D/Common/b2Math.h +++ /dev/null @@ -1,707 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_MATH_H -#define B2_MATH_H - -#include "Box2D/Common/b2Settings.h" -#include <math.h> - -/// This function is used to ensure that a floating point number is not a NaN or infinity. -inline bool b2IsValid(float32 x) -{ - return isfinite(x); -} - -#define b2Sqrt(x) sqrtf(x) -#define b2Atan2(y, x) atan2f(y, x) - -/// A 2D column vector. -struct b2Vec2 -{ - /// Default constructor does nothing (for performance). - b2Vec2() {} - - /// Construct using coordinates. - b2Vec2(float32 xIn, float32 yIn) : x(xIn), y(yIn) {} - - /// Set this vector to all zeros. - void SetZero() { x = 0.0f; y = 0.0f; } - - /// Set this vector to some specified coordinates. - void Set(float32 x_, float32 y_) { x = x_; y = y_; } - - /// Negate this vector. - b2Vec2 operator -() const { b2Vec2 v; v.Set(-x, -y); return v; } - - /// Read from and indexed element. - float32 operator () (int32 i) const - { - return (&x)[i]; - } - - /// Write to an indexed element. - float32& operator () (int32 i) - { - return (&x)[i]; - } - - /// Add a vector to this vector. - void operator += (const b2Vec2& v) - { - x += v.x; y += v.y; - } - - /// Subtract a vector from this vector. - void operator -= (const b2Vec2& v) - { - x -= v.x; y -= v.y; - } - - /// Multiply this vector by a scalar. - void operator *= (float32 a) - { - x *= a; y *= a; - } - - /// Get the length of this vector (the norm). - float32 Length() const - { - return b2Sqrt(x * x + y * y); - } - - /// Get the length squared. For performance, use this instead of - /// b2Vec2::Length (if possible). - float32 LengthSquared() const - { - return x * x + y * y; - } - - /// Convert this vector into a unit vector. Returns the length. - float32 Normalize() - { - float32 length = Length(); - if (length < b2_epsilon) - { - return 0.0f; - } - float32 invLength = 1.0f / length; - x *= invLength; - y *= invLength; - - return length; - } - - /// Does this vector contain finite coordinates? - bool IsValid() const - { - return b2IsValid(x) && b2IsValid(y); - } - - /// Get the skew vector such that dot(skew_vec, other) == cross(vec, other) - b2Vec2 Skew() const - { - return b2Vec2(-y, x); - } - - float32 x, y; -}; - -/// A 2D column vector with 3 elements. -struct b2Vec3 -{ - /// Default constructor does nothing (for performance). - b2Vec3() {} - - /// Construct using coordinates. - b2Vec3(float32 xIn, float32 yIn, float32 zIn) : x(xIn), y(yIn), z(zIn) {} - - /// Set this vector to all zeros. - void SetZero() { x = 0.0f; y = 0.0f; z = 0.0f; } - - /// Set this vector to some specified coordinates. - void Set(float32 x_, float32 y_, float32 z_) { x = x_; y = y_; z = z_; } - - /// Negate this vector. - b2Vec3 operator -() const { b2Vec3 v; v.Set(-x, -y, -z); return v; } - - /// Add a vector to this vector. - void operator += (const b2Vec3& v) - { - x += v.x; y += v.y; z += v.z; - } - - /// Subtract a vector from this vector. - void operator -= (const b2Vec3& v) - { - x -= v.x; y -= v.y; z -= v.z; - } - - /// Multiply this vector by a scalar. - void operator *= (float32 s) - { - x *= s; y *= s; z *= s; - } - - float32 x, y, z; -}; - -/// A 2-by-2 matrix. Stored in column-major order. -struct b2Mat22 -{ - /// The default constructor does nothing (for performance). - b2Mat22() {} - - /// Construct this matrix using columns. - b2Mat22(const b2Vec2& c1, const b2Vec2& c2) - { - ex = c1; - ey = c2; - } - - /// Construct this matrix using scalars. - b2Mat22(float32 a11, float32 a12, float32 a21, float32 a22) - { - ex.x = a11; ex.y = a21; - ey.x = a12; ey.y = a22; - } - - /// Initialize this matrix using columns. - void Set(const b2Vec2& c1, const b2Vec2& c2) - { - ex = c1; - ey = c2; - } - - /// Set this to the identity matrix. - void SetIdentity() - { - ex.x = 1.0f; ey.x = 0.0f; - ex.y = 0.0f; ey.y = 1.0f; - } - - /// Set this matrix to all zeros. - void SetZero() - { - ex.x = 0.0f; ey.x = 0.0f; - ex.y = 0.0f; ey.y = 0.0f; - } - - b2Mat22 GetInverse() const - { - float32 a = ex.x, b = ey.x, c = ex.y, d = ey.y; - b2Mat22 B; - float32 det = a * d - b * c; - if (det != 0.0f) - { - det = 1.0f / det; - } - B.ex.x = det * d; B.ey.x = -det * b; - B.ex.y = -det * c; B.ey.y = det * a; - return B; - } - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. - b2Vec2 Solve(const b2Vec2& b) const - { - float32 a11 = ex.x, a12 = ey.x, a21 = ex.y, a22 = ey.y; - float32 det = a11 * a22 - a12 * a21; - if (det != 0.0f) - { - det = 1.0f / det; - } - b2Vec2 x; - x.x = det * (a22 * b.x - a12 * b.y); - x.y = det * (a11 * b.y - a21 * b.x); - return x; - } - - b2Vec2 ex, ey; -}; - -/// A 3-by-3 matrix. Stored in column-major order. -struct b2Mat33 -{ - /// The default constructor does nothing (for performance). - b2Mat33() {} - - /// Construct this matrix using columns. - b2Mat33(const b2Vec3& c1, const b2Vec3& c2, const b2Vec3& c3) - { - ex = c1; - ey = c2; - ez = c3; - } - - /// Set this matrix to all zeros. - void SetZero() - { - ex.SetZero(); - ey.SetZero(); - ez.SetZero(); - } - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. - b2Vec3 Solve33(const b2Vec3& b) const; - - /// Solve A * x = b, where b is a column vector. This is more efficient - /// than computing the inverse in one-shot cases. Solve only the upper - /// 2-by-2 matrix equation. - b2Vec2 Solve22(const b2Vec2& b) const; - - /// Get the inverse of this matrix as a 2-by-2. - /// Returns the zero matrix if singular. - void GetInverse22(b2Mat33* M) const; - - /// Get the symmetric inverse of this matrix as a 3-by-3. - /// Returns the zero matrix if singular. - void GetSymInverse33(b2Mat33* M) const; - - b2Vec3 ex, ey, ez; -}; - -/// Rotation -struct b2Rot -{ - b2Rot() {} - - /// Initialize from an angle in radians - explicit b2Rot(float32 angle) - { - /// TODO_ERIN optimize - s = sinf(angle); - c = cosf(angle); - } - - /// Set using an angle in radians. - void Set(float32 angle) - { - /// TODO_ERIN optimize - s = sinf(angle); - c = cosf(angle); - } - - /// Set to the identity rotation - void SetIdentity() - { - s = 0.0f; - c = 1.0f; - } - - /// Get the angle in radians - float32 GetAngle() const - { - return b2Atan2(s, c); - } - - /// Get the x-axis - b2Vec2 GetXAxis() const - { - return b2Vec2(c, s); - } - - /// Get the u-axis - b2Vec2 GetYAxis() const - { - return b2Vec2(-s, c); - } - - /// Sine and cosine - float32 s, c; -}; - -/// A transform contains translation and rotation. It is used to represent -/// the position and orientation of rigid frames. -struct b2Transform -{ - /// The default constructor does nothing. - b2Transform() {} - - /// Initialize using a position vector and a rotation. - b2Transform(const b2Vec2& position, const b2Rot& rotation) : p(position), q(rotation) {} - - /// Set this to the identity transform. - void SetIdentity() - { - p.SetZero(); - q.SetIdentity(); - } - - /// Set this based on the position and angle. - void Set(const b2Vec2& position, float32 angle) - { - p = position; - q.Set(angle); - } - - b2Vec2 p; - b2Rot q; -}; - -/// This describes the motion of a body/shape for TOI computation. -/// Shapes are defined with respect to the body origin, which may -/// no coincide with the center of mass. However, to support dynamics -/// we must interpolate the center of mass position. -struct b2Sweep -{ - /// Get the interpolated transform at a specific time. - /// @param beta is a factor in [0,1], where 0 indicates alpha0. - void GetTransform(b2Transform* xfb, float32 beta) const; - - /// Advance the sweep forward, yielding a new initial state. - /// @param alpha the new initial time. - void Advance(float32 alpha); - - /// Normalize the angles. - void Normalize(); - - b2Vec2 localCenter; ///< local center of mass position - b2Vec2 c0, c; ///< center world positions - float32 a0, a; ///< world angles - - /// Fraction of the current time step in the range [0,1] - /// c0 and a0 are the positions at alpha0. - float32 alpha0; -}; - -/// Useful constant -extern const b2Vec2 b2Vec2_zero; - -/// Perform the dot product on two vectors. -inline float32 b2Dot(const b2Vec2& a, const b2Vec2& b) -{ - return a.x * b.x + a.y * b.y; -} - -/// Perform the cross product on two vectors. In 2D this produces a scalar. -inline float32 b2Cross(const b2Vec2& a, const b2Vec2& b) -{ - return a.x * b.y - a.y * b.x; -} - -/// Perform the cross product on a vector and a scalar. In 2D this produces -/// a vector. -inline b2Vec2 b2Cross(const b2Vec2& a, float32 s) -{ - return b2Vec2(s * a.y, -s * a.x); -} - -/// Perform the cross product on a scalar and a vector. In 2D this produces -/// a vector. -inline b2Vec2 b2Cross(float32 s, const b2Vec2& a) -{ - return b2Vec2(-s * a.y, s * a.x); -} - -/// Multiply a matrix times a vector. If a rotation matrix is provided, -/// then this transforms the vector from one frame to another. -inline b2Vec2 b2Mul(const b2Mat22& A, const b2Vec2& v) -{ - return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); -} - -/// Multiply a matrix transpose times a vector. If a rotation matrix is provided, -/// then this transforms the vector from one frame to another (inverse transform). -inline b2Vec2 b2MulT(const b2Mat22& A, const b2Vec2& v) -{ - return b2Vec2(b2Dot(v, A.ex), b2Dot(v, A.ey)); -} - -/// Add two vectors component-wise. -inline b2Vec2 operator + (const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(a.x + b.x, a.y + b.y); -} - -/// Subtract two vectors component-wise. -inline b2Vec2 operator - (const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(a.x - b.x, a.y - b.y); -} - -inline b2Vec2 operator * (float32 s, const b2Vec2& a) -{ - return b2Vec2(s * a.x, s * a.y); -} - -inline bool operator == (const b2Vec2& a, const b2Vec2& b) -{ - return a.x == b.x && a.y == b.y; -} - -inline bool operator != (const b2Vec2& a, const b2Vec2& b) -{ - return a.x != b.x || a.y != b.y; -} - -inline float32 b2Distance(const b2Vec2& a, const b2Vec2& b) -{ - b2Vec2 c = a - b; - return c.Length(); -} - -inline float32 b2DistanceSquared(const b2Vec2& a, const b2Vec2& b) -{ - b2Vec2 c = a - b; - return b2Dot(c, c); -} - -inline b2Vec3 operator * (float32 s, const b2Vec3& a) -{ - return b2Vec3(s * a.x, s * a.y, s * a.z); -} - -/// Add two vectors component-wise. -inline b2Vec3 operator + (const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.x + b.x, a.y + b.y, a.z + b.z); -} - -/// Subtract two vectors component-wise. -inline b2Vec3 operator - (const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.x - b.x, a.y - b.y, a.z - b.z); -} - -/// Perform the dot product on two vectors. -inline float32 b2Dot(const b2Vec3& a, const b2Vec3& b) -{ - return a.x * b.x + a.y * b.y + a.z * b.z; -} - -/// Perform the cross product on two vectors. -inline b2Vec3 b2Cross(const b2Vec3& a, const b2Vec3& b) -{ - return b2Vec3(a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x); -} - -inline b2Mat22 operator + (const b2Mat22& A, const b2Mat22& B) -{ - return b2Mat22(A.ex + B.ex, A.ey + B.ey); -} - -// A * B -inline b2Mat22 b2Mul(const b2Mat22& A, const b2Mat22& B) -{ - return b2Mat22(b2Mul(A, B.ex), b2Mul(A, B.ey)); -} - -// A^T * B -inline b2Mat22 b2MulT(const b2Mat22& A, const b2Mat22& B) -{ - b2Vec2 c1(b2Dot(A.ex, B.ex), b2Dot(A.ey, B.ex)); - b2Vec2 c2(b2Dot(A.ex, B.ey), b2Dot(A.ey, B.ey)); - return b2Mat22(c1, c2); -} - -/// Multiply a matrix times a vector. -inline b2Vec3 b2Mul(const b2Mat33& A, const b2Vec3& v) -{ - return v.x * A.ex + v.y * A.ey + v.z * A.ez; -} - -/// Multiply a matrix times a vector. -inline b2Vec2 b2Mul22(const b2Mat33& A, const b2Vec2& v) -{ - return b2Vec2(A.ex.x * v.x + A.ey.x * v.y, A.ex.y * v.x + A.ey.y * v.y); -} - -/// Multiply two rotations: q * r -inline b2Rot b2Mul(const b2Rot& q, const b2Rot& r) -{ - // [qc -qs] * [rc -rs] = [qc*rc-qs*rs -qc*rs-qs*rc] - // [qs qc] [rs rc] [qs*rc+qc*rs -qs*rs+qc*rc] - // s = qs * rc + qc * rs - // c = qc * rc - qs * rs - b2Rot qr; - qr.s = q.s * r.c + q.c * r.s; - qr.c = q.c * r.c - q.s * r.s; - return qr; -} - -/// Transpose multiply two rotations: qT * r -inline b2Rot b2MulT(const b2Rot& q, const b2Rot& r) -{ - // [ qc qs] * [rc -rs] = [qc*rc+qs*rs -qc*rs+qs*rc] - // [-qs qc] [rs rc] [-qs*rc+qc*rs qs*rs+qc*rc] - // s = qc * rs - qs * rc - // c = qc * rc + qs * rs - b2Rot qr; - qr.s = q.c * r.s - q.s * r.c; - qr.c = q.c * r.c + q.s * r.s; - return qr; -} - -/// Rotate a vector -inline b2Vec2 b2Mul(const b2Rot& q, const b2Vec2& v) -{ - return b2Vec2(q.c * v.x - q.s * v.y, q.s * v.x + q.c * v.y); -} - -/// Inverse rotate a vector -inline b2Vec2 b2MulT(const b2Rot& q, const b2Vec2& v) -{ - return b2Vec2(q.c * v.x + q.s * v.y, -q.s * v.x + q.c * v.y); -} - -inline b2Vec2 b2Mul(const b2Transform& T, const b2Vec2& v) -{ - float32 x = (T.q.c * v.x - T.q.s * v.y) + T.p.x; - float32 y = (T.q.s * v.x + T.q.c * v.y) + T.p.y; - - return b2Vec2(x, y); -} - -inline b2Vec2 b2MulT(const b2Transform& T, const b2Vec2& v) -{ - float32 px = v.x - T.p.x; - float32 py = v.y - T.p.y; - float32 x = (T.q.c * px + T.q.s * py); - float32 y = (-T.q.s * px + T.q.c * py); - - return b2Vec2(x, y); -} - -// v2 = A.q.Rot(B.q.Rot(v1) + B.p) + A.p -// = (A.q * B.q).Rot(v1) + A.q.Rot(B.p) + A.p -inline b2Transform b2Mul(const b2Transform& A, const b2Transform& B) -{ - b2Transform C; - C.q = b2Mul(A.q, B.q); - C.p = b2Mul(A.q, B.p) + A.p; - return C; -} - -// v2 = A.q' * (B.q * v1 + B.p - A.p) -// = A.q' * B.q * v1 + A.q' * (B.p - A.p) -inline b2Transform b2MulT(const b2Transform& A, const b2Transform& B) -{ - b2Transform C; - C.q = b2MulT(A.q, B.q); - C.p = b2MulT(A.q, B.p - A.p); - return C; -} - -template <typename T> -inline T b2Abs(T a) -{ - return a > T(0) ? a : -a; -} - -inline b2Vec2 b2Abs(const b2Vec2& a) -{ - return b2Vec2(b2Abs(a.x), b2Abs(a.y)); -} - -inline b2Mat22 b2Abs(const b2Mat22& A) -{ - return b2Mat22(b2Abs(A.ex), b2Abs(A.ey)); -} - -template <typename T> -inline T b2Min(T a, T b) -{ - return a < b ? a : b; -} - -inline b2Vec2 b2Min(const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(b2Min(a.x, b.x), b2Min(a.y, b.y)); -} - -template <typename T> -inline T b2Max(T a, T b) -{ - return a > b ? a : b; -} - -inline b2Vec2 b2Max(const b2Vec2& a, const b2Vec2& b) -{ - return b2Vec2(b2Max(a.x, b.x), b2Max(a.y, b.y)); -} - -template <typename T> -inline T b2Clamp(T a, T low, T high) -{ - return b2Max(low, b2Min(a, high)); -} - -inline b2Vec2 b2Clamp(const b2Vec2& a, const b2Vec2& low, const b2Vec2& high) -{ - return b2Max(low, b2Min(a, high)); -} - -template<typename T> inline void b2Swap(T& a, T& b) -{ - T tmp = a; - a = b; - b = tmp; -} - -/// "Next Largest Power of 2 -/// Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm -/// that recursively "folds" the upper bits into the lower bits. This process yields a bit vector with -/// the same most significant 1 as x, but all 1's below it. Adding 1 to that value yields the next -/// largest power of 2. For a 32-bit value:" -inline uint32 b2NextPowerOfTwo(uint32 x) -{ - x |= (x >> 1); - x |= (x >> 2); - x |= (x >> 4); - x |= (x >> 8); - x |= (x >> 16); - return x + 1; -} - -inline bool b2IsPowerOfTwo(uint32 x) -{ - bool result = x > 0 && (x & (x - 1)) == 0; - return result; -} - -inline void b2Sweep::GetTransform(b2Transform* xf, float32 beta) const -{ - xf->p = (1.0f - beta) * c0 + beta * c; - float32 angle = (1.0f - beta) * a0 + beta * a; - xf->q.Set(angle); - - // Shift to origin - xf->p -= b2Mul(xf->q, localCenter); -} - -inline void b2Sweep::Advance(float32 alpha) -{ - b2Assert(alpha0 < 1.0f); - float32 beta = (alpha - alpha0) / (1.0f - alpha0); - c0 += beta * (c - c0); - a0 += beta * (a - a0); - alpha0 = alpha; -} - -/// Normalize an angle in radians to be between -pi and pi -inline void b2Sweep::Normalize() -{ - float32 twoPi = 2.0f * b2_pi; - float32 d = twoPi * floorf(a0 / twoPi); - a0 -= d; - a -= d; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Common/b2Settings.cpp b/libjin/3rdparty/Box2D/Common/b2Settings.cpp deleted file mode 100644 index a59cefe..0000000 --- a/libjin/3rdparty/Box2D/Common/b2Settings.cpp +++ /dev/null @@ -1,44 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Common/b2Settings.h" -#include <stdio.h> -#include <stdarg.h> -#include <stdlib.h> - -b2Version b2_version = {2, 3, 2}; - -// Memory allocators. Modify these to use your own allocator. -void* b2Alloc(int32 size) -{ - return malloc(size); -} - -void b2Free(void* mem) -{ - free(mem); -} - -// You can modify this to use your logging facility. -void b2Log(const char* string, ...) -{ - va_list args; - va_start(args, string); - vprintf(string, args); - va_end(args); -} diff --git a/libjin/3rdparty/Box2D/Common/b2Settings.h b/libjin/3rdparty/Box2D/Common/b2Settings.h deleted file mode 100644 index c69280f..0000000 --- a/libjin/3rdparty/Box2D/Common/b2Settings.h +++ /dev/null @@ -1,155 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_SETTINGS_H -#define B2_SETTINGS_H - -#include <stddef.h> -#include <assert.h> -#include <float.h> - -#if !defined(NDEBUG) - #define b2DEBUG -#endif - -#define B2_NOT_USED(x) ((void)(x)) -#define b2Assert(A) assert(A) - -typedef signed char int8; -typedef signed short int16; -typedef signed int int32; -typedef unsigned char uint8; -typedef unsigned short uint16; -typedef unsigned int uint32; -typedef float float32; -typedef double float64; - -#define b2_maxFloat FLT_MAX -#define b2_epsilon FLT_EPSILON -#define b2_pi 3.14159265359f - -/// @file -/// Global tuning constants based on meters-kilograms-seconds (MKS) units. -/// - -// Collision - -/// The maximum number of contact points between two convex shapes. Do -/// not change this value. -#define b2_maxManifoldPoints 2 - -/// The maximum number of vertices on a convex polygon. You cannot increase -/// this too much because b2BlockAllocator has a maximum object size. -#define b2_maxPolygonVertices 8 - -/// This is used to fatten AABBs in the dynamic tree. This allows proxies -/// to move by a small amount without triggering a tree adjustment. -/// This is in meters. -#define b2_aabbExtension 0.1f - -/// This is used to fatten AABBs in the dynamic tree. This is used to predict -/// the future position based on the current displacement. -/// This is a dimensionless multiplier. -#define b2_aabbMultiplier 2.0f - -/// A small length used as a collision and constraint tolerance. Usually it is -/// chosen to be numerically significant, but visually insignificant. -#define b2_linearSlop 0.005f - -/// A small angle used as a collision and constraint tolerance. Usually it is -/// chosen to be numerically significant, but visually insignificant. -#define b2_angularSlop (2.0f / 180.0f * b2_pi) - -/// The radius of the polygon/edge shape skin. This should not be modified. Making -/// this smaller means polygons will have an insufficient buffer for continuous collision. -/// Making it larger may create artifacts for vertex collision. -#define b2_polygonRadius (2.0f * b2_linearSlop) - -/// Maximum number of sub-steps per contact in continuous physics simulation. -#define b2_maxSubSteps 8 - - -// Dynamics - -/// Maximum number of contacts to be handled to solve a TOI impact. -#define b2_maxTOIContacts 32 - -/// A velocity threshold for elastic collisions. Any collision with a relative linear -/// velocity below this threshold will be treated as inelastic. -#define b2_velocityThreshold 1.0f - -/// The maximum linear position correction used when solving constraints. This helps to -/// prevent overshoot. -#define b2_maxLinearCorrection 0.2f - -/// The maximum angular position correction used when solving constraints. This helps to -/// prevent overshoot. -#define b2_maxAngularCorrection (8.0f / 180.0f * b2_pi) - -/// The maximum linear velocity of a body. This limit is very large and is used -/// to prevent numerical problems. You shouldn't need to adjust this. -#define b2_maxTranslation 2.0f -#define b2_maxTranslationSquared (b2_maxTranslation * b2_maxTranslation) - -/// The maximum angular velocity of a body. This limit is very large and is used -/// to prevent numerical problems. You shouldn't need to adjust this. -#define b2_maxRotation (0.5f * b2_pi) -#define b2_maxRotationSquared (b2_maxRotation * b2_maxRotation) - -/// This scale factor controls how fast overlap is resolved. Ideally this would be 1 so -/// that overlap is removed in one time step. However using values close to 1 often lead -/// to overshoot. -#define b2_baumgarte 0.2f -#define b2_toiBaugarte 0.75f - - -// Sleep - -/// The time that a body must be still before it will go to sleep. -#define b2_timeToSleep 0.5f - -/// A body cannot sleep if its linear velocity is above this tolerance. -#define b2_linearSleepTolerance 0.01f - -/// A body cannot sleep if its angular velocity is above this tolerance. -#define b2_angularSleepTolerance (2.0f / 180.0f * b2_pi) - -// Memory Allocation - -/// Implement this function to use your own memory allocator. -void* b2Alloc(int32 size); - -/// If you implement b2Alloc, you should also implement this function. -void b2Free(void* mem); - -/// Logging function. -void b2Log(const char* string, ...); - -/// Version numbering scheme. -/// See http://en.wikipedia.org/wiki/Software_versioning -struct b2Version -{ - int32 major; ///< significant changes - int32 minor; ///< incremental changes - int32 revision; ///< bug fixes -}; - -/// Current version. -extern b2Version b2_version; - -#endif diff --git a/libjin/3rdparty/Box2D/Common/b2StackAllocator.cpp b/libjin/3rdparty/Box2D/Common/b2StackAllocator.cpp deleted file mode 100644 index 1347f3c..0000000 --- a/libjin/3rdparty/Box2D/Common/b2StackAllocator.cpp +++ /dev/null @@ -1,83 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Common/b2StackAllocator.h" -#include "Box2D/Common/b2Math.h" - -b2StackAllocator::b2StackAllocator() -{ - m_index = 0; - m_allocation = 0; - m_maxAllocation = 0; - m_entryCount = 0; -} - -b2StackAllocator::~b2StackAllocator() -{ - b2Assert(m_index == 0); - b2Assert(m_entryCount == 0); -} - -void* b2StackAllocator::Allocate(int32 size) -{ - b2Assert(m_entryCount < b2_maxStackEntries); - - b2StackEntry* entry = m_entries + m_entryCount; - entry->size = size; - if (m_index + size > b2_stackSize) - { - entry->data = (char*)b2Alloc(size); - entry->usedMalloc = true; - } - else - { - entry->data = m_data + m_index; - entry->usedMalloc = false; - m_index += size; - } - - m_allocation += size; - m_maxAllocation = b2Max(m_maxAllocation, m_allocation); - ++m_entryCount; - - return entry->data; -} - -void b2StackAllocator::Free(void* p) -{ - b2Assert(m_entryCount > 0); - b2StackEntry* entry = m_entries + m_entryCount - 1; - b2Assert(p == entry->data); - if (entry->usedMalloc) - { - b2Free(p); - } - else - { - m_index -= entry->size; - } - m_allocation -= entry->size; - --m_entryCount; - - p = nullptr; -} - -int32 b2StackAllocator::GetMaxAllocation() const -{ - return m_maxAllocation; -} diff --git a/libjin/3rdparty/Box2D/Common/b2StackAllocator.h b/libjin/3rdparty/Box2D/Common/b2StackAllocator.h deleted file mode 100644 index 27340e8..0000000 --- a/libjin/3rdparty/Box2D/Common/b2StackAllocator.h +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_STACK_ALLOCATOR_H -#define B2_STACK_ALLOCATOR_H - -#include "Box2D/Common/b2Settings.h" - -const int32 b2_stackSize = 100 * 1024; // 100k -const int32 b2_maxStackEntries = 32; - -struct b2StackEntry -{ - char* data; - int32 size; - bool usedMalloc; -}; - -// This is a stack allocator used for fast per step allocations. -// You must nest allocate/free pairs. The code will assert -// if you try to interleave multiple allocate/free pairs. -class b2StackAllocator -{ -public: - b2StackAllocator(); - ~b2StackAllocator(); - - void* Allocate(int32 size); - void Free(void* p); - - int32 GetMaxAllocation() const; - -private: - - char m_data[b2_stackSize]; - int32 m_index; - - int32 m_allocation; - int32 m_maxAllocation; - - b2StackEntry m_entries[b2_maxStackEntries]; - int32 m_entryCount; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Common/b2Timer.cpp b/libjin/3rdparty/Box2D/Common/b2Timer.cpp deleted file mode 100644 index 38f3dea..0000000 --- a/libjin/3rdparty/Box2D/Common/b2Timer.cpp +++ /dev/null @@ -1,121 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* 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 "Box2D/Common/b2Timer.h" - -#if defined(_WIN32) - -float64 b2Timer::s_invFrequency = 0.0f; - -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif - -#include <windows.h> - -b2Timer::b2Timer() -{ - LARGE_INTEGER largeInteger; - - if (s_invFrequency == 0.0f) - { - QueryPerformanceFrequency(&largeInteger); - s_invFrequency = float64(largeInteger.QuadPart); - if (s_invFrequency > 0.0f) - { - s_invFrequency = 1000.0f / s_invFrequency; - } - } - - QueryPerformanceCounter(&largeInteger); - m_start = float64(largeInteger.QuadPart); -} - -void b2Timer::Reset() -{ - LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); - m_start = float64(largeInteger.QuadPart); -} - -float32 b2Timer::GetMilliseconds() const -{ - LARGE_INTEGER largeInteger; - QueryPerformanceCounter(&largeInteger); - float64 count = float64(largeInteger.QuadPart); - float32 ms = float32(s_invFrequency * (count - m_start)); - return ms; -} - -#elif defined(__linux__) || defined (__APPLE__) - -#include <sys/time.h> - -b2Timer::b2Timer() -{ - Reset(); -} - -void b2Timer::Reset() -{ - timeval t; - gettimeofday(&t, 0); - m_start_sec = t.tv_sec; - m_start_usec = t.tv_usec; -} - -float32 b2Timer::GetMilliseconds() const -{ - timeval t; - gettimeofday(&t, 0); - time_t start_sec = m_start_sec; - suseconds_t start_usec = m_start_usec; - - // http://www.gnu.org/software/libc/manual/html_node/Elapsed-Time.html - if (t.tv_usec < start_usec) - { - int nsec = (start_usec - t.tv_usec) / 1000000 + 1; - start_usec -= 1000000 * nsec; - start_sec += nsec; - } - - if (t.tv_usec - start_usec > 1000000) - { - int nsec = (t.tv_usec - start_usec) / 1000000; - start_usec += 1000000 * nsec; - start_sec -= nsec; - } - return 1000.0f * (t.tv_sec - start_sec) + 0.001f * (t.tv_usec - start_usec); -} - -#else - -b2Timer::b2Timer() -{ -} - -void b2Timer::Reset() -{ -} - -float32 b2Timer::GetMilliseconds() const -{ - return 0.0f; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Common/b2Timer.h b/libjin/3rdparty/Box2D/Common/b2Timer.h deleted file mode 100644 index a25e907..0000000 --- a/libjin/3rdparty/Box2D/Common/b2Timer.h +++ /dev/null @@ -1,50 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* 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 B2_TIMER_H -#define B2_TIMER_H - -#include "Box2D/Common/b2Settings.h" - -/// Timer for profiling. This has platform specific code and may -/// not work on every platform. -class b2Timer -{ -public: - - /// Constructor - b2Timer(); - - /// Reset the timer. - void Reset(); - - /// Get the time since construction or the last reset. - float32 GetMilliseconds() const; - -private: - -#if defined(_WIN32) - float64 m_start; - static float64 s_invFrequency; -#elif defined(__linux__) || defined (__APPLE__) - unsigned long long m_start_sec; - unsigned long long m_start_usec; -#endif -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp deleted file mode 100644 index c930255..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Collision/Shapes/b2ChainShape.h" -#include "Box2D/Collision/Shapes/b2EdgeShape.h" - -#include <new> - -b2Contact* b2ChainAndCircleContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2ChainAndCircleContact)); - return new (mem) b2ChainAndCircleContact(fixtureA, indexA, fixtureB, indexB); -} - -void b2ChainAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2ChainAndCircleContact*)contact)->~b2ChainAndCircleContact(); - allocator->Free(contact, sizeof(b2ChainAndCircleContact)); -} - -b2ChainAndCircleContact::b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) -: b2Contact(fixtureA, indexA, fixtureB, indexB) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2ChainAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); - b2EdgeShape edge; - chain->GetChildEdge(&edge, m_indexA); - b2CollideEdgeAndCircle( manifold, &edge, xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h deleted file mode 100644 index 1421f90..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_CHAIN_AND_CIRCLE_CONTACT_H -#define B2_CHAIN_AND_CIRCLE_CONTACT_H - -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -class b2BlockAllocator; - -class b2ChainAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2ChainAndCircleContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - ~b2ChainAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp deleted file mode 100644 index 78431d5..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.cpp +++ /dev/null @@ -1,53 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Collision/Shapes/b2ChainShape.h" -#include "Box2D/Collision/Shapes/b2EdgeShape.h" - -#include <new> - -b2Contact* b2ChainAndPolygonContact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2ChainAndPolygonContact)); - return new (mem) b2ChainAndPolygonContact(fixtureA, indexA, fixtureB, indexB); -} - -void b2ChainAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2ChainAndPolygonContact*)contact)->~b2ChainAndPolygonContact(); - allocator->Free(contact, sizeof(b2ChainAndPolygonContact)); -} - -b2ChainAndPolygonContact::b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB) -: b2Contact(fixtureA, indexA, fixtureB, indexB) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_chain); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2ChainAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2ChainShape* chain = (b2ChainShape*)m_fixtureA->GetShape(); - b2EdgeShape edge; - chain->GetChildEdge(&edge, m_indexA); - b2CollideEdgeAndPolygon( manifold, &edge, xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h deleted file mode 100644 index 89b8dd3..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_CHAIN_AND_POLYGON_CONTACT_H -#define B2_CHAIN_AND_POLYGON_CONTACT_H - -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -class b2BlockAllocator; - -class b2ChainAndPolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2ChainAndPolygonContact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - ~b2ChainAndPolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2CircleContact.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2CircleContact.cpp deleted file mode 100644 index 3b6c50b..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2CircleContact.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2CircleContact.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2WorldCallbacks.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Collision/b2TimeOfImpact.h" - -#include <new> - -b2Contact* b2CircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2CircleContact)); - return new (mem) b2CircleContact(fixtureA, fixtureB); -} - -void b2CircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2CircleContact*)contact)->~b2CircleContact(); - allocator->Free(contact, sizeof(b2CircleContact)); -} - -b2CircleContact::b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_circle); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2CircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideCircles(manifold, - (b2CircleShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2CircleContact.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2CircleContact.h deleted file mode 100644 index d40c7fb..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2CircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_CIRCLE_CONTACT_H -#define B2_CIRCLE_CONTACT_H - -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -class b2BlockAllocator; - -class b2CircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2CircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2CircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2Contact.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2Contact.cpp deleted file mode 100644 index 41b0f78..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2Contact.cpp +++ /dev/null @@ -1,247 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2Contact.h" -#include "Box2D/Dynamics/Contacts/b2CircleContact.h" -#include "Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h" -#include "Box2D/Dynamics/Contacts/b2PolygonContact.h" -#include "Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h" -#include "Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h" -#include "Box2D/Dynamics/Contacts/b2ChainAndCircleContact.h" -#include "Box2D/Dynamics/Contacts/b2ChainAndPolygonContact.h" -#include "Box2D/Dynamics/Contacts/b2ContactSolver.h" - -#include "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/b2TimeOfImpact.h" -#include "Box2D/Collision/Shapes/b2Shape.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2World.h" - -b2ContactRegister b2Contact::s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; -bool b2Contact::s_initialized = false; - -void b2Contact::InitializeRegisters() -{ - AddType(b2CircleContact::Create, b2CircleContact::Destroy, b2Shape::e_circle, b2Shape::e_circle); - AddType(b2PolygonAndCircleContact::Create, b2PolygonAndCircleContact::Destroy, b2Shape::e_polygon, b2Shape::e_circle); - AddType(b2PolygonContact::Create, b2PolygonContact::Destroy, b2Shape::e_polygon, b2Shape::e_polygon); - AddType(b2EdgeAndCircleContact::Create, b2EdgeAndCircleContact::Destroy, b2Shape::e_edge, b2Shape::e_circle); - AddType(b2EdgeAndPolygonContact::Create, b2EdgeAndPolygonContact::Destroy, b2Shape::e_edge, b2Shape::e_polygon); - AddType(b2ChainAndCircleContact::Create, b2ChainAndCircleContact::Destroy, b2Shape::e_chain, b2Shape::e_circle); - AddType(b2ChainAndPolygonContact::Create, b2ChainAndPolygonContact::Destroy, b2Shape::e_chain, b2Shape::e_polygon); -} - -void b2Contact::AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destoryFcn, - b2Shape::Type type1, b2Shape::Type type2) -{ - b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); - b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); - - s_registers[type1][type2].createFcn = createFcn; - s_registers[type1][type2].destroyFcn = destoryFcn; - s_registers[type1][type2].primary = true; - - if (type1 != type2) - { - s_registers[type2][type1].createFcn = createFcn; - s_registers[type2][type1].destroyFcn = destoryFcn; - s_registers[type2][type1].primary = false; - } -} - -b2Contact* b2Contact::Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator) -{ - if (s_initialized == false) - { - InitializeRegisters(); - s_initialized = true; - } - - b2Shape::Type type1 = fixtureA->GetType(); - b2Shape::Type type2 = fixtureB->GetType(); - - b2Assert(0 <= type1 && type1 < b2Shape::e_typeCount); - b2Assert(0 <= type2 && type2 < b2Shape::e_typeCount); - - b2ContactCreateFcn* createFcn = s_registers[type1][type2].createFcn; - if (createFcn) - { - if (s_registers[type1][type2].primary) - { - return createFcn(fixtureA, indexA, fixtureB, indexB, allocator); - } - else - { - return createFcn(fixtureB, indexB, fixtureA, indexA, allocator); - } - } - else - { - return nullptr; - } -} - -void b2Contact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - b2Assert(s_initialized == true); - - b2Fixture* fixtureA = contact->m_fixtureA; - b2Fixture* fixtureB = contact->m_fixtureB; - - if (contact->m_manifold.pointCount > 0 && - fixtureA->IsSensor() == false && - fixtureB->IsSensor() == false) - { - fixtureA->GetBody()->SetAwake(true); - fixtureB->GetBody()->SetAwake(true); - } - - b2Shape::Type typeA = fixtureA->GetType(); - b2Shape::Type typeB = fixtureB->GetType(); - - b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); - b2Assert(0 <= typeA && typeB < b2Shape::e_typeCount); - - b2ContactDestroyFcn* destroyFcn = s_registers[typeA][typeB].destroyFcn; - destroyFcn(contact, allocator); -} - -b2Contact::b2Contact(b2Fixture* fA, int32 indexA, b2Fixture* fB, int32 indexB) -{ - m_flags = e_enabledFlag; - - m_fixtureA = fA; - m_fixtureB = fB; - - m_indexA = indexA; - m_indexB = indexB; - - m_manifold.pointCount = 0; - - m_prev = nullptr; - m_next = nullptr; - - m_nodeA.contact = nullptr; - m_nodeA.prev = nullptr; - m_nodeA.next = nullptr; - m_nodeA.other = nullptr; - - m_nodeB.contact = nullptr; - m_nodeB.prev = nullptr; - m_nodeB.next = nullptr; - m_nodeB.other = nullptr; - - m_toiCount = 0; - - m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); - m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); - - m_tangentSpeed = 0.0f; -} - -// Update the contact manifold and touching status. -// Note: do not assume the fixture AABBs are overlapping or are valid. -void b2Contact::Update(b2ContactListener* listener) -{ - b2Manifold oldManifold = m_manifold; - - // Re-enable this contact. - m_flags |= e_enabledFlag; - - bool touching = false; - bool wasTouching = (m_flags & e_touchingFlag) == e_touchingFlag; - - bool sensorA = m_fixtureA->IsSensor(); - bool sensorB = m_fixtureB->IsSensor(); - bool sensor = sensorA || sensorB; - - b2Body* bodyA = m_fixtureA->GetBody(); - b2Body* bodyB = m_fixtureB->GetBody(); - const b2Transform& xfA = bodyA->GetTransform(); - const b2Transform& xfB = bodyB->GetTransform(); - - // Is this contact a sensor? - if (sensor) - { - const b2Shape* shapeA = m_fixtureA->GetShape(); - const b2Shape* shapeB = m_fixtureB->GetShape(); - touching = b2TestOverlap(shapeA, m_indexA, shapeB, m_indexB, xfA, xfB); - - // Sensors don't generate manifolds. - m_manifold.pointCount = 0; - } - else - { - Evaluate(&m_manifold, xfA, xfB); - touching = m_manifold.pointCount > 0; - - // Match old contact ids to new contact ids and copy the - // stored impulses to warm start the solver. - for (int32 i = 0; i < m_manifold.pointCount; ++i) - { - b2ManifoldPoint* mp2 = m_manifold.points + i; - mp2->normalImpulse = 0.0f; - mp2->tangentImpulse = 0.0f; - b2ContactID id2 = mp2->id; - - for (int32 j = 0; j < oldManifold.pointCount; ++j) - { - b2ManifoldPoint* mp1 = oldManifold.points + j; - - if (mp1->id.key == id2.key) - { - mp2->normalImpulse = mp1->normalImpulse; - mp2->tangentImpulse = mp1->tangentImpulse; - break; - } - } - } - - if (touching != wasTouching) - { - bodyA->SetAwake(true); - bodyB->SetAwake(true); - } - } - - if (touching) - { - m_flags |= e_touchingFlag; - } - else - { - m_flags &= ~e_touchingFlag; - } - - if (wasTouching == false && touching == true && listener) - { - listener->BeginContact(this); - } - - if (wasTouching == true && touching == false && listener) - { - listener->EndContact(this); - } - - if (sensor == false && touching && listener) - { - listener->PreSolve(this, &oldManifold); - } -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2Contact.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2Contact.h deleted file mode 100644 index df23d3c..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2Contact.h +++ /dev/null @@ -1,349 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_CONTACT_H -#define B2_CONTACT_H - -#include "Box2D/Common/b2Math.h" -#include "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/Shapes/b2Shape.h" -#include "Box2D/Dynamics/b2Fixture.h" - -class b2Body; -class b2Contact; -class b2Fixture; -class b2World; -class b2BlockAllocator; -class b2StackAllocator; -class b2ContactListener; - -/// Friction mixing law. The idea is to allow either fixture to drive the friction to zero. -/// For example, anything slides on ice. -inline float32 b2MixFriction(float32 friction1, float32 friction2) -{ - return b2Sqrt(friction1 * friction2); -} - -/// Restitution mixing law. The idea is allow for anything to bounce off an inelastic surface. -/// For example, a superball bounces on anything. -inline float32 b2MixRestitution(float32 restitution1, float32 restitution2) -{ - return restitution1 > restitution2 ? restitution1 : restitution2; -} - -typedef b2Contact* b2ContactCreateFcn( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, - b2BlockAllocator* allocator); -typedef void b2ContactDestroyFcn(b2Contact* contact, b2BlockAllocator* allocator); - -struct b2ContactRegister -{ - b2ContactCreateFcn* createFcn; - b2ContactDestroyFcn* destroyFcn; - bool primary; -}; - -/// A contact edge is used to connect bodies and contacts together -/// in a contact graph where each body is a node and each contact -/// is an edge. A contact edge belongs to a doubly linked list -/// maintained in each attached body. Each contact has two contact -/// nodes, one for each attached body. -struct b2ContactEdge -{ - b2Body* other; ///< provides quick access to the other body attached. - b2Contact* contact; ///< the contact - b2ContactEdge* prev; ///< the previous contact edge in the body's contact list - b2ContactEdge* next; ///< the next contact edge in the body's contact list -}; - -/// The class manages contact between two shapes. A contact exists for each overlapping -/// AABB in the broad-phase (except if filtered). Therefore a contact object may exist -/// that has no contact points. -class b2Contact -{ -public: - - /// Get the contact manifold. Do not modify the manifold unless you understand the - /// internals of Box2D. - b2Manifold* GetManifold(); - const b2Manifold* GetManifold() const; - - /// Get the world manifold. - void GetWorldManifold(b2WorldManifold* worldManifold) const; - - /// Is this contact touching? - bool IsTouching() const; - - /// Enable/disable this contact. This can be used inside the pre-solve - /// contact listener. The contact is only disabled for the current - /// time step (or sub-step in continuous collisions). - void SetEnabled(bool flag); - - /// Has this contact been disabled? - bool IsEnabled() const; - - /// Get the next contact in the world's contact list. - b2Contact* GetNext(); - const b2Contact* GetNext() const; - - /// Get fixture A in this contact. - b2Fixture* GetFixtureA(); - const b2Fixture* GetFixtureA() const; - - /// Get the child primitive index for fixture A. - int32 GetChildIndexA() const; - - /// Get fixture B in this contact. - b2Fixture* GetFixtureB(); - const b2Fixture* GetFixtureB() const; - - /// Get the child primitive index for fixture B. - int32 GetChildIndexB() const; - - /// Override the default friction mixture. You can call this in b2ContactListener::PreSolve. - /// This value persists until set or reset. - void SetFriction(float32 friction); - - /// Get the friction. - float32 GetFriction() const; - - /// Reset the friction mixture to the default value. - void ResetFriction(); - - /// Override the default restitution mixture. You can call this in b2ContactListener::PreSolve. - /// The value persists until you set or reset. - void SetRestitution(float32 restitution); - - /// Get the restitution. - float32 GetRestitution() const; - - /// Reset the restitution to the default value. - void ResetRestitution(); - - /// Set the desired tangent speed for a conveyor belt behavior. In meters per second. - void SetTangentSpeed(float32 speed); - - /// Get the desired tangent speed. In meters per second. - float32 GetTangentSpeed() const; - - /// Evaluate this contact with your own manifold and transforms. - virtual void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) = 0; - -protected: - friend class b2ContactManager; - friend class b2World; - friend class b2ContactSolver; - friend class b2Body; - friend class b2Fixture; - - // Flags stored in m_flags - enum - { - // Used when crawling contact graph when forming islands. - e_islandFlag = 0x0001, - - // Set when the shapes are touching. - e_touchingFlag = 0x0002, - - // This contact can be disabled (by user) - e_enabledFlag = 0x0004, - - // This contact needs filtering because a fixture filter was changed. - e_filterFlag = 0x0008, - - // This bullet contact had a TOI event - e_bulletHitFlag = 0x0010, - - // This contact has a valid TOI in m_toi - e_toiFlag = 0x0020 - }; - - /// Flag this contact for filtering. Filtering will occur the next time step. - void FlagForFiltering(); - - static void AddType(b2ContactCreateFcn* createFcn, b2ContactDestroyFcn* destroyFcn, - b2Shape::Type typeA, b2Shape::Type typeB); - static void InitializeRegisters(); - static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2Shape::Type typeA, b2Shape::Type typeB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2Contact() : m_fixtureA(nullptr), m_fixtureB(nullptr) {} - b2Contact(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB); - virtual ~b2Contact() {} - - void Update(b2ContactListener* listener); - - static b2ContactRegister s_registers[b2Shape::e_typeCount][b2Shape::e_typeCount]; - static bool s_initialized; - - uint32 m_flags; - - // World pool and list pointers. - b2Contact* m_prev; - b2Contact* m_next; - - // Nodes for connecting bodies. - b2ContactEdge m_nodeA; - b2ContactEdge m_nodeB; - - b2Fixture* m_fixtureA; - b2Fixture* m_fixtureB; - - int32 m_indexA; - int32 m_indexB; - - b2Manifold m_manifold; - - int32 m_toiCount; - float32 m_toi; - - float32 m_friction; - float32 m_restitution; - - float32 m_tangentSpeed; -}; - -inline b2Manifold* b2Contact::GetManifold() -{ - return &m_manifold; -} - -inline const b2Manifold* b2Contact::GetManifold() const -{ - return &m_manifold; -} - -inline void b2Contact::GetWorldManifold(b2WorldManifold* worldManifold) const -{ - const b2Body* bodyA = m_fixtureA->GetBody(); - const b2Body* bodyB = m_fixtureB->GetBody(); - const b2Shape* shapeA = m_fixtureA->GetShape(); - const b2Shape* shapeB = m_fixtureB->GetShape(); - - worldManifold->Initialize(&m_manifold, bodyA->GetTransform(), shapeA->m_radius, bodyB->GetTransform(), shapeB->m_radius); -} - -inline void b2Contact::SetEnabled(bool flag) -{ - if (flag) - { - m_flags |= e_enabledFlag; - } - else - { - m_flags &= ~e_enabledFlag; - } -} - -inline bool b2Contact::IsEnabled() const -{ - return (m_flags & e_enabledFlag) == e_enabledFlag; -} - -inline bool b2Contact::IsTouching() const -{ - return (m_flags & e_touchingFlag) == e_touchingFlag; -} - -inline b2Contact* b2Contact::GetNext() -{ - return m_next; -} - -inline const b2Contact* b2Contact::GetNext() const -{ - return m_next; -} - -inline b2Fixture* b2Contact::GetFixtureA() -{ - return m_fixtureA; -} - -inline const b2Fixture* b2Contact::GetFixtureA() const -{ - return m_fixtureA; -} - -inline b2Fixture* b2Contact::GetFixtureB() -{ - return m_fixtureB; -} - -inline int32 b2Contact::GetChildIndexA() const -{ - return m_indexA; -} - -inline const b2Fixture* b2Contact::GetFixtureB() const -{ - return m_fixtureB; -} - -inline int32 b2Contact::GetChildIndexB() const -{ - return m_indexB; -} - -inline void b2Contact::FlagForFiltering() -{ - m_flags |= e_filterFlag; -} - -inline void b2Contact::SetFriction(float32 friction) -{ - m_friction = friction; -} - -inline float32 b2Contact::GetFriction() const -{ - return m_friction; -} - -inline void b2Contact::ResetFriction() -{ - m_friction = b2MixFriction(m_fixtureA->m_friction, m_fixtureB->m_friction); -} - -inline void b2Contact::SetRestitution(float32 restitution) -{ - m_restitution = restitution; -} - -inline float32 b2Contact::GetRestitution() const -{ - return m_restitution; -} - -inline void b2Contact::ResetRestitution() -{ - m_restitution = b2MixRestitution(m_fixtureA->m_restitution, m_fixtureB->m_restitution); -} - -inline void b2Contact::SetTangentSpeed(float32 speed) -{ - m_tangentSpeed = speed; -} - -inline float32 b2Contact::GetTangentSpeed() const -{ - return m_tangentSpeed; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ContactSolver.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ContactSolver.cpp deleted file mode 100644 index 147968c..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ContactSolver.cpp +++ /dev/null @@ -1,838 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2ContactSolver.h" - -#include "Box2D/Dynamics/Contacts/b2Contact.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2World.h" -#include "Box2D/Common/b2StackAllocator.h" - -// Solver debugging is normally disabled because the block solver sometimes has to deal with a poorly conditioned effective mass matrix. -#define B2_DEBUG_SOLVER 0 - -bool g_blockSolve = true; - -struct b2ContactPositionConstraint -{ - b2Vec2 localPoints[b2_maxManifoldPoints]; - b2Vec2 localNormal; - b2Vec2 localPoint; - int32 indexA; - int32 indexB; - float32 invMassA, invMassB; - b2Vec2 localCenterA, localCenterB; - float32 invIA, invIB; - b2Manifold::Type type; - float32 radiusA, radiusB; - int32 pointCount; -}; - -b2ContactSolver::b2ContactSolver(b2ContactSolverDef* def) -{ - m_step = def->step; - m_allocator = def->allocator; - m_count = def->count; - m_positionConstraints = (b2ContactPositionConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactPositionConstraint)); - m_velocityConstraints = (b2ContactVelocityConstraint*)m_allocator->Allocate(m_count * sizeof(b2ContactVelocityConstraint)); - m_positions = def->positions; - m_velocities = def->velocities; - m_contacts = def->contacts; - - // Initialize position independent portions of the constraints. - for (int32 i = 0; i < m_count; ++i) - { - b2Contact* contact = m_contacts[i]; - - b2Fixture* fixtureA = contact->m_fixtureA; - b2Fixture* fixtureB = contact->m_fixtureB; - b2Shape* shapeA = fixtureA->GetShape(); - b2Shape* shapeB = fixtureB->GetShape(); - float32 radiusA = shapeA->m_radius; - float32 radiusB = shapeB->m_radius; - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - b2Manifold* manifold = contact->GetManifold(); - - int32 pointCount = manifold->pointCount; - b2Assert(pointCount > 0); - - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - vc->friction = contact->m_friction; - vc->restitution = contact->m_restitution; - vc->tangentSpeed = contact->m_tangentSpeed; - vc->indexA = bodyA->m_islandIndex; - vc->indexB = bodyB->m_islandIndex; - vc->invMassA = bodyA->m_invMass; - vc->invMassB = bodyB->m_invMass; - vc->invIA = bodyA->m_invI; - vc->invIB = bodyB->m_invI; - vc->contactIndex = i; - vc->pointCount = pointCount; - vc->K.SetZero(); - vc->normalMass.SetZero(); - - b2ContactPositionConstraint* pc = m_positionConstraints + i; - pc->indexA = bodyA->m_islandIndex; - pc->indexB = bodyB->m_islandIndex; - pc->invMassA = bodyA->m_invMass; - pc->invMassB = bodyB->m_invMass; - pc->localCenterA = bodyA->m_sweep.localCenter; - pc->localCenterB = bodyB->m_sweep.localCenter; - pc->invIA = bodyA->m_invI; - pc->invIB = bodyB->m_invI; - pc->localNormal = manifold->localNormal; - pc->localPoint = manifold->localPoint; - pc->pointCount = pointCount; - pc->radiusA = radiusA; - pc->radiusB = radiusB; - pc->type = manifold->type; - - for (int32 j = 0; j < pointCount; ++j) - { - b2ManifoldPoint* cp = manifold->points + j; - b2VelocityConstraintPoint* vcp = vc->points + j; - - if (m_step.warmStarting) - { - vcp->normalImpulse = m_step.dtRatio * cp->normalImpulse; - vcp->tangentImpulse = m_step.dtRatio * cp->tangentImpulse; - } - else - { - vcp->normalImpulse = 0.0f; - vcp->tangentImpulse = 0.0f; - } - - vcp->rA.SetZero(); - vcp->rB.SetZero(); - vcp->normalMass = 0.0f; - vcp->tangentMass = 0.0f; - vcp->velocityBias = 0.0f; - - pc->localPoints[j] = cp->localPoint; - } - } -} - -b2ContactSolver::~b2ContactSolver() -{ - m_allocator->Free(m_velocityConstraints); - m_allocator->Free(m_positionConstraints); -} - -// Initialize position dependent portions of the velocity constraints. -void b2ContactSolver::InitializeVelocityConstraints() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - float32 radiusA = pc->radiusA; - float32 radiusB = pc->radiusB; - b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - - float32 mA = vc->invMassA; - float32 mB = vc->invMassB; - float32 iA = vc->invIA; - float32 iB = vc->invIB; - b2Vec2 localCenterA = pc->localCenterA; - b2Vec2 localCenterB = pc->localCenterB; - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Assert(manifold->pointCount > 0); - - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2WorldManifold worldManifold; - worldManifold.Initialize(manifold, xfA, radiusA, xfB, radiusB); - - vc->normal = worldManifold.normal; - - int32 pointCount = vc->pointCount; - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - - vcp->rA = worldManifold.points[j] - cA; - vcp->rB = worldManifold.points[j] - cB; - - float32 rnA = b2Cross(vcp->rA, vc->normal); - float32 rnB = b2Cross(vcp->rB, vc->normal); - - float32 kNormal = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - vcp->normalMass = kNormal > 0.0f ? 1.0f / kNormal : 0.0f; - - b2Vec2 tangent = b2Cross(vc->normal, 1.0f); - - float32 rtA = b2Cross(vcp->rA, tangent); - float32 rtB = b2Cross(vcp->rB, tangent); - - float32 kTangent = mA + mB + iA * rtA * rtA + iB * rtB * rtB; - - vcp->tangentMass = kTangent > 0.0f ? 1.0f / kTangent : 0.0f; - - // Setup a velocity bias for restitution. - vcp->velocityBias = 0.0f; - float32 vRel = b2Dot(vc->normal, vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA)); - if (vRel < -b2_velocityThreshold) - { - vcp->velocityBias = -vc->restitution * vRel; - } - } - - // If we have two points, then prepare the block solver. - if (vc->pointCount == 2 && g_blockSolve) - { - b2VelocityConstraintPoint* vcp1 = vc->points + 0; - b2VelocityConstraintPoint* vcp2 = vc->points + 1; - - float32 rn1A = b2Cross(vcp1->rA, vc->normal); - float32 rn1B = b2Cross(vcp1->rB, vc->normal); - float32 rn2A = b2Cross(vcp2->rA, vc->normal); - float32 rn2B = b2Cross(vcp2->rB, vc->normal); - - float32 k11 = mA + mB + iA * rn1A * rn1A + iB * rn1B * rn1B; - float32 k22 = mA + mB + iA * rn2A * rn2A + iB * rn2B * rn2B; - float32 k12 = mA + mB + iA * rn1A * rn2A + iB * rn1B * rn2B; - - // Ensure a reasonable condition number. - const float32 k_maxConditionNumber = 1000.0f; - if (k11 * k11 < k_maxConditionNumber * (k11 * k22 - k12 * k12)) - { - // K is safe to invert. - vc->K.ex.Set(k11, k12); - vc->K.ey.Set(k12, k22); - vc->normalMass = vc->K.GetInverse(); - } - else - { - // The constraints are redundant, just use one. - // TODO_ERIN use deepest? - vc->pointCount = 1; - } - } - } -} - -void b2ContactSolver::WarmStart() -{ - // Warm start. - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 iA = vc->invIA; - float32 mB = vc->invMassB; - float32 iB = vc->invIB; - int32 pointCount = vc->pointCount; - - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Vec2 normal = vc->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - b2Vec2 P = vcp->normalImpulse * normal + vcp->tangentImpulse * tangent; - wA -= iA * b2Cross(vcp->rA, P); - vA -= mA * P; - wB += iB * b2Cross(vcp->rB, P); - vB += mB * P; - } - - m_velocities[indexA].v = vA; - m_velocities[indexA].w = wA; - m_velocities[indexB].v = vB; - m_velocities[indexB].w = wB; - } -} - -void b2ContactSolver::SolveVelocityConstraints() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - - int32 indexA = vc->indexA; - int32 indexB = vc->indexB; - float32 mA = vc->invMassA; - float32 iA = vc->invIA; - float32 mB = vc->invMassB; - float32 iB = vc->invIB; - int32 pointCount = vc->pointCount; - - b2Vec2 vA = m_velocities[indexA].v; - float32 wA = m_velocities[indexA].w; - b2Vec2 vB = m_velocities[indexB].v; - float32 wB = m_velocities[indexB].w; - - b2Vec2 normal = vc->normal; - b2Vec2 tangent = b2Cross(normal, 1.0f); - float32 friction = vc->friction; - - b2Assert(pointCount == 1 || pointCount == 2); - - // Solve tangent constraints first because non-penetration is more important - // than friction. - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - - // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); - - // Compute tangent force - float32 vt = b2Dot(dv, tangent) - vc->tangentSpeed; - float32 lambda = vcp->tangentMass * (-vt); - - // b2Clamp the accumulated force - float32 maxFriction = friction * vcp->normalImpulse; - float32 newImpulse = b2Clamp(vcp->tangentImpulse + lambda, -maxFriction, maxFriction); - lambda = newImpulse - vcp->tangentImpulse; - vcp->tangentImpulse = newImpulse; - - // Apply contact impulse - b2Vec2 P = lambda * tangent; - - vA -= mA * P; - wA -= iA * b2Cross(vcp->rA, P); - - vB += mB * P; - wB += iB * b2Cross(vcp->rB, P); - } - - // Solve normal constraints - if (pointCount == 1 || g_blockSolve == false) - { - for (int32 j = 0; j < pointCount; ++j) - { - b2VelocityConstraintPoint* vcp = vc->points + j; - - // Relative velocity at contact - b2Vec2 dv = vB + b2Cross(wB, vcp->rB) - vA - b2Cross(wA, vcp->rA); - - // Compute normal impulse - float32 vn = b2Dot(dv, normal); - float32 lambda = -vcp->normalMass * (vn - vcp->velocityBias); - - // b2Clamp the accumulated impulse - float32 newImpulse = b2Max(vcp->normalImpulse + lambda, 0.0f); - lambda = newImpulse - vcp->normalImpulse; - vcp->normalImpulse = newImpulse; - - // Apply contact impulse - b2Vec2 P = lambda * normal; - vA -= mA * P; - wA -= iA * b2Cross(vcp->rA, P); - - vB += mB * P; - wB += iB * b2Cross(vcp->rB, P); - } - } - else - { - // Block solver developed in collaboration with Dirk Gregorius (back in 01/07 on Box2D_Lite). - // Build the mini LCP for this contact patch - // - // vn = A * x + b, vn >= 0, x >= 0 and vn_i * x_i = 0 with i = 1..2 - // - // A = J * W * JT and J = ( -n, -r1 x n, n, r2 x n ) - // b = vn0 - velocityBias - // - // The system is solved using the "Total enumeration method" (s. Murty). The complementary constraint vn_i * x_i - // implies that we must have in any solution either vn_i = 0 or x_i = 0. So for the 2D contact problem the cases - // vn1 = 0 and vn2 = 0, x1 = 0 and x2 = 0, x1 = 0 and vn2 = 0, x2 = 0 and vn1 = 0 need to be tested. The first valid - // solution that satisfies the problem is chosen. - // - // In order to account of the accumulated impulse 'a' (because of the iterative nature of the solver which only requires - // that the accumulated impulse is clamped and not the incremental impulse) we change the impulse variable (x_i). - // - // Substitute: - // - // x = a + d - // - // a := old total impulse - // x := new total impulse - // d := incremental impulse - // - // For the current iteration we extend the formula for the incremental impulse - // to compute the new total impulse: - // - // vn = A * d + b - // = A * (x - a) + b - // = A * x + b - A * a - // = A * x + b' - // b' = b - A * a; - - b2VelocityConstraintPoint* cp1 = vc->points + 0; - b2VelocityConstraintPoint* cp2 = vc->points + 1; - - b2Vec2 a(cp1->normalImpulse, cp2->normalImpulse); - b2Assert(a.x >= 0.0f && a.y >= 0.0f); - - // Relative velocity at contact - b2Vec2 dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - b2Vec2 dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - float32 vn1 = b2Dot(dv1, normal); - float32 vn2 = b2Dot(dv2, normal); - - b2Vec2 b; - b.x = vn1 - cp1->velocityBias; - b.y = vn2 - cp2->velocityBias; - - // Compute b' - b -= b2Mul(vc->K, a); - - const float32 k_errorTol = 1e-3f; - B2_NOT_USED(k_errorTol); - - for (;;) - { - // - // Case 1: vn = 0 - // - // 0 = A * x + b' - // - // Solve for x: - // - // x = - inv(A) * b' - // - b2Vec2 x = - b2Mul(vc->normalMass, b); - - if (x.x >= 0.0f && x.y >= 0.0f) - { - // Get the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - vn1 = b2Dot(dv1, normal); - vn2 = b2Dot(dv2, normal); - - b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); - b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); -#endif - break; - } - - // - // Case 2: vn1 = 0 and x2 = 0 - // - // 0 = a11 * x1 + a12 * 0 + b1' - // vn2 = a21 * x1 + a22 * 0 + b2' - // - x.x = - cp1->normalMass * b.x; - x.y = 0.0f; - vn1 = 0.0f; - vn2 = vc->K.ex.y * x.x + b.y; - if (x.x >= 0.0f && vn2 >= 0.0f) - { - // Get the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv1 = vB + b2Cross(wB, cp1->rB) - vA - b2Cross(wA, cp1->rA); - - // Compute normal velocity - vn1 = b2Dot(dv1, normal); - - b2Assert(b2Abs(vn1 - cp1->velocityBias) < k_errorTol); -#endif - break; - } - - - // - // Case 3: vn2 = 0 and x1 = 0 - // - // vn1 = a11 * 0 + a12 * x2 + b1' - // 0 = a21 * 0 + a22 * x2 + b2' - // - x.x = 0.0f; - x.y = - cp2->normalMass * b.y; - vn1 = vc->K.ey.x * x.y + b.x; - vn2 = 0.0f; - - if (x.y >= 0.0f && vn1 >= 0.0f) - { - // Resubstitute for the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - -#if B2_DEBUG_SOLVER == 1 - // Postconditions - dv2 = vB + b2Cross(wB, cp2->rB) - vA - b2Cross(wA, cp2->rA); - - // Compute normal velocity - vn2 = b2Dot(dv2, normal); - - b2Assert(b2Abs(vn2 - cp2->velocityBias) < k_errorTol); -#endif - break; - } - - // - // Case 4: x1 = 0 and x2 = 0 - // - // vn1 = b1 - // vn2 = b2; - x.x = 0.0f; - x.y = 0.0f; - vn1 = b.x; - vn2 = b.y; - - if (vn1 >= 0.0f && vn2 >= 0.0f ) - { - // Resubstitute for the incremental impulse - b2Vec2 d = x - a; - - // Apply incremental impulse - b2Vec2 P1 = d.x * normal; - b2Vec2 P2 = d.y * normal; - vA -= mA * (P1 + P2); - wA -= iA * (b2Cross(cp1->rA, P1) + b2Cross(cp2->rA, P2)); - - vB += mB * (P1 + P2); - wB += iB * (b2Cross(cp1->rB, P1) + b2Cross(cp2->rB, P2)); - - // Accumulate - cp1->normalImpulse = x.x; - cp2->normalImpulse = x.y; - - break; - } - - // No solution, give up. This is hit sometimes, but it doesn't seem to matter. - break; - } - } - - m_velocities[indexA].v = vA; - m_velocities[indexA].w = wA; - m_velocities[indexB].v = vB; - m_velocities[indexB].w = wB; - } -} - -void b2ContactSolver::StoreImpulses() -{ - for (int32 i = 0; i < m_count; ++i) - { - b2ContactVelocityConstraint* vc = m_velocityConstraints + i; - b2Manifold* manifold = m_contacts[vc->contactIndex]->GetManifold(); - - for (int32 j = 0; j < vc->pointCount; ++j) - { - manifold->points[j].normalImpulse = vc->points[j].normalImpulse; - manifold->points[j].tangentImpulse = vc->points[j].tangentImpulse; - } - } -} - -struct b2PositionSolverManifold -{ - void Initialize(b2ContactPositionConstraint* pc, const b2Transform& xfA, const b2Transform& xfB, int32 index) - { - b2Assert(pc->pointCount > 0); - - switch (pc->type) - { - case b2Manifold::e_circles: - { - b2Vec2 pointA = b2Mul(xfA, pc->localPoint); - b2Vec2 pointB = b2Mul(xfB, pc->localPoints[0]); - normal = pointB - pointA; - normal.Normalize(); - point = 0.5f * (pointA + pointB); - separation = b2Dot(pointB - pointA, normal) - pc->radiusA - pc->radiusB; - } - break; - - case b2Manifold::e_faceA: - { - normal = b2Mul(xfA.q, pc->localNormal); - b2Vec2 planePoint = b2Mul(xfA, pc->localPoint); - - b2Vec2 clipPoint = b2Mul(xfB, pc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; - point = clipPoint; - } - break; - - case b2Manifold::e_faceB: - { - normal = b2Mul(xfB.q, pc->localNormal); - b2Vec2 planePoint = b2Mul(xfB, pc->localPoint); - - b2Vec2 clipPoint = b2Mul(xfA, pc->localPoints[index]); - separation = b2Dot(clipPoint - planePoint, normal) - pc->radiusA - pc->radiusB; - point = clipPoint; - - // Ensure normal points from A to B - normal = -normal; - } - break; - } - } - - b2Vec2 normal; - b2Vec2 point; - float32 separation; -}; - -// Sequential solver. -bool b2ContactSolver::SolvePositionConstraints() -{ - float32 minSeparation = 0.0f; - - for (int32 i = 0; i < m_count; ++i) - { - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - int32 indexA = pc->indexA; - int32 indexB = pc->indexB; - b2Vec2 localCenterA = pc->localCenterA; - float32 mA = pc->invMassA; - float32 iA = pc->invIA; - b2Vec2 localCenterB = pc->localCenterB; - float32 mB = pc->invMassB; - float32 iB = pc->invIB; - int32 pointCount = pc->pointCount; - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - - // Solve normal constraints - for (int32 j = 0; j < pointCount; ++j) - { - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2PositionSolverManifold psm; - psm.Initialize(pc, xfA, xfB, j); - b2Vec2 normal = psm.normal; - - b2Vec2 point = psm.point; - float32 separation = psm.separation; - - b2Vec2 rA = point - cA; - b2Vec2 rB = point - cB; - - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); - - // Prevent large corrections and allow slop. - float32 C = b2Clamp(b2_baumgarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; - - b2Vec2 P = impulse * normal; - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - - m_positions[indexA].c = cA; - m_positions[indexA].a = aA; - - m_positions[indexB].c = cB; - m_positions[indexB].a = aB; - } - - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -3.0f * b2_linearSlop; -} - -// Sequential position solver for position constraints. -bool b2ContactSolver::SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB) -{ - float32 minSeparation = 0.0f; - - for (int32 i = 0; i < m_count; ++i) - { - b2ContactPositionConstraint* pc = m_positionConstraints + i; - - int32 indexA = pc->indexA; - int32 indexB = pc->indexB; - b2Vec2 localCenterA = pc->localCenterA; - b2Vec2 localCenterB = pc->localCenterB; - int32 pointCount = pc->pointCount; - - float32 mA = 0.0f; - float32 iA = 0.0f; - if (indexA == toiIndexA || indexA == toiIndexB) - { - mA = pc->invMassA; - iA = pc->invIA; - } - - float32 mB = 0.0f; - float32 iB = 0.; - if (indexB == toiIndexA || indexB == toiIndexB) - { - mB = pc->invMassB; - iB = pc->invIB; - } - - b2Vec2 cA = m_positions[indexA].c; - float32 aA = m_positions[indexA].a; - - b2Vec2 cB = m_positions[indexB].c; - float32 aB = m_positions[indexB].a; - - // Solve normal constraints - for (int32 j = 0; j < pointCount; ++j) - { - b2Transform xfA, xfB; - xfA.q.Set(aA); - xfB.q.Set(aB); - xfA.p = cA - b2Mul(xfA.q, localCenterA); - xfB.p = cB - b2Mul(xfB.q, localCenterB); - - b2PositionSolverManifold psm; - psm.Initialize(pc, xfA, xfB, j); - b2Vec2 normal = psm.normal; - - b2Vec2 point = psm.point; - float32 separation = psm.separation; - - b2Vec2 rA = point - cA; - b2Vec2 rB = point - cB; - - // Track max constraint error. - minSeparation = b2Min(minSeparation, separation); - - // Prevent large corrections and allow slop. - float32 C = b2Clamp(b2_toiBaugarte * (separation + b2_linearSlop), -b2_maxLinearCorrection, 0.0f); - - // Compute the effective mass. - float32 rnA = b2Cross(rA, normal); - float32 rnB = b2Cross(rB, normal); - float32 K = mA + mB + iA * rnA * rnA + iB * rnB * rnB; - - // Compute normal impulse - float32 impulse = K > 0.0f ? - C / K : 0.0f; - - b2Vec2 P = impulse * normal; - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - - m_positions[indexA].c = cA; - m_positions[indexA].a = aA; - - m_positions[indexB].c = cB; - m_positions[indexB].a = aB; - } - - // We can't expect minSpeparation >= -b2_linearSlop because we don't - // push the separation above -b2_linearSlop. - return minSeparation >= -1.5f * b2_linearSlop; -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ContactSolver.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ContactSolver.h deleted file mode 100644 index ed98df5..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2ContactSolver.h +++ /dev/null @@ -1,95 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_CONTACT_SOLVER_H -#define B2_CONTACT_SOLVER_H - -#include "Box2D/Common/b2Math.h" -#include "Box2D/Collision/b2Collision.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -class b2Contact; -class b2Body; -class b2StackAllocator; -struct b2ContactPositionConstraint; - -struct b2VelocityConstraintPoint -{ - b2Vec2 rA; - b2Vec2 rB; - float32 normalImpulse; - float32 tangentImpulse; - float32 normalMass; - float32 tangentMass; - float32 velocityBias; -}; - -struct b2ContactVelocityConstraint -{ - b2VelocityConstraintPoint points[b2_maxManifoldPoints]; - b2Vec2 normal; - b2Mat22 normalMass; - b2Mat22 K; - int32 indexA; - int32 indexB; - float32 invMassA, invMassB; - float32 invIA, invIB; - float32 friction; - float32 restitution; - float32 tangentSpeed; - int32 pointCount; - int32 contactIndex; -}; - -struct b2ContactSolverDef -{ - b2TimeStep step; - b2Contact** contacts; - int32 count; - b2Position* positions; - b2Velocity* velocities; - b2StackAllocator* allocator; -}; - -class b2ContactSolver -{ -public: - b2ContactSolver(b2ContactSolverDef* def); - ~b2ContactSolver(); - - void InitializeVelocityConstraints(); - - void WarmStart(); - void SolveVelocityConstraints(); - void StoreImpulses(); - - bool SolvePositionConstraints(); - bool SolveTOIPositionConstraints(int32 toiIndexA, int32 toiIndexB); - - b2TimeStep m_step; - b2Position* m_positions; - b2Velocity* m_velocities; - b2StackAllocator* m_allocator; - b2ContactPositionConstraint* m_positionConstraints; - b2ContactVelocityConstraint* m_velocityConstraints; - b2Contact** m_contacts; - int m_count; -}; - -#endif - diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp deleted file mode 100644 index 8d5933e..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Dynamics/b2Fixture.h" - -#include <new> - -b2Contact* b2EdgeAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2EdgeAndCircleContact)); - return new (mem) b2EdgeAndCircleContact(fixtureA, fixtureB); -} - -void b2EdgeAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2EdgeAndCircleContact*)contact)->~b2EdgeAndCircleContact(); - allocator->Free(contact, sizeof(b2EdgeAndCircleContact)); -} - -b2EdgeAndCircleContact::b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2EdgeAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideEdgeAndCircle( manifold, - (b2EdgeShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h deleted file mode 100644 index e241985..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndCircleContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_EDGE_AND_CIRCLE_CONTACT_H -#define B2_EDGE_AND_CIRCLE_CONTACT_H - -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -class b2BlockAllocator; - -class b2EdgeAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2EdgeAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2EdgeAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp deleted file mode 100644 index 6fab3f7..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* -* Copyright (c) 2006-2010 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Dynamics/b2Fixture.h" - -#include <new> - -b2Contact* b2EdgeAndPolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2EdgeAndPolygonContact)); - return new (mem) b2EdgeAndPolygonContact(fixtureA, fixtureB); -} - -void b2EdgeAndPolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2EdgeAndPolygonContact*)contact)->~b2EdgeAndPolygonContact(); - allocator->Free(contact, sizeof(b2EdgeAndPolygonContact)); -} - -b2EdgeAndPolygonContact::b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_edge); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2EdgeAndPolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollideEdgeAndPolygon( manifold, - (b2EdgeShape*)m_fixtureA->GetShape(), xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h deleted file mode 100644 index ad92aac..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2EdgeAndPolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_EDGE_AND_POLYGON_CONTACT_H -#define B2_EDGE_AND_POLYGON_CONTACT_H - -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -class b2BlockAllocator; - -class b2EdgeAndPolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2EdgeAndPolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2EdgeAndPolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp deleted file mode 100644 index d3c3b94..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.cpp +++ /dev/null @@ -1,49 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Dynamics/b2Fixture.h" - -#include <new> - -b2Contact* b2PolygonAndCircleContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2PolygonAndCircleContact)); - return new (mem) b2PolygonAndCircleContact(fixtureA, fixtureB); -} - -void b2PolygonAndCircleContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2PolygonAndCircleContact*)contact)->~b2PolygonAndCircleContact(); - allocator->Free(contact, sizeof(b2PolygonAndCircleContact)); -} - -b2PolygonAndCircleContact::b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB) -: b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); - b2Assert(m_fixtureB->GetType() == b2Shape::e_circle); -} - -void b2PolygonAndCircleContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollidePolygonAndCircle( manifold, - (b2PolygonShape*)m_fixtureA->GetShape(), xfA, - (b2CircleShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h deleted file mode 100644 index fc3573c..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonAndCircleContact.h +++ /dev/null @@ -1,38 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_POLYGON_AND_CIRCLE_CONTACT_H -#define B2_POLYGON_AND_CIRCLE_CONTACT_H - -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -class b2BlockAllocator; - -class b2PolygonAndCircleContact : public b2Contact -{ -public: - static b2Contact* Create(b2Fixture* fixtureA, int32 indexA, b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2PolygonAndCircleContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2PolygonAndCircleContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonContact.cpp b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonContact.cpp deleted file mode 100644 index a9a6cdc..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonContact.cpp +++ /dev/null @@ -1,52 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Contacts/b2PolygonContact.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Collision/b2TimeOfImpact.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2WorldCallbacks.h" - -#include <new> - -b2Contact* b2PolygonContact::Create(b2Fixture* fixtureA, int32, b2Fixture* fixtureB, int32, b2BlockAllocator* allocator) -{ - void* mem = allocator->Allocate(sizeof(b2PolygonContact)); - return new (mem) b2PolygonContact(fixtureA, fixtureB); -} - -void b2PolygonContact::Destroy(b2Contact* contact, b2BlockAllocator* allocator) -{ - ((b2PolygonContact*)contact)->~b2PolygonContact(); - allocator->Free(contact, sizeof(b2PolygonContact)); -} - -b2PolygonContact::b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB) - : b2Contact(fixtureA, 0, fixtureB, 0) -{ - b2Assert(m_fixtureA->GetType() == b2Shape::e_polygon); - b2Assert(m_fixtureB->GetType() == b2Shape::e_polygon); -} - -void b2PolygonContact::Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) -{ - b2CollidePolygons( manifold, - (b2PolygonShape*)m_fixtureA->GetShape(), xfA, - (b2PolygonShape*)m_fixtureB->GetShape(), xfB); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonContact.h b/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonContact.h deleted file mode 100644 index 4755b4b..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Contacts/b2PolygonContact.h +++ /dev/null @@ -1,39 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_POLYGON_CONTACT_H -#define B2_POLYGON_CONTACT_H - -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -class b2BlockAllocator; - -class b2PolygonContact : public b2Contact -{ -public: - static b2Contact* Create( b2Fixture* fixtureA, int32 indexA, - b2Fixture* fixtureB, int32 indexB, b2BlockAllocator* allocator); - static void Destroy(b2Contact* contact, b2BlockAllocator* allocator); - - b2PolygonContact(b2Fixture* fixtureA, b2Fixture* fixtureB); - ~b2PolygonContact() {} - - void Evaluate(b2Manifold* manifold, const b2Transform& xfA, const b2Transform& xfB) override; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2DistanceJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2DistanceJoint.cpp deleted file mode 100644 index 126133c..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2DistanceJoint.cpp +++ /dev/null @@ -1,260 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2DistanceJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// 1-D constrained system -// m (v2 - v1) = lambda -// v2 + (beta/h) * x1 + gamma * lambda = 0, gamma has units of inverse mass. -// x2 = x1 + h * v2 - -// 1-D mass-damper-spring system -// m (v2 - v1) + h * d * v2 + h * k * - -// C = norm(p2 - p1) - L -// u = (p2 - p1) / norm(p2 - p1) -// Cdot = dot(u, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -// J = [-u -cross(r1, u) u cross(r2, u)] -// K = J * invM * JT -// = invMass1 + invI1 * cross(r1, u)^2 + invMass2 + invI2 * cross(r2, u)^2 - -void b2DistanceJointDef::Initialize(b2Body* b1, b2Body* b2, - const b2Vec2& anchor1, const b2Vec2& anchor2) -{ - bodyA = b1; - bodyB = b2; - localAnchorA = bodyA->GetLocalPoint(anchor1); - localAnchorB = bodyB->GetLocalPoint(anchor2); - b2Vec2 d = anchor2 - anchor1; - length = d.Length(); -} - -b2DistanceJoint::b2DistanceJoint(const b2DistanceJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_length = def->length; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - m_impulse = 0.0f; - m_gamma = 0.0f; - m_bias = 0.0f; -} - -void b2DistanceJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - m_u = cB + m_rB - cA - m_rA; - - // Handle singularity. - float32 length = m_u.Length(); - if (length > b2_linearSlop) - { - m_u *= 1.0f / length; - } - else - { - m_u.Set(0.0f, 0.0f); - } - - float32 crAu = b2Cross(m_rA, m_u); - float32 crBu = b2Cross(m_rB, m_u); - float32 invMass = m_invMassA + m_invIA * crAu * crAu + m_invMassB + m_invIB * crBu * crBu; - - // Compute the effective mass matrix. - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - - if (m_frequencyHz > 0.0f) - { - float32 C = length - m_length; - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * m_mass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m_mass * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * h * k * m_gamma; - - invMass += m_gamma; - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - } - else - { - m_gamma = 0.0f; - m_bias = 0.0f; - } - - if (data.step.warmStarting) - { - // Scale the impulse to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2DistanceJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 Cdot = b2Dot(m_u, vpB - vpA); - - float32 impulse = -m_mass * (Cdot + m_bias + m_gamma * m_impulse); - m_impulse += impulse; - - b2Vec2 P = impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2DistanceJoint::SolvePositionConstraints(const b2SolverData& data) -{ - if (m_frequencyHz > 0.0f) - { - // There is no position correction for soft distance constraints. - return true; - } - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 u = cB + rB - cA - rA; - - float32 length = u.Normalize(); - float32 C = length - m_length; - C = b2Clamp(C, -b2_maxLinearCorrection, b2_maxLinearCorrection); - - float32 impulse = -m_mass * C; - b2Vec2 P = impulse * u; - - cA -= m_invMassA * P; - aA -= m_invIA * b2Cross(rA, P); - cB += m_invMassB * P; - aB += m_invIB * b2Cross(rB, P); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return b2Abs(C) < b2_linearSlop; -} - -b2Vec2 b2DistanceJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2DistanceJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2DistanceJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 F = (inv_dt * m_impulse) * m_u; - return F; -} - -float32 b2DistanceJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -void b2DistanceJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2DistanceJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.length = %.15lef;\n", m_length); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2DistanceJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2DistanceJoint.h deleted file mode 100644 index ba59210..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2DistanceJoint.h +++ /dev/null @@ -1,169 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* 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 B2_DISTANCE_JOINT_H -#define B2_DISTANCE_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Distance joint definition. This requires defining an -/// anchor point on both bodies and the non-zero length of the -/// distance joint. The definition uses local anchor points -/// so that the initial configuration can violate the constraint -/// slightly. This helps when saving and loading a game. -/// @warning Do not use a zero or short length. -struct b2DistanceJointDef : public b2JointDef -{ - b2DistanceJointDef() - { - type = e_distanceJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - length = 1.0f; - frequencyHz = 0.0f; - dampingRatio = 0.0f; - } - - /// Initialize the bodies, anchors, and length using the world - /// anchors. - void Initialize(b2Body* bodyA, b2Body* bodyB, - const b2Vec2& anchorA, const b2Vec2& anchorB); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The natural length between the anchor points. - float32 length; - - /// The mass-spring-damper frequency in Hertz. A value of 0 - /// disables softness. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A distance joint constrains two points on two bodies -/// to remain at a fixed distance from each other. You can view -/// this as a massless, rigid rod. -class b2DistanceJoint : public b2Joint -{ -public: - - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - /// Get the reaction force given the inverse time step. - /// Unit is N. - b2Vec2 GetReactionForce(float32 inv_dt) const override; - - /// Get the reaction torque given the inverse time step. - /// Unit is N*m. This is always zero for a distance joint. - float32 GetReactionTorque(float32 inv_dt) const override; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set/get the natural length. - /// Manipulating the length can lead to non-physical behavior when the frequency is zero. - void SetLength(float32 length); - float32 GetLength() const; - - /// Set/get frequency in Hz. - void SetFrequency(float32 hz); - float32 GetFrequency() const; - - /// Set/get damping ratio. - void SetDampingRatio(float32 ratio); - float32 GetDampingRatio() const; - - /// Dump joint to dmLog - void Dump() override; - -protected: - - friend class b2Joint; - b2DistanceJoint(const b2DistanceJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_bias; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_gamma; - float32 m_impulse; - float32 m_length; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_u; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; -}; - -inline void b2DistanceJoint::SetLength(float32 length) -{ - m_length = length; -} - -inline float32 b2DistanceJoint::GetLength() const -{ - return m_length; -} - -inline void b2DistanceJoint::SetFrequency(float32 hz) -{ - m_frequencyHz = hz; -} - -inline float32 b2DistanceJoint::GetFrequency() const -{ - return m_frequencyHz; -} - -inline void b2DistanceJoint::SetDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -inline float32 b2DistanceJoint::GetDampingRatio() const -{ - return m_dampingRatio; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2FrictionJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2FrictionJoint.cpp deleted file mode 100644 index cb122eb..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2FrictionJoint.cpp +++ /dev/null @@ -1,251 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2FrictionJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// Point-to-point constraint -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Angle constraint -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2FrictionJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); -} - -b2FrictionJoint::b2FrictionJoint(const b2FrictionJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - - m_maxForce = def->maxForce; - m_maxTorque = def->maxTorque; -} - -void b2FrictionJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective mass matrix. - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat22 K; - K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; - K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; - - m_linearMass = K.GetInverse(); - - m_angularMass = iA + iB; - if (m_angularMass > 0.0f) - { - m_angularMass = 1.0f / m_angularMass; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_linearImpulse *= data.step.dtRatio; - m_angularImpulse *= data.step.dtRatio; - - b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); - } - else - { - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2FrictionJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - float32 h = data.step.dt; - - // Solve angular friction - { - float32 Cdot = wB - wA; - float32 impulse = -m_angularMass * Cdot; - - float32 oldImpulse = m_angularImpulse; - float32 maxImpulse = h * m_maxTorque; - m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_angularImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve linear friction - { - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - - b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); - b2Vec2 oldImpulse = m_linearImpulse; - m_linearImpulse += impulse; - - float32 maxImpulse = h * m_maxForce; - - if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_linearImpulse.Normalize(); - m_linearImpulse *= maxImpulse; - } - - impulse = m_linearImpulse - oldImpulse; - - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); - - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2FrictionJoint::SolvePositionConstraints(const b2SolverData& data) -{ - B2_NOT_USED(data); - - return true; -} - -b2Vec2 b2FrictionJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2FrictionJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2FrictionJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * m_linearImpulse; -} - -float32 b2FrictionJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_angularImpulse; -} - -void b2FrictionJoint::SetMaxForce(float32 force) -{ - b2Assert(b2IsValid(force) && force >= 0.0f); - m_maxForce = force; -} - -float32 b2FrictionJoint::GetMaxForce() const -{ - return m_maxForce; -} - -void b2FrictionJoint::SetMaxTorque(float32 torque) -{ - b2Assert(b2IsValid(torque) && torque >= 0.0f); - m_maxTorque = torque; -} - -float32 b2FrictionJoint::GetMaxTorque() const -{ - return m_maxTorque; -} - -void b2FrictionJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2FrictionJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); - b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2FrictionJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2FrictionJoint.h deleted file mode 100644 index d964f84..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2FrictionJoint.h +++ /dev/null @@ -1,119 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* 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 B2_FRICTION_JOINT_H -#define B2_FRICTION_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Friction joint definition. -struct b2FrictionJointDef : public b2JointDef -{ - b2FrictionJointDef() - { - type = e_frictionJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - maxForce = 0.0f; - maxTorque = 0.0f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The maximum friction force in N. - float32 maxForce; - - /// The maximum friction torque in N-m. - float32 maxTorque; -}; - -/// Friction joint. This is used for top-down friction. -/// It provides 2D translational friction and angular friction. -class b2FrictionJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - b2Vec2 GetReactionForce(float32 inv_dt) const override; - float32 GetReactionTorque(float32 inv_dt) const override; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set the maximum friction force in N. - void SetMaxForce(float32 force); - - /// Get the maximum friction force in N. - float32 GetMaxForce() const; - - /// Set the maximum friction torque in N*m. - void SetMaxTorque(float32 torque); - - /// Get the maximum friction torque in N*m. - float32 GetMaxTorque() const; - - /// Dump joint to dmLog - void Dump() override; - -protected: - - friend class b2Joint; - - b2FrictionJoint(const b2FrictionJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - - // Solver shared - b2Vec2 m_linearImpulse; - float32 m_angularImpulse; - float32 m_maxForce; - float32 m_maxTorque; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat22 m_linearMass; - float32 m_angularMass; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2GearJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2GearJoint.cpp deleted file mode 100644 index 1ce575b..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2GearJoint.cpp +++ /dev/null @@ -1,419 +0,0 @@ -/* -* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2GearJoint.h" -#include "Box2D/Dynamics/Joints/b2RevoluteJoint.h" -#include "Box2D/Dynamics/Joints/b2PrismaticJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// Gear Joint: -// C0 = (coordinate1 + ratio * coordinate2)_initial -// C = (coordinate1 + ratio * coordinate2) - C0 = 0 -// J = [J1 ratio * J2] -// K = J * invM * JT -// = J1 * invM1 * J1T + ratio * ratio * J2 * invM2 * J2T -// -// Revolute: -// coordinate = rotation -// Cdot = angularVelocity -// J = [0 0 1] -// K = J * invM * JT = invI -// -// Prismatic: -// coordinate = dot(p - pg, ug) -// Cdot = dot(v + cross(w, r), ug) -// J = [ug cross(r, ug)] -// K = J * invM * JT = invMass + invI * cross(r, ug)^2 - -b2GearJoint::b2GearJoint(const b2GearJointDef* def) -: b2Joint(def) -{ - m_joint1 = def->joint1; - m_joint2 = def->joint2; - - m_typeA = m_joint1->GetType(); - m_typeB = m_joint2->GetType(); - - b2Assert(m_typeA == e_revoluteJoint || m_typeA == e_prismaticJoint); - b2Assert(m_typeB == e_revoluteJoint || m_typeB == e_prismaticJoint); - - float32 coordinateA, coordinateB; - - // TODO_ERIN there might be some problem with the joint edges in b2Joint. - - m_bodyC = m_joint1->GetBodyA(); - m_bodyA = m_joint1->GetBodyB(); - - // Get geometry of joint1 - b2Transform xfA = m_bodyA->m_xf; - float32 aA = m_bodyA->m_sweep.a; - b2Transform xfC = m_bodyC->m_xf; - float32 aC = m_bodyC->m_sweep.a; - - if (m_typeA == e_revoluteJoint) - { - b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint1; - m_localAnchorC = revolute->m_localAnchorA; - m_localAnchorA = revolute->m_localAnchorB; - m_referenceAngleA = revolute->m_referenceAngle; - m_localAxisC.SetZero(); - - coordinateA = aA - aC - m_referenceAngleA; - } - else - { - b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint1; - m_localAnchorC = prismatic->m_localAnchorA; - m_localAnchorA = prismatic->m_localAnchorB; - m_referenceAngleA = prismatic->m_referenceAngle; - m_localAxisC = prismatic->m_localXAxisA; - - b2Vec2 pC = m_localAnchorC; - b2Vec2 pA = b2MulT(xfC.q, b2Mul(xfA.q, m_localAnchorA) + (xfA.p - xfC.p)); - coordinateA = b2Dot(pA - pC, m_localAxisC); - } - - m_bodyD = m_joint2->GetBodyA(); - m_bodyB = m_joint2->GetBodyB(); - - // Get geometry of joint2 - b2Transform xfB = m_bodyB->m_xf; - float32 aB = m_bodyB->m_sweep.a; - b2Transform xfD = m_bodyD->m_xf; - float32 aD = m_bodyD->m_sweep.a; - - if (m_typeB == e_revoluteJoint) - { - b2RevoluteJoint* revolute = (b2RevoluteJoint*)def->joint2; - m_localAnchorD = revolute->m_localAnchorA; - m_localAnchorB = revolute->m_localAnchorB; - m_referenceAngleB = revolute->m_referenceAngle; - m_localAxisD.SetZero(); - - coordinateB = aB - aD - m_referenceAngleB; - } - else - { - b2PrismaticJoint* prismatic = (b2PrismaticJoint*)def->joint2; - m_localAnchorD = prismatic->m_localAnchorA; - m_localAnchorB = prismatic->m_localAnchorB; - m_referenceAngleB = prismatic->m_referenceAngle; - m_localAxisD = prismatic->m_localXAxisA; - - b2Vec2 pD = m_localAnchorD; - b2Vec2 pB = b2MulT(xfD.q, b2Mul(xfB.q, m_localAnchorB) + (xfB.p - xfD.p)); - coordinateB = b2Dot(pB - pD, m_localAxisD); - } - - m_ratio = def->ratio; - - m_constant = coordinateA + m_ratio * coordinateB; - - m_impulse = 0.0f; -} - -void b2GearJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_indexC = m_bodyC->m_islandIndex; - m_indexD = m_bodyD->m_islandIndex; - m_lcA = m_bodyA->m_sweep.localCenter; - m_lcB = m_bodyB->m_sweep.localCenter; - m_lcC = m_bodyC->m_sweep.localCenter; - m_lcD = m_bodyD->m_sweep.localCenter; - m_mA = m_bodyA->m_invMass; - m_mB = m_bodyB->m_invMass; - m_mC = m_bodyC->m_invMass; - m_mD = m_bodyD->m_invMass; - m_iA = m_bodyA->m_invI; - m_iB = m_bodyB->m_invI; - m_iC = m_bodyC->m_invI; - m_iD = m_bodyD->m_invI; - - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 aC = data.positions[m_indexC].a; - b2Vec2 vC = data.velocities[m_indexC].v; - float32 wC = data.velocities[m_indexC].w; - - float32 aD = data.positions[m_indexD].a; - b2Vec2 vD = data.velocities[m_indexD].v; - float32 wD = data.velocities[m_indexD].w; - - b2Rot qA(aA), qB(aB), qC(aC), qD(aD); - - m_mass = 0.0f; - - if (m_typeA == e_revoluteJoint) - { - m_JvAC.SetZero(); - m_JwA = 1.0f; - m_JwC = 1.0f; - m_mass += m_iA + m_iC; - } - else - { - b2Vec2 u = b2Mul(qC, m_localAxisC); - b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); - m_JvAC = u; - m_JwC = b2Cross(rC, u); - m_JwA = b2Cross(rA, u); - m_mass += m_mC + m_mA + m_iC * m_JwC * m_JwC + m_iA * m_JwA * m_JwA; - } - - if (m_typeB == e_revoluteJoint) - { - m_JvBD.SetZero(); - m_JwB = m_ratio; - m_JwD = m_ratio; - m_mass += m_ratio * m_ratio * (m_iB + m_iD); - } - else - { - b2Vec2 u = b2Mul(qD, m_localAxisD); - b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); - m_JvBD = m_ratio * u; - m_JwD = m_ratio * b2Cross(rD, u); - m_JwB = m_ratio * b2Cross(rB, u); - m_mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * m_JwD * m_JwD + m_iB * m_JwB * m_JwB; - } - - // Compute effective mass. - m_mass = m_mass > 0.0f ? 1.0f / m_mass : 0.0f; - - if (data.step.warmStarting) - { - vA += (m_mA * m_impulse) * m_JvAC; - wA += m_iA * m_impulse * m_JwA; - vB += (m_mB * m_impulse) * m_JvBD; - wB += m_iB * m_impulse * m_JwB; - vC -= (m_mC * m_impulse) * m_JvAC; - wC -= m_iC * m_impulse * m_JwC; - vD -= (m_mD * m_impulse) * m_JvBD; - wD -= m_iD * m_impulse * m_JwD; - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; - data.velocities[m_indexC].v = vC; - data.velocities[m_indexC].w = wC; - data.velocities[m_indexD].v = vD; - data.velocities[m_indexD].w = wD; -} - -void b2GearJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - b2Vec2 vC = data.velocities[m_indexC].v; - float32 wC = data.velocities[m_indexC].w; - b2Vec2 vD = data.velocities[m_indexD].v; - float32 wD = data.velocities[m_indexD].w; - - float32 Cdot = b2Dot(m_JvAC, vA - vC) + b2Dot(m_JvBD, vB - vD); - Cdot += (m_JwA * wA - m_JwC * wC) + (m_JwB * wB - m_JwD * wD); - - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - vA += (m_mA * impulse) * m_JvAC; - wA += m_iA * impulse * m_JwA; - vB += (m_mB * impulse) * m_JvBD; - wB += m_iB * impulse * m_JwB; - vC -= (m_mC * impulse) * m_JvAC; - wC -= m_iC * impulse * m_JwC; - vD -= (m_mD * impulse) * m_JvBD; - wD -= m_iD * impulse * m_JwD; - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; - data.velocities[m_indexC].v = vC; - data.velocities[m_indexC].w = wC; - data.velocities[m_indexD].v = vD; - data.velocities[m_indexD].w = wD; -} - -bool b2GearJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 cC = data.positions[m_indexC].c; - float32 aC = data.positions[m_indexC].a; - b2Vec2 cD = data.positions[m_indexD].c; - float32 aD = data.positions[m_indexD].a; - - b2Rot qA(aA), qB(aB), qC(aC), qD(aD); - - float32 linearError = 0.0f; - - float32 coordinateA, coordinateB; - - b2Vec2 JvAC, JvBD; - float32 JwA, JwB, JwC, JwD; - float32 mass = 0.0f; - - if (m_typeA == e_revoluteJoint) - { - JvAC.SetZero(); - JwA = 1.0f; - JwC = 1.0f; - mass += m_iA + m_iC; - - coordinateA = aA - aC - m_referenceAngleA; - } - else - { - b2Vec2 u = b2Mul(qC, m_localAxisC); - b2Vec2 rC = b2Mul(qC, m_localAnchorC - m_lcC); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_lcA); - JvAC = u; - JwC = b2Cross(rC, u); - JwA = b2Cross(rA, u); - mass += m_mC + m_mA + m_iC * JwC * JwC + m_iA * JwA * JwA; - - b2Vec2 pC = m_localAnchorC - m_lcC; - b2Vec2 pA = b2MulT(qC, rA + (cA - cC)); - coordinateA = b2Dot(pA - pC, m_localAxisC); - } - - if (m_typeB == e_revoluteJoint) - { - JvBD.SetZero(); - JwB = m_ratio; - JwD = m_ratio; - mass += m_ratio * m_ratio * (m_iB + m_iD); - - coordinateB = aB - aD - m_referenceAngleB; - } - else - { - b2Vec2 u = b2Mul(qD, m_localAxisD); - b2Vec2 rD = b2Mul(qD, m_localAnchorD - m_lcD); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_lcB); - JvBD = m_ratio * u; - JwD = m_ratio * b2Cross(rD, u); - JwB = m_ratio * b2Cross(rB, u); - mass += m_ratio * m_ratio * (m_mD + m_mB) + m_iD * JwD * JwD + m_iB * JwB * JwB; - - b2Vec2 pD = m_localAnchorD - m_lcD; - b2Vec2 pB = b2MulT(qD, rB + (cB - cD)); - coordinateB = b2Dot(pB - pD, m_localAxisD); - } - - float32 C = (coordinateA + m_ratio * coordinateB) - m_constant; - - float32 impulse = 0.0f; - if (mass > 0.0f) - { - impulse = -C / mass; - } - - cA += m_mA * impulse * JvAC; - aA += m_iA * impulse * JwA; - cB += m_mB * impulse * JvBD; - aB += m_iB * impulse * JwB; - cC -= m_mC * impulse * JvAC; - aC -= m_iC * impulse * JwC; - cD -= m_mD * impulse * JvBD; - aD -= m_iD * impulse * JwD; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - data.positions[m_indexC].c = cC; - data.positions[m_indexC].a = aC; - data.positions[m_indexD].c = cD; - data.positions[m_indexD].a = aD; - - // TODO_ERIN not implemented - return linearError < b2_linearSlop; -} - -b2Vec2 b2GearJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2GearJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2GearJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P = m_impulse * m_JvAC; - return inv_dt * P; -} - -float32 b2GearJoint::GetReactionTorque(float32 inv_dt) const -{ - float32 L = m_impulse * m_JwA; - return inv_dt * L; -} - -void b2GearJoint::SetRatio(float32 ratio) -{ - b2Assert(b2IsValid(ratio)); - m_ratio = ratio; -} - -float32 b2GearJoint::GetRatio() const -{ - return m_ratio; -} - -void b2GearJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - int32 index1 = m_joint1->m_index; - int32 index2 = m_joint2->m_index; - - b2Log(" b2GearJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.joint1 = joints[%d];\n", index1); - b2Log(" jd.joint2 = joints[%d];\n", index2); - b2Log(" jd.ratio = %.15lef;\n", m_ratio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2GearJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2GearJoint.h deleted file mode 100644 index 53f7e58..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2GearJoint.h +++ /dev/null @@ -1,125 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_GEAR_JOINT_H -#define B2_GEAR_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Gear joint definition. This definition requires two existing -/// revolute or prismatic joints (any combination will work). -struct b2GearJointDef : public b2JointDef -{ - b2GearJointDef() - { - type = e_gearJoint; - joint1 = nullptr; - joint2 = nullptr; - ratio = 1.0f; - } - - /// The first revolute/prismatic joint attached to the gear joint. - b2Joint* joint1; - - /// The second revolute/prismatic joint attached to the gear joint. - b2Joint* joint2; - - /// The gear ratio. - /// @see b2GearJoint for explanation. - float32 ratio; -}; - -/// A gear joint is used to connect two joints together. Either joint -/// can be a revolute or prismatic joint. You specify a gear ratio -/// to bind the motions together: -/// coordinate1 + ratio * coordinate2 = constant -/// The ratio can be negative or positive. If one joint is a revolute joint -/// and the other joint is a prismatic joint, then the ratio will have units -/// of length or units of 1/length. -/// @warning You have to manually destroy the gear joint if joint1 or joint2 -/// is destroyed. -class b2GearJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - b2Vec2 GetReactionForce(float32 inv_dt) const override; - float32 GetReactionTorque(float32 inv_dt) const override; - - /// Get the first joint. - b2Joint* GetJoint1() { return m_joint1; } - - /// Get the second joint. - b2Joint* GetJoint2() { return m_joint2; } - - /// Set/Get the gear ratio. - void SetRatio(float32 ratio); - float32 GetRatio() const; - - /// Dump joint to dmLog - void Dump() override; - -protected: - - friend class b2Joint; - b2GearJoint(const b2GearJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - b2Joint* m_joint1; - b2Joint* m_joint2; - - b2JointType m_typeA; - b2JointType m_typeB; - - // Body A is connected to body C - // Body B is connected to body D - b2Body* m_bodyC; - b2Body* m_bodyD; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localAnchorC; - b2Vec2 m_localAnchorD; - - b2Vec2 m_localAxisC; - b2Vec2 m_localAxisD; - - float32 m_referenceAngleA; - float32 m_referenceAngleB; - - float32 m_constant; - float32 m_ratio; - - float32 m_impulse; - - // Solver temp - int32 m_indexA, m_indexB, m_indexC, m_indexD; - b2Vec2 m_lcA, m_lcB, m_lcC, m_lcD; - float32 m_mA, m_mB, m_mC, m_mD; - float32 m_iA, m_iB, m_iC, m_iD; - b2Vec2 m_JvAC, m_JvBD; - float32 m_JwA, m_JwB, m_JwC, m_JwD; - float32 m_mass; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2Joint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2Joint.cpp deleted file mode 100644 index 8103b01..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2Joint.cpp +++ /dev/null @@ -1,211 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2Joint.h" -#include "Box2D/Dynamics/Joints/b2DistanceJoint.h" -#include "Box2D/Dynamics/Joints/b2WheelJoint.h" -#include "Box2D/Dynamics/Joints/b2MouseJoint.h" -#include "Box2D/Dynamics/Joints/b2RevoluteJoint.h" -#include "Box2D/Dynamics/Joints/b2PrismaticJoint.h" -#include "Box2D/Dynamics/Joints/b2PulleyJoint.h" -#include "Box2D/Dynamics/Joints/b2GearJoint.h" -#include "Box2D/Dynamics/Joints/b2WeldJoint.h" -#include "Box2D/Dynamics/Joints/b2FrictionJoint.h" -#include "Box2D/Dynamics/Joints/b2RopeJoint.h" -#include "Box2D/Dynamics/Joints/b2MotorJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2World.h" -#include "Box2D/Common/b2BlockAllocator.h" - -#include <new> - -b2Joint* b2Joint::Create(const b2JointDef* def, b2BlockAllocator* allocator) -{ - b2Joint* joint = nullptr; - - switch (def->type) - { - case e_distanceJoint: - { - void* mem = allocator->Allocate(sizeof(b2DistanceJoint)); - joint = new (mem) b2DistanceJoint(static_cast<const b2DistanceJointDef*>(def)); - } - break; - - case e_mouseJoint: - { - void* mem = allocator->Allocate(sizeof(b2MouseJoint)); - joint = new (mem) b2MouseJoint(static_cast<const b2MouseJointDef*>(def)); - } - break; - - case e_prismaticJoint: - { - void* mem = allocator->Allocate(sizeof(b2PrismaticJoint)); - joint = new (mem) b2PrismaticJoint(static_cast<const b2PrismaticJointDef*>(def)); - } - break; - - case e_revoluteJoint: - { - void* mem = allocator->Allocate(sizeof(b2RevoluteJoint)); - joint = new (mem) b2RevoluteJoint(static_cast<const b2RevoluteJointDef*>(def)); - } - break; - - case e_pulleyJoint: - { - void* mem = allocator->Allocate(sizeof(b2PulleyJoint)); - joint = new (mem) b2PulleyJoint(static_cast<const b2PulleyJointDef*>(def)); - } - break; - - case e_gearJoint: - { - void* mem = allocator->Allocate(sizeof(b2GearJoint)); - joint = new (mem) b2GearJoint(static_cast<const b2GearJointDef*>(def)); - } - break; - - case e_wheelJoint: - { - void* mem = allocator->Allocate(sizeof(b2WheelJoint)); - joint = new (mem) b2WheelJoint(static_cast<const b2WheelJointDef*>(def)); - } - break; - - case e_weldJoint: - { - void* mem = allocator->Allocate(sizeof(b2WeldJoint)); - joint = new (mem) b2WeldJoint(static_cast<const b2WeldJointDef*>(def)); - } - break; - - case e_frictionJoint: - { - void* mem = allocator->Allocate(sizeof(b2FrictionJoint)); - joint = new (mem) b2FrictionJoint(static_cast<const b2FrictionJointDef*>(def)); - } - break; - - case e_ropeJoint: - { - void* mem = allocator->Allocate(sizeof(b2RopeJoint)); - joint = new (mem) b2RopeJoint(static_cast<const b2RopeJointDef*>(def)); - } - break; - - case e_motorJoint: - { - void* mem = allocator->Allocate(sizeof(b2MotorJoint)); - joint = new (mem) b2MotorJoint(static_cast<const b2MotorJointDef*>(def)); - } - break; - - default: - b2Assert(false); - break; - } - - return joint; -} - -void b2Joint::Destroy(b2Joint* joint, b2BlockAllocator* allocator) -{ - joint->~b2Joint(); - switch (joint->m_type) - { - case e_distanceJoint: - allocator->Free(joint, sizeof(b2DistanceJoint)); - break; - - case e_mouseJoint: - allocator->Free(joint, sizeof(b2MouseJoint)); - break; - - case e_prismaticJoint: - allocator->Free(joint, sizeof(b2PrismaticJoint)); - break; - - case e_revoluteJoint: - allocator->Free(joint, sizeof(b2RevoluteJoint)); - break; - - case e_pulleyJoint: - allocator->Free(joint, sizeof(b2PulleyJoint)); - break; - - case e_gearJoint: - allocator->Free(joint, sizeof(b2GearJoint)); - break; - - case e_wheelJoint: - allocator->Free(joint, sizeof(b2WheelJoint)); - break; - - case e_weldJoint: - allocator->Free(joint, sizeof(b2WeldJoint)); - break; - - case e_frictionJoint: - allocator->Free(joint, sizeof(b2FrictionJoint)); - break; - - case e_ropeJoint: - allocator->Free(joint, sizeof(b2RopeJoint)); - break; - - case e_motorJoint: - allocator->Free(joint, sizeof(b2MotorJoint)); - break; - - default: - b2Assert(false); - break; - } -} - -b2Joint::b2Joint(const b2JointDef* def) -{ - b2Assert(def->bodyA != def->bodyB); - - m_type = def->type; - m_prev = nullptr; - m_next = nullptr; - m_bodyA = def->bodyA; - m_bodyB = def->bodyB; - m_index = 0; - m_collideConnected = def->collideConnected; - m_islandFlag = false; - m_userData = def->userData; - - m_edgeA.joint = nullptr; - m_edgeA.other = nullptr; - m_edgeA.prev = nullptr; - m_edgeA.next = nullptr; - - m_edgeB.joint = nullptr; - m_edgeB.other = nullptr; - m_edgeB.prev = nullptr; - m_edgeB.next = nullptr; -} - -bool b2Joint::IsActive() const -{ - return m_bodyA->IsActive() && m_bodyB->IsActive(); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2Joint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2Joint.h deleted file mode 100644 index 2ab5616..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2Joint.h +++ /dev/null @@ -1,226 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* 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 B2_JOINT_H -#define B2_JOINT_H - -#include "Box2D/Common/b2Math.h" - -class b2Body; -class b2Joint; -struct b2SolverData; -class b2BlockAllocator; - -enum b2JointType -{ - e_unknownJoint, - e_revoluteJoint, - e_prismaticJoint, - e_distanceJoint, - e_pulleyJoint, - e_mouseJoint, - e_gearJoint, - e_wheelJoint, - e_weldJoint, - e_frictionJoint, - e_ropeJoint, - e_motorJoint -}; - -enum b2LimitState -{ - e_inactiveLimit, - e_atLowerLimit, - e_atUpperLimit, - e_equalLimits -}; - -struct b2Jacobian -{ - b2Vec2 linear; - float32 angularA; - float32 angularB; -}; - -/// A joint edge is used to connect bodies and joints together -/// in a joint graph where each body is a node and each joint -/// is an edge. A joint edge belongs to a doubly linked list -/// maintained in each attached body. Each joint has two joint -/// nodes, one for each attached body. -struct b2JointEdge -{ - b2Body* other; ///< provides quick access to the other body attached. - b2Joint* joint; ///< the joint - b2JointEdge* prev; ///< the previous joint edge in the body's joint list - b2JointEdge* next; ///< the next joint edge in the body's joint list -}; - -/// Joint definitions are used to construct joints. -struct b2JointDef -{ - b2JointDef() - { - type = e_unknownJoint; - userData = nullptr; - bodyA = nullptr; - bodyB = nullptr; - collideConnected = false; - } - - /// The joint type is set automatically for concrete joint types. - b2JointType type; - - /// Use this to attach application specific data to your joints. - void* userData; - - /// The first attached body. - b2Body* bodyA; - - /// The second attached body. - b2Body* bodyB; - - /// Set this flag to true if the attached bodies should collide. - bool collideConnected; -}; - -/// The base joint class. Joints are used to constraint two bodies together in -/// various fashions. Some joints also feature limits and motors. -class b2Joint -{ -public: - - /// Get the type of the concrete joint. - b2JointType GetType() const; - - /// Get the first body attached to this joint. - b2Body* GetBodyA(); - - /// Get the second body attached to this joint. - b2Body* GetBodyB(); - - /// Get the anchor point on bodyA in world coordinates. - virtual b2Vec2 GetAnchorA() const = 0; - - /// Get the anchor point on bodyB in world coordinates. - virtual b2Vec2 GetAnchorB() const = 0; - - /// Get the reaction force on bodyB at the joint anchor in Newtons. - virtual b2Vec2 GetReactionForce(float32 inv_dt) const = 0; - - /// Get the reaction torque on bodyB in N*m. - virtual float32 GetReactionTorque(float32 inv_dt) const = 0; - - /// Get the next joint the world joint list. - b2Joint* GetNext(); - const b2Joint* GetNext() const; - - /// Get the user data pointer. - void* GetUserData() const; - - /// Set the user data pointer. - void SetUserData(void* data); - - /// Short-cut function to determine if either body is inactive. - bool IsActive() const; - - /// Get collide connected. - /// Note: modifying the collide connect flag won't work correctly because - /// the flag is only checked when fixture AABBs begin to overlap. - bool GetCollideConnected() const; - - /// Dump this joint to the log file. - virtual void Dump() { b2Log("// Dump is not supported for this joint type.\n"); } - - /// Shift the origin for any points stored in world coordinates. - virtual void ShiftOrigin(const b2Vec2& newOrigin) { B2_NOT_USED(newOrigin); } - -protected: - friend class b2World; - friend class b2Body; - friend class b2Island; - friend class b2GearJoint; - - static b2Joint* Create(const b2JointDef* def, b2BlockAllocator* allocator); - static void Destroy(b2Joint* joint, b2BlockAllocator* allocator); - - b2Joint(const b2JointDef* def); - virtual ~b2Joint() {} - - virtual void InitVelocityConstraints(const b2SolverData& data) = 0; - virtual void SolveVelocityConstraints(const b2SolverData& data) = 0; - - // This returns true if the position errors are within tolerance. - virtual bool SolvePositionConstraints(const b2SolverData& data) = 0; - - b2JointType m_type; - b2Joint* m_prev; - b2Joint* m_next; - b2JointEdge m_edgeA; - b2JointEdge m_edgeB; - b2Body* m_bodyA; - b2Body* m_bodyB; - - int32 m_index; - - bool m_islandFlag; - bool m_collideConnected; - - void* m_userData; -}; - -inline b2JointType b2Joint::GetType() const -{ - return m_type; -} - -inline b2Body* b2Joint::GetBodyA() -{ - return m_bodyA; -} - -inline b2Body* b2Joint::GetBodyB() -{ - return m_bodyB; -} - -inline b2Joint* b2Joint::GetNext() -{ - return m_next; -} - -inline const b2Joint* b2Joint::GetNext() const -{ - return m_next; -} - -inline void* b2Joint::GetUserData() const -{ - return m_userData; -} - -inline void b2Joint::SetUserData(void* data) -{ - m_userData = data; -} - -inline bool b2Joint::GetCollideConnected() const -{ - return m_collideConnected; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2MotorJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2MotorJoint.cpp deleted file mode 100644 index 7906845..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2MotorJoint.cpp +++ /dev/null @@ -1,309 +0,0 @@ -/* -* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2MotorJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// Point-to-point constraint -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) -// -// r1 = offset - c1 -// r2 = -c2 - -// Angle constraint -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2MotorJointDef::Initialize(b2Body* bA, b2Body* bB) -{ - bodyA = bA; - bodyB = bB; - b2Vec2 xB = bodyB->GetPosition(); - linearOffset = bodyA->GetLocalPoint(xB); - - float32 angleA = bodyA->GetAngle(); - float32 angleB = bodyB->GetAngle(); - angularOffset = angleB - angleA; -} - -b2MotorJoint::b2MotorJoint(const b2MotorJointDef* def) -: b2Joint(def) -{ - m_linearOffset = def->linearOffset; - m_angularOffset = def->angularOffset; - - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - - m_maxForce = def->maxForce; - m_maxTorque = def->maxTorque; - m_correctionFactor = def->correctionFactor; -} - -void b2MotorJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective mass matrix. - m_rA = b2Mul(qA, m_linearOffset - m_localCenterA); - m_rB = b2Mul(qB, -m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Upper 2 by 2 of K for point to point - b2Mat22 K; - K.ex.x = mA + mB + iA * m_rA.y * m_rA.y + iB * m_rB.y * m_rB.y; - K.ex.y = -iA * m_rA.x * m_rA.y - iB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * m_rA.x * m_rA.x + iB * m_rB.x * m_rB.x; - - m_linearMass = K.GetInverse(); - - m_angularMass = iA + iB; - if (m_angularMass > 0.0f) - { - m_angularMass = 1.0f / m_angularMass; - } - - m_linearError = cB + m_rB - cA - m_rA; - m_angularError = aB - aA - m_angularOffset; - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_linearImpulse *= data.step.dtRatio; - m_angularImpulse *= data.step.dtRatio; - - b2Vec2 P(m_linearImpulse.x, m_linearImpulse.y); - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_angularImpulse); - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_angularImpulse); - } - else - { - m_linearImpulse.SetZero(); - m_angularImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2MotorJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - float32 h = data.step.dt; - float32 inv_h = data.step.inv_dt; - - // Solve angular friction - { - float32 Cdot = wB - wA + inv_h * m_correctionFactor * m_angularError; - float32 impulse = -m_angularMass * Cdot; - - float32 oldImpulse = m_angularImpulse; - float32 maxImpulse = h * m_maxTorque; - m_angularImpulse = b2Clamp(m_angularImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_angularImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve linear friction - { - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA) + inv_h * m_correctionFactor * m_linearError; - - b2Vec2 impulse = -b2Mul(m_linearMass, Cdot); - b2Vec2 oldImpulse = m_linearImpulse; - m_linearImpulse += impulse; - - float32 maxImpulse = h * m_maxForce; - - if (m_linearImpulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_linearImpulse.Normalize(); - m_linearImpulse *= maxImpulse; - } - - impulse = m_linearImpulse - oldImpulse; - - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); - - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2MotorJoint::SolvePositionConstraints(const b2SolverData& data) -{ - B2_NOT_USED(data); - - return true; -} - -b2Vec2 b2MotorJoint::GetAnchorA() const -{ - return m_bodyA->GetPosition(); -} - -b2Vec2 b2MotorJoint::GetAnchorB() const -{ - return m_bodyB->GetPosition(); -} - -b2Vec2 b2MotorJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * m_linearImpulse; -} - -float32 b2MotorJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_angularImpulse; -} - -void b2MotorJoint::SetMaxForce(float32 force) -{ - b2Assert(b2IsValid(force) && force >= 0.0f); - m_maxForce = force; -} - -float32 b2MotorJoint::GetMaxForce() const -{ - return m_maxForce; -} - -void b2MotorJoint::SetMaxTorque(float32 torque) -{ - b2Assert(b2IsValid(torque) && torque >= 0.0f); - m_maxTorque = torque; -} - -float32 b2MotorJoint::GetMaxTorque() const -{ - return m_maxTorque; -} - -void b2MotorJoint::SetCorrectionFactor(float32 factor) -{ - b2Assert(b2IsValid(factor) && 0.0f <= factor && factor <= 1.0f); - m_correctionFactor = factor; -} - -float32 b2MotorJoint::GetCorrectionFactor() const -{ - return m_correctionFactor; -} - -void b2MotorJoint::SetLinearOffset(const b2Vec2& linearOffset) -{ - if (linearOffset.x != m_linearOffset.x || linearOffset.y != m_linearOffset.y) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_linearOffset = linearOffset; - } -} - -const b2Vec2& b2MotorJoint::GetLinearOffset() const -{ - return m_linearOffset; -} - -void b2MotorJoint::SetAngularOffset(float32 angularOffset) -{ - if (angularOffset != m_angularOffset) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_angularOffset = angularOffset; - } -} - -float32 b2MotorJoint::GetAngularOffset() const -{ - return m_angularOffset; -} - -void b2MotorJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2MotorJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.linearOffset.Set(%.15lef, %.15lef);\n", m_linearOffset.x, m_linearOffset.y); - b2Log(" jd.angularOffset = %.15lef;\n", m_angularOffset); - b2Log(" jd.maxForce = %.15lef;\n", m_maxForce); - b2Log(" jd.maxTorque = %.15lef;\n", m_maxTorque); - b2Log(" jd.correctionFactor = %.15lef;\n", m_correctionFactor); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2MotorJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2MotorJoint.h deleted file mode 100644 index f384f41..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2MotorJoint.h +++ /dev/null @@ -1,133 +0,0 @@ -/* -* Copyright (c) 2006-2012 Erin Catto http://www.box2d.org -* -* 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 B2_MOTOR_JOINT_H -#define B2_MOTOR_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Motor joint definition. -struct b2MotorJointDef : public b2JointDef -{ - b2MotorJointDef() - { - type = e_motorJoint; - linearOffset.SetZero(); - angularOffset = 0.0f; - maxForce = 1.0f; - maxTorque = 1.0f; - correctionFactor = 0.3f; - } - - /// Initialize the bodies and offsets using the current transforms. - void Initialize(b2Body* bodyA, b2Body* bodyB); - - /// Position of bodyB minus the position of bodyA, in bodyA's frame, in meters. - b2Vec2 linearOffset; - - /// The bodyB angle minus bodyA angle in radians. - float32 angularOffset; - - /// The maximum motor force in N. - float32 maxForce; - - /// The maximum motor torque in N-m. - float32 maxTorque; - - /// Position correction factor in the range [0,1]. - float32 correctionFactor; -}; - -/// A motor joint is used to control the relative motion -/// between two bodies. A typical usage is to control the movement -/// of a dynamic body with respect to the ground. -class b2MotorJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - b2Vec2 GetReactionForce(float32 inv_dt) const override; - float32 GetReactionTorque(float32 inv_dt) const override; - - /// Set/get the target linear offset, in frame A, in meters. - void SetLinearOffset(const b2Vec2& linearOffset); - const b2Vec2& GetLinearOffset() const; - - /// Set/get the target angular offset, in radians. - void SetAngularOffset(float32 angularOffset); - float32 GetAngularOffset() const; - - /// Set the maximum friction force in N. - void SetMaxForce(float32 force); - - /// Get the maximum friction force in N. - float32 GetMaxForce() const; - - /// Set the maximum friction torque in N*m. - void SetMaxTorque(float32 torque); - - /// Get the maximum friction torque in N*m. - float32 GetMaxTorque() const; - - /// Set the position correction factor in the range [0,1]. - void SetCorrectionFactor(float32 factor); - - /// Get the position correction factor in the range [0,1]. - float32 GetCorrectionFactor() const; - - /// Dump to b2Log - void Dump() override; - -protected: - - friend class b2Joint; - - b2MotorJoint(const b2MotorJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - // Solver shared - b2Vec2 m_linearOffset; - float32 m_angularOffset; - b2Vec2 m_linearImpulse; - float32 m_angularImpulse; - float32 m_maxForce; - float32 m_maxTorque; - float32 m_correctionFactor; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - b2Vec2 m_linearError; - float32 m_angularError; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat22 m_linearMass; - float32 m_angularMass; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2MouseJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2MouseJoint.cpp deleted file mode 100644 index 637e4cd..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2MouseJoint.cpp +++ /dev/null @@ -1,222 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2MouseJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// p = attached point, m = mouse point -// C = p - m -// Cdot = v -// = v + cross(w, r) -// J = [I r_skew] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -b2MouseJoint::b2MouseJoint(const b2MouseJointDef* def) -: b2Joint(def) -{ - b2Assert(def->target.IsValid()); - b2Assert(b2IsValid(def->maxForce) && def->maxForce >= 0.0f); - b2Assert(b2IsValid(def->frequencyHz) && def->frequencyHz >= 0.0f); - b2Assert(b2IsValid(def->dampingRatio) && def->dampingRatio >= 0.0f); - - m_targetA = def->target; - m_localAnchorB = b2MulT(m_bodyB->GetTransform(), m_targetA); - - m_maxForce = def->maxForce; - m_impulse.SetZero(); - - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_beta = 0.0f; - m_gamma = 0.0f; -} - -void b2MouseJoint::SetTarget(const b2Vec2& target) -{ - if (target != m_targetA) - { - m_bodyB->SetAwake(true); - m_targetA = target; - } -} - -const b2Vec2& b2MouseJoint::GetTarget() const -{ - return m_targetA; -} - -void b2MouseJoint::SetMaxForce(float32 force) -{ - m_maxForce = force; -} - -float32 b2MouseJoint::GetMaxForce() const -{ - return m_maxForce; -} - -void b2MouseJoint::SetFrequency(float32 hz) -{ - m_frequencyHz = hz; -} - -float32 b2MouseJoint::GetFrequency() const -{ - return m_frequencyHz; -} - -void b2MouseJoint::SetDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -float32 b2MouseJoint::GetDampingRatio() const -{ - return m_dampingRatio; -} - -void b2MouseJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexB = m_bodyB->m_islandIndex; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassB = m_bodyB->m_invMass; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qB(aB); - - float32 mass = m_bodyB->GetMass(); - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * mass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = mass * (omega * omega); - - // magic formulas - // gamma has units of inverse mass. - // beta has units of inverse time. - float32 h = data.step.dt; - b2Assert(d + h * k > b2_epsilon); - m_gamma = h * (d + h * k); - if (m_gamma != 0.0f) - { - m_gamma = 1.0f / m_gamma; - } - m_beta = h * k * m_gamma; - - // Compute the effective mass matrix. - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // K = [(1/m1 + 1/m2) * eye(2) - skew(r1) * invI1 * skew(r1) - skew(r2) * invI2 * skew(r2)] - // = [1/m1+1/m2 0 ] + invI1 * [r1.y*r1.y -r1.x*r1.y] + invI2 * [r1.y*r1.y -r1.x*r1.y] - // [ 0 1/m1+1/m2] [-r1.x*r1.y r1.x*r1.x] [-r1.x*r1.y r1.x*r1.x] - b2Mat22 K; - K.ex.x = m_invMassB + m_invIB * m_rB.y * m_rB.y + m_gamma; - K.ex.y = -m_invIB * m_rB.x * m_rB.y; - K.ey.x = K.ex.y; - K.ey.y = m_invMassB + m_invIB * m_rB.x * m_rB.x + m_gamma; - - m_mass = K.GetInverse(); - - m_C = cB + m_rB - m_targetA; - m_C *= m_beta; - - // Cheat with some damping - wB *= 0.98f; - - if (data.step.warmStarting) - { - m_impulse *= data.step.dtRatio; - vB += m_invMassB * m_impulse; - wB += m_invIB * b2Cross(m_rB, m_impulse); - } - else - { - m_impulse.SetZero(); - } - - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2MouseJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = v + cross(w, r) - b2Vec2 Cdot = vB + b2Cross(wB, m_rB); - b2Vec2 impulse = b2Mul(m_mass, -(Cdot + m_C + m_gamma * m_impulse)); - - b2Vec2 oldImpulse = m_impulse; - m_impulse += impulse; - float32 maxImpulse = data.step.dt * m_maxForce; - if (m_impulse.LengthSquared() > maxImpulse * maxImpulse) - { - m_impulse *= maxImpulse / m_impulse.Length(); - } - impulse = m_impulse - oldImpulse; - - vB += m_invMassB * impulse; - wB += m_invIB * b2Cross(m_rB, impulse); - - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2MouseJoint::SolvePositionConstraints(const b2SolverData& data) -{ - B2_NOT_USED(data); - return true; -} - -b2Vec2 b2MouseJoint::GetAnchorA() const -{ - return m_targetA; -} - -b2Vec2 b2MouseJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2MouseJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * m_impulse; -} - -float32 b2MouseJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * 0.0f; -} - -void b2MouseJoint::ShiftOrigin(const b2Vec2& newOrigin) -{ - m_targetA -= newOrigin; -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2MouseJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2MouseJoint.h deleted file mode 100644 index 7441978..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2MouseJoint.h +++ /dev/null @@ -1,129 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* 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 B2_MOUSE_JOINT_H -#define B2_MOUSE_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Mouse joint definition. This requires a world target point, -/// tuning parameters, and the time step. -struct b2MouseJointDef : public b2JointDef -{ - b2MouseJointDef() - { - type = e_mouseJoint; - target.Set(0.0f, 0.0f); - maxForce = 0.0f; - frequencyHz = 5.0f; - dampingRatio = 0.7f; - } - - /// The initial world target point. This is assumed - /// to coincide with the body anchor initially. - b2Vec2 target; - - /// The maximum constraint force that can be exerted - /// to move the candidate body. Usually you will express - /// as some multiple of the weight (multiplier * mass * gravity). - float32 maxForce; - - /// The response speed. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A mouse joint is used to make a point on a body track a -/// specified world point. This a soft constraint with a maximum -/// force. This allows the constraint to stretch and without -/// applying huge forces. -/// NOTE: this joint is not documented in the manual because it was -/// developed to be used in the testbed. If you want to learn how to -/// use the mouse joint, look at the testbed. -class b2MouseJoint : public b2Joint -{ -public: - - /// Implements b2Joint. - b2Vec2 GetAnchorA() const override; - - /// Implements b2Joint. - b2Vec2 GetAnchorB() const override; - - /// Implements b2Joint. - b2Vec2 GetReactionForce(float32 inv_dt) const override; - - /// Implements b2Joint. - float32 GetReactionTorque(float32 inv_dt) const override; - - /// Use this to update the target point. - void SetTarget(const b2Vec2& target); - const b2Vec2& GetTarget() const; - - /// Set/get the maximum force in Newtons. - void SetMaxForce(float32 force); - float32 GetMaxForce() const; - - /// Set/get the frequency in Hertz. - void SetFrequency(float32 hz); - float32 GetFrequency() const; - - /// Set/get the damping ratio (dimensionless). - void SetDampingRatio(float32 ratio); - float32 GetDampingRatio() const; - - /// The mouse joint does not support dumping. - void Dump() override { b2Log("Mouse joint dumping is not supported.\n"); } - - /// Implement b2Joint::ShiftOrigin - void ShiftOrigin(const b2Vec2& newOrigin) override; - -protected: - friend class b2Joint; - - b2MouseJoint(const b2MouseJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - b2Vec2 m_localAnchorB; - b2Vec2 m_targetA; - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_beta; - - // Solver shared - b2Vec2 m_impulse; - float32 m_maxForce; - float32 m_gamma; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rB; - b2Vec2 m_localCenterB; - float32 m_invMassB; - float32 m_invIB; - b2Mat22 m_mass; - b2Vec2 m_C; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp deleted file mode 100644 index 5da19b6..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2PrismaticJoint.cpp +++ /dev/null @@ -1,642 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2PrismaticJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// Linear constraint (point-to-line) -// d = p2 - p1 = x2 + r2 - x1 - r1 -// C = dot(perp, d) -// Cdot = dot(d, cross(w1, perp)) + dot(perp, v2 + cross(w2, r2) - v1 - cross(w1, r1)) -// = -dot(perp, v1) - dot(cross(d + r1, perp), w1) + dot(perp, v2) + dot(cross(r2, perp), v2) -// J = [-perp, -cross(d + r1, perp), perp, cross(r2,perp)] -// -// Angular constraint -// C = a2 - a1 + a_initial -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// -// K = J * invM * JT -// -// J = [-a -s1 a s2] -// [0 -1 0 1] -// a = perp -// s1 = cross(d + r1, a) = cross(p2 - x1, a) -// s2 = cross(r2, a) = cross(p2 - x2, a) - - -// Motor/Limit linear constraint -// C = dot(ax1, d) -// Cdot = = -dot(ax1, v1) - dot(cross(d + r1, ax1), w1) + dot(ax1, v2) + dot(cross(r2, ax1), v2) -// J = [-ax1 -cross(d+r1,ax1) ax1 cross(r2,ax1)] - -// Block Solver -// We develop a block solver that includes the joint limit. This makes the limit stiff (inelastic) even -// when the mass has poor distribution (leading to large torques about the joint anchor points). -// -// The Jacobian has 3 rows: -// J = [-uT -s1 uT s2] // linear -// [0 -1 0 1] // angular -// [-vT -a1 vT a2] // limit -// -// u = perp -// v = axis -// s1 = cross(d + r1, u), s2 = cross(r2, u) -// a1 = cross(d + r1, v), a2 = cross(r2, v) - -// M * (v2 - v1) = JT * df -// J * v2 = bias -// -// v2 = v1 + invM * JT * df -// J * (v1 + invM * JT * df) = bias -// K * df = bias - J * v1 = -Cdot -// K = J * invM * JT -// Cdot = J * v1 - bias -// -// Now solve for f2. -// df = f2 - f1 -// K * (f2 - f1) = -Cdot -// f2 = invK * (-Cdot) + f1 -// -// Clamp accumulated limit impulse. -// lower: f2(3) = max(f2(3), 0) -// upper: f2(3) = min(f2(3), 0) -// -// Solve for correct f2(1:2) -// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:3) * f1 -// = -Cdot(1:2) - K(1:2,3) * f2(3) + K(1:2,1:2) * f1(1:2) + K(1:2,3) * f1(3) -// K(1:2, 1:2) * f2(1:2) = -Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3)) + K(1:2,1:2) * f1(1:2) -// f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) -// -// Now compute impulse to be applied: -// df = f2 - f1 - -void b2PrismaticJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2PrismaticJoint::b2PrismaticJoint(const b2PrismaticJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_localXAxisA = def->localAxisA; - m_localXAxisA.Normalize(); - m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - m_referenceAngle = def->referenceAngle; - - m_impulse.SetZero(); - m_motorMass = 0.0f; - m_motorImpulse = 0.0f; - - m_lowerTranslation = def->lowerTranslation; - m_upperTranslation = def->upperTranslation; - m_maxMotorForce = def->maxMotorForce; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; - - m_axis.SetZero(); - m_perp.SetZero(); -} - -void b2PrismaticJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective masses. - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = (cB - cA) + rB - rA; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Compute motor Jacobian and effective mass. - { - m_axis = b2Mul(qA, m_localXAxisA); - m_a1 = b2Cross(d + rA, m_axis); - m_a2 = b2Cross(rB, m_axis); - - m_motorMass = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - } - - // Prismatic constraint. - { - m_perp = b2Mul(qA, m_localYAxisA); - - m_s1 = b2Cross(d + rA, m_perp); - m_s2 = b2Cross(rB, m_perp); - - float32 k11 = mA + mB + iA * m_s1 * m_s1 + iB * m_s2 * m_s2; - float32 k12 = iA * m_s1 + iB * m_s2; - float32 k13 = iA * m_s1 * m_a1 + iB * m_s2 * m_a2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - // For bodies with fixed rotation. - k22 = 1.0f; - } - float32 k23 = iA * m_a1 + iB * m_a2; - float32 k33 = mA + mB + iA * m_a1 * m_a1 + iB * m_a2 * m_a2; - - m_K.ex.Set(k11, k12, k13); - m_K.ey.Set(k12, k22, k23); - m_K.ez.Set(k13, k23, k33); - } - - // Compute motor and limit terms. - if (m_enableLimit) - { - float32 jointTranslation = b2Dot(m_axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - m_limitState = e_equalLimits; - } - else if (jointTranslation <= m_lowerTranslation) - { - if (m_limitState != e_atLowerLimit) - { - m_limitState = e_atLowerLimit; - m_impulse.z = 0.0f; - } - } - else if (jointTranslation >= m_upperTranslation) - { - if (m_limitState != e_atUpperLimit) - { - m_limitState = e_atUpperLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - - if (m_enableMotor == false) - { - m_motorImpulse = 0.0f; - } - - if (data.step.warmStarting) - { - // Account for variable time step. - m_impulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis; - float32 LA = m_impulse.x * m_s1 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a1; - float32 LB = m_impulse.x * m_s2 + m_impulse.y + (m_motorImpulse + m_impulse.z) * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2PrismaticJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Solve linear motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits) - { - float32 Cdot = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; - float32 impulse = m_motorMass * (m_motorSpeed - Cdot); - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorForce; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - b2Vec2 P = impulse * m_axis; - float32 LA = impulse * m_a1; - float32 LB = impulse * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - b2Vec2 Cdot1; - Cdot1.x = b2Dot(m_perp, vB - vA) + m_s2 * wB - m_s1 * wA; - Cdot1.y = wB - wA; - - if (m_enableLimit && m_limitState != e_inactiveLimit) - { - // Solve prismatic and limit constraint in block form. - float32 Cdot2; - Cdot2 = b2Dot(m_axis, vB - vA) + m_a2 * wB - m_a1 * wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 f1 = m_impulse; - b2Vec3 df = m_K.Solve33(-Cdot); - m_impulse += df; - - if (m_limitState == e_atLowerLimit) - { - m_impulse.z = b2Max(m_impulse.z, 0.0f); - } - else if (m_limitState == e_atUpperLimit) - { - m_impulse.z = b2Min(m_impulse.z, 0.0f); - } - - // f2(1:2) = invK(1:2,1:2) * (-Cdot(1:2) - K(1:2,3) * (f2(3) - f1(3))) + f1(1:2) - b2Vec2 b = -Cdot1 - (m_impulse.z - f1.z) * b2Vec2(m_K.ez.x, m_K.ez.y); - b2Vec2 f2r = m_K.Solve22(b) + b2Vec2(f1.x, f1.y); - m_impulse.x = f2r.x; - m_impulse.y = f2r.y; - - df = m_impulse - f1; - - b2Vec2 P = df.x * m_perp + df.z * m_axis; - float32 LA = df.x * m_s1 + df.y + df.z * m_a1; - float32 LB = df.x * m_s2 + df.y + df.z * m_a2; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - else - { - // Limit is inactive, just solve the prismatic constraint in block form. - b2Vec2 df = m_K.Solve22(-Cdot1); - m_impulse.x += df.x; - m_impulse.y += df.y; - - b2Vec2 P = df.x * m_perp; - float32 LA = df.x * m_s1 + df.y; - float32 LB = df.x * m_s2 + df.y; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -// A velocity based solver computes reaction forces(impulses) using the velocity constraint solver.Under this context, -// the position solver is not there to resolve forces.It is only there to cope with integration error. -// -// Therefore, the pseudo impulses in the position solver do not have any physical meaning.Thus it is okay if they suck. -// -// We could take the active state from the velocity solver.However, the joint might push past the limit when the velocity -// solver indicates the limit is inactive. -bool b2PrismaticJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - // Compute fresh Jacobians - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = cB + rB - cA - rA; - - b2Vec2 axis = b2Mul(qA, m_localXAxisA); - float32 a1 = b2Cross(d + rA, axis); - float32 a2 = b2Cross(rB, axis); - b2Vec2 perp = b2Mul(qA, m_localYAxisA); - - float32 s1 = b2Cross(d + rA, perp); - float32 s2 = b2Cross(rB, perp); - - b2Vec3 impulse; - b2Vec2 C1; - C1.x = b2Dot(perp, d); - C1.y = aB - aA - m_referenceAngle; - - float32 linearError = b2Abs(C1.x); - float32 angularError = b2Abs(C1.y); - - bool active = false; - float32 C2 = 0.0f; - if (m_enableLimit) - { - float32 translation = b2Dot(axis, d); - if (b2Abs(m_upperTranslation - m_lowerTranslation) < 2.0f * b2_linearSlop) - { - // Prevent large angular corrections - C2 = b2Clamp(translation, -b2_maxLinearCorrection, b2_maxLinearCorrection); - linearError = b2Max(linearError, b2Abs(translation)); - active = true; - } - else if (translation <= m_lowerTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_lowerTranslation + b2_linearSlop, -b2_maxLinearCorrection, 0.0f); - linearError = b2Max(linearError, m_lowerTranslation - translation); - active = true; - } - else if (translation >= m_upperTranslation) - { - // Prevent large linear corrections and allow some slop. - C2 = b2Clamp(translation - m_upperTranslation - b2_linearSlop, 0.0f, b2_maxLinearCorrection); - linearError = b2Max(linearError, translation - m_upperTranslation); - active = true; - } - } - - if (active) - { - float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; - float32 k12 = iA * s1 + iB * s2; - float32 k13 = iA * s1 * a1 + iB * s2 * a2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - // For fixed rotation - k22 = 1.0f; - } - float32 k23 = iA * a1 + iB * a2; - float32 k33 = mA + mB + iA * a1 * a1 + iB * a2 * a2; - - b2Mat33 K; - K.ex.Set(k11, k12, k13); - K.ey.Set(k12, k22, k23); - K.ez.Set(k13, k23, k33); - - b2Vec3 C; - C.x = C1.x; - C.y = C1.y; - C.z = C2; - - impulse = K.Solve33(-C); - } - else - { - float32 k11 = mA + mB + iA * s1 * s1 + iB * s2 * s2; - float32 k12 = iA * s1 + iB * s2; - float32 k22 = iA + iB; - if (k22 == 0.0f) - { - k22 = 1.0f; - } - - b2Mat22 K; - K.ex.Set(k11, k12); - K.ey.Set(k12, k22); - - b2Vec2 impulse1 = K.Solve(-C1); - impulse.x = impulse1.x; - impulse.y = impulse1.y; - impulse.z = 0.0f; - } - - b2Vec2 P = impulse.x * perp + impulse.z * axis; - float32 LA = impulse.x * s1 + impulse.y + impulse.z * a1; - float32 LB = impulse.x * s2 + impulse.y + impulse.z * a2; - - cA -= mA * P; - aA -= iA * LA; - cB += mB * P; - aB += iB * LB; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return linearError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2PrismaticJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2PrismaticJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2PrismaticJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * (m_impulse.x * m_perp + (m_motorImpulse + m_impulse.z) * m_axis); -} - -float32 b2PrismaticJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.y; -} - -float32 b2PrismaticJoint::GetJointTranslation() const -{ - b2Vec2 pA = m_bodyA->GetWorldPoint(m_localAnchorA); - b2Vec2 pB = m_bodyB->GetWorldPoint(m_localAnchorB); - b2Vec2 d = pB - pA; - b2Vec2 axis = m_bodyA->GetWorldVector(m_localXAxisA); - - float32 translation = b2Dot(d, axis); - return translation; -} - -float32 b2PrismaticJoint::GetJointSpeed() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - - b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); - b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); - b2Vec2 p1 = bA->m_sweep.c + rA; - b2Vec2 p2 = bB->m_sweep.c + rB; - b2Vec2 d = p2 - p1; - b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); - - b2Vec2 vA = bA->m_linearVelocity; - b2Vec2 vB = bB->m_linearVelocity; - float32 wA = bA->m_angularVelocity; - float32 wB = bB->m_angularVelocity; - - float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); - return speed; -} - -bool b2PrismaticJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2PrismaticJoint::EnableLimit(bool flag) -{ - if (flag != m_enableLimit) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; - m_impulse.z = 0.0f; - } -} - -float32 b2PrismaticJoint::GetLowerLimit() const -{ - return m_lowerTranslation; -} - -float32 b2PrismaticJoint::GetUpperLimit() const -{ - return m_upperTranslation; -} - -void b2PrismaticJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - if (lower != m_lowerTranslation || upper != m_upperTranslation) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_lowerTranslation = lower; - m_upperTranslation = upper; - m_impulse.z = 0.0f; - } -} - -bool b2PrismaticJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2PrismaticJoint::EnableMotor(bool flag) -{ - if (flag != m_enableMotor) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; - } -} - -void b2PrismaticJoint::SetMotorSpeed(float32 speed) -{ - if (speed != m_motorSpeed) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; - } -} - -void b2PrismaticJoint::SetMaxMotorForce(float32 force) -{ - if (force != m_maxMotorForce) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorForce = force; - } -} - -float32 b2PrismaticJoint::GetMotorForce(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2PrismaticJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2PrismaticJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); - b2Log(" jd.lowerTranslation = %.15lef;\n", m_lowerTranslation); - b2Log(" jd.upperTranslation = %.15lef;\n", m_upperTranslation); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorForce = %.15lef;\n", m_maxMotorForce); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2PrismaticJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2PrismaticJoint.h deleted file mode 100644 index 131dffd..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2PrismaticJoint.h +++ /dev/null @@ -1,196 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_PRISMATIC_JOINT_H -#define B2_PRISMATIC_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Prismatic joint definition. This requires defining a line of -/// motion using an axis and an anchor point. The definition uses local -/// anchor points and a local axis so that the initial configuration -/// can violate the constraint slightly. The joint translation is zero -/// when the local anchor points coincide in world space. Using local -/// anchors and a local axis helps when saving and loading a game. -struct b2PrismaticJointDef : public b2JointDef -{ - b2PrismaticJointDef() - { - type = e_prismaticJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - referenceAngle = 0.0f; - enableLimit = false; - lowerTranslation = 0.0f; - upperTranslation = 0.0f; - enableMotor = false; - maxMotorForce = 0.0f; - motorSpeed = 0.0f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and unit world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The local translation unit axis in bodyA. - b2Vec2 localAxisA; - - /// The constrained angle between the bodies: bodyB_angle - bodyA_angle. - float32 referenceAngle; - - /// Enable/disable the joint limit. - bool enableLimit; - - /// The lower translation limit, usually in meters. - float32 lowerTranslation; - - /// The upper translation limit, usually in meters. - float32 upperTranslation; - - /// Enable/disable the joint motor. - bool enableMotor; - - /// The maximum motor torque, usually in N-m. - float32 maxMotorForce; - - /// The desired motor speed in radians per second. - float32 motorSpeed; -}; - -/// A prismatic joint. This joint provides one degree of freedom: translation -/// along an axis fixed in bodyA. Relative rotation is prevented. You can -/// use a joint limit to restrict the range of motion and a joint motor to -/// drive the motion or to model joint friction. -class b2PrismaticJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - b2Vec2 GetReactionForce(float32 inv_dt) const override; - float32 GetReactionTorque(float32 inv_dt) const override; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// The local joint axis relative to bodyA. - const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; - - /// Get the current joint translation speed, usually in meters per second. - float32 GetJointSpeed() const; - - /// Is the joint limit enabled? - bool IsLimitEnabled() const; - - /// Enable/disable the joint limit. - void EnableLimit(bool flag); - - /// Get the lower joint limit, usually in meters. - float32 GetLowerLimit() const; - - /// Get the upper joint limit, usually in meters. - float32 GetUpperLimit() const; - - /// Set the joint limits, usually in meters. - void SetLimits(float32 lower, float32 upper); - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed, usually in meters per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed, usually in meters per second. - float32 GetMotorSpeed() const; - - /// Set the maximum motor force, usually in N. - void SetMaxMotorForce(float32 force); - float32 GetMaxMotorForce() const { return m_maxMotorForce; } - - /// Get the current motor force given the inverse time step, usually in N. - float32 GetMotorForce(float32 inv_dt) const; - - /// Dump to b2Log - void Dump() override; - -protected: - friend class b2Joint; - friend class b2GearJoint; - b2PrismaticJoint(const b2PrismaticJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localXAxisA; - b2Vec2 m_localYAxisA; - float32 m_referenceAngle; - b2Vec3 m_impulse; - float32 m_motorImpulse; - float32 m_lowerTranslation; - float32 m_upperTranslation; - float32 m_maxMotorForce; - float32 m_motorSpeed; - bool m_enableLimit; - bool m_enableMotor; - b2LimitState m_limitState; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Vec2 m_axis, m_perp; - float32 m_s1, m_s2; - float32 m_a1, m_a2; - b2Mat33 m_K; - float32 m_motorMass; -}; - -inline float32 b2PrismaticJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2PulleyJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2PulleyJoint.cpp deleted file mode 100644 index 1525f41..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2PulleyJoint.cpp +++ /dev/null @@ -1,348 +0,0 @@ -/* -* Copyright (c) 2007 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2PulleyJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// Pulley: -// length1 = norm(p1 - s1) -// length2 = norm(p2 - s2) -// C0 = (length1 + ratio * length2)_initial -// C = C0 - (length1 + ratio * length2) -// u1 = (p1 - s1) / norm(p1 - s1) -// u2 = (p2 - s2) / norm(p2 - s2) -// Cdot = -dot(u1, v1 + cross(w1, r1)) - ratio * dot(u2, v2 + cross(w2, r2)) -// J = -[u1 cross(r1, u1) ratio * u2 ratio * cross(r2, u2)] -// K = J * invM * JT -// = invMass1 + invI1 * cross(r1, u1)^2 + ratio^2 * (invMass2 + invI2 * cross(r2, u2)^2) - -void b2PulleyJointDef::Initialize(b2Body* bA, b2Body* bB, - const b2Vec2& groundA, const b2Vec2& groundB, - const b2Vec2& anchorA, const b2Vec2& anchorB, - float32 r) -{ - bodyA = bA; - bodyB = bB; - groundAnchorA = groundA; - groundAnchorB = groundB; - localAnchorA = bodyA->GetLocalPoint(anchorA); - localAnchorB = bodyB->GetLocalPoint(anchorB); - b2Vec2 dA = anchorA - groundA; - lengthA = dA.Length(); - b2Vec2 dB = anchorB - groundB; - lengthB = dB.Length(); - ratio = r; - b2Assert(ratio > b2_epsilon); -} - -b2PulleyJoint::b2PulleyJoint(const b2PulleyJointDef* def) -: b2Joint(def) -{ - m_groundAnchorA = def->groundAnchorA; - m_groundAnchorB = def->groundAnchorB; - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_lengthA = def->lengthA; - m_lengthB = def->lengthB; - - b2Assert(def->ratio != 0.0f); - m_ratio = def->ratio; - - m_constant = def->lengthA + m_ratio * def->lengthB; - - m_impulse = 0.0f; -} - -void b2PulleyJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // Get the pulley axes. - m_uA = cA + m_rA - m_groundAnchorA; - m_uB = cB + m_rB - m_groundAnchorB; - - float32 lengthA = m_uA.Length(); - float32 lengthB = m_uB.Length(); - - if (lengthA > 10.0f * b2_linearSlop) - { - m_uA *= 1.0f / lengthA; - } - else - { - m_uA.SetZero(); - } - - if (lengthB > 10.0f * b2_linearSlop) - { - m_uB *= 1.0f / lengthB; - } - else - { - m_uB.SetZero(); - } - - // Compute effective mass. - float32 ruA = b2Cross(m_rA, m_uA); - float32 ruB = b2Cross(m_rB, m_uB); - - float32 mA = m_invMassA + m_invIA * ruA * ruA; - float32 mB = m_invMassB + m_invIB * ruB * ruB; - - m_mass = mA + m_ratio * m_ratio * mB; - - if (m_mass > 0.0f) - { - m_mass = 1.0f / m_mass; - } - - if (data.step.warmStarting) - { - // Scale impulses to support variable time steps. - m_impulse *= data.step.dtRatio; - - // Warm starting. - b2Vec2 PA = -(m_impulse) * m_uA; - b2Vec2 PB = (-m_ratio * m_impulse) * m_uB; - - vA += m_invMassA * PA; - wA += m_invIA * b2Cross(m_rA, PA); - vB += m_invMassB * PB; - wB += m_invIB * b2Cross(m_rB, PB); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2PulleyJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - - float32 Cdot = -b2Dot(m_uA, vpA) - m_ratio * b2Dot(m_uB, vpB); - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - b2Vec2 PA = -impulse * m_uA; - b2Vec2 PB = -m_ratio * impulse * m_uB; - vA += m_invMassA * PA; - wA += m_invIA * b2Cross(m_rA, PA); - vB += m_invMassB * PB; - wB += m_invIB * b2Cross(m_rB, PB); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2PulleyJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // Get the pulley axes. - b2Vec2 uA = cA + rA - m_groundAnchorA; - b2Vec2 uB = cB + rB - m_groundAnchorB; - - float32 lengthA = uA.Length(); - float32 lengthB = uB.Length(); - - if (lengthA > 10.0f * b2_linearSlop) - { - uA *= 1.0f / lengthA; - } - else - { - uA.SetZero(); - } - - if (lengthB > 10.0f * b2_linearSlop) - { - uB *= 1.0f / lengthB; - } - else - { - uB.SetZero(); - } - - // Compute effective mass. - float32 ruA = b2Cross(rA, uA); - float32 ruB = b2Cross(rB, uB); - - float32 mA = m_invMassA + m_invIA * ruA * ruA; - float32 mB = m_invMassB + m_invIB * ruB * ruB; - - float32 mass = mA + m_ratio * m_ratio * mB; - - if (mass > 0.0f) - { - mass = 1.0f / mass; - } - - float32 C = m_constant - lengthA - m_ratio * lengthB; - float32 linearError = b2Abs(C); - - float32 impulse = -mass * C; - - b2Vec2 PA = -impulse * uA; - b2Vec2 PB = -m_ratio * impulse * uB; - - cA += m_invMassA * PA; - aA += m_invIA * b2Cross(rA, PA); - cB += m_invMassB * PB; - aB += m_invIB * b2Cross(rB, PB); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return linearError < b2_linearSlop; -} - -b2Vec2 b2PulleyJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2PulleyJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2PulleyJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P = m_impulse * m_uB; - return inv_dt * P; -} - -float32 b2PulleyJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -b2Vec2 b2PulleyJoint::GetGroundAnchorA() const -{ - return m_groundAnchorA; -} - -b2Vec2 b2PulleyJoint::GetGroundAnchorB() const -{ - return m_groundAnchorB; -} - -float32 b2PulleyJoint::GetLengthA() const -{ - return m_lengthA; -} - -float32 b2PulleyJoint::GetLengthB() const -{ - return m_lengthB; -} - -float32 b2PulleyJoint::GetRatio() const -{ - return m_ratio; -} - -float32 b2PulleyJoint::GetCurrentLengthA() const -{ - b2Vec2 p = m_bodyA->GetWorldPoint(m_localAnchorA); - b2Vec2 s = m_groundAnchorA; - b2Vec2 d = p - s; - return d.Length(); -} - -float32 b2PulleyJoint::GetCurrentLengthB() const -{ - b2Vec2 p = m_bodyB->GetWorldPoint(m_localAnchorB); - b2Vec2 s = m_groundAnchorB; - b2Vec2 d = p - s; - return d.Length(); -} - -void b2PulleyJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2PulleyJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.groundAnchorA.Set(%.15lef, %.15lef);\n", m_groundAnchorA.x, m_groundAnchorA.y); - b2Log(" jd.groundAnchorB.Set(%.15lef, %.15lef);\n", m_groundAnchorB.x, m_groundAnchorB.y); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.lengthA = %.15lef;\n", m_lengthA); - b2Log(" jd.lengthB = %.15lef;\n", m_lengthB); - b2Log(" jd.ratio = %.15lef;\n", m_ratio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} - -void b2PulleyJoint::ShiftOrigin(const b2Vec2& newOrigin) -{ - m_groundAnchorA -= newOrigin; - m_groundAnchorB -= newOrigin; -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2PulleyJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2PulleyJoint.h deleted file mode 100644 index 71c759b..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2PulleyJoint.h +++ /dev/null @@ -1,152 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_PULLEY_JOINT_H -#define B2_PULLEY_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -const float32 b2_minPulleyLength = 2.0f; - -/// Pulley joint definition. This requires two ground anchors, -/// two dynamic body anchor points, and a pulley ratio. -struct b2PulleyJointDef : public b2JointDef -{ - b2PulleyJointDef() - { - type = e_pulleyJoint; - groundAnchorA.Set(-1.0f, 1.0f); - groundAnchorB.Set(1.0f, 1.0f); - localAnchorA.Set(-1.0f, 0.0f); - localAnchorB.Set(1.0f, 0.0f); - lengthA = 0.0f; - lengthB = 0.0f; - ratio = 1.0f; - collideConnected = true; - } - - /// Initialize the bodies, anchors, lengths, max lengths, and ratio using the world anchors. - void Initialize(b2Body* bodyA, b2Body* bodyB, - const b2Vec2& groundAnchorA, const b2Vec2& groundAnchorB, - const b2Vec2& anchorA, const b2Vec2& anchorB, - float32 ratio); - - /// The first ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchorA; - - /// The second ground anchor in world coordinates. This point never moves. - b2Vec2 groundAnchorB; - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The a reference length for the segment attached to bodyA. - float32 lengthA; - - /// The a reference length for the segment attached to bodyB. - float32 lengthB; - - /// The pulley ratio, used to simulate a block-and-tackle. - float32 ratio; -}; - -/// The pulley joint is connected to two bodies and two fixed ground points. -/// The pulley supports a ratio such that: -/// length1 + ratio * length2 <= constant -/// Yes, the force transmitted is scaled by the ratio. -/// Warning: the pulley joint can get a bit squirrelly by itself. They often -/// work better when combined with prismatic joints. You should also cover the -/// the anchor points with static shapes to prevent one side from going to -/// zero length. -class b2PulleyJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - b2Vec2 GetReactionForce(float32 inv_dt) const override; - float32 GetReactionTorque(float32 inv_dt) const override; - - /// Get the first ground anchor. - b2Vec2 GetGroundAnchorA() const; - - /// Get the second ground anchor. - b2Vec2 GetGroundAnchorB() const; - - /// Get the current length of the segment attached to bodyA. - float32 GetLengthA() const; - - /// Get the current length of the segment attached to bodyB. - float32 GetLengthB() const; - - /// Get the pulley ratio. - float32 GetRatio() const; - - /// Get the current length of the segment attached to bodyA. - float32 GetCurrentLengthA() const; - - /// Get the current length of the segment attached to bodyB. - float32 GetCurrentLengthB() const; - - /// Dump joint to dmLog - void Dump() override; - - /// Implement b2Joint::ShiftOrigin - void ShiftOrigin(const b2Vec2& newOrigin) override; - -protected: - - friend class b2Joint; - b2PulleyJoint(const b2PulleyJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - b2Vec2 m_groundAnchorA; - b2Vec2 m_groundAnchorB; - float32 m_lengthA; - float32 m_lengthB; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_constant; - float32 m_ratio; - float32 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_uA; - b2Vec2 m_uB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp deleted file mode 100644 index b3f7ee5..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2RevoluteJoint.cpp +++ /dev/null @@ -1,511 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2RevoluteJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// Point-to-point constraint -// C = p2 - p1 -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Motor constraint -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2RevoluteJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2RevoluteJoint::b2RevoluteJoint(const b2RevoluteJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_referenceAngle = def->referenceAngle; - - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - - m_lowerAngle = def->lowerAngle; - m_upperAngle = def->upperAngle; - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableLimit = def->enableLimit; - m_enableMotor = def->enableMotor; - m_limitState = e_inactiveLimit; -} - -void b2RevoluteJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - bool fixedRotation = (iA + iB == 0.0f); - - m_mass.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - m_mass.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - m_mass.ez.x = -m_rA.y * iA - m_rB.y * iB; - m_mass.ex.y = m_mass.ey.x; - m_mass.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - m_mass.ez.y = m_rA.x * iA + m_rB.x * iB; - m_mass.ex.z = m_mass.ez.x; - m_mass.ey.z = m_mass.ez.y; - m_mass.ez.z = iA + iB; - - m_motorMass = iA + iB; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - - if (m_enableMotor == false || fixedRotation) - { - m_motorImpulse = 0.0f; - } - - if (m_enableLimit && fixedRotation == false) - { - float32 jointAngle = aB - aA - m_referenceAngle; - if (b2Abs(m_upperAngle - m_lowerAngle) < 2.0f * b2_angularSlop) - { - m_limitState = e_equalLimits; - } - else if (jointAngle <= m_lowerAngle) - { - if (m_limitState != e_atLowerLimit) - { - m_impulse.z = 0.0f; - } - m_limitState = e_atLowerLimit; - } - else if (jointAngle >= m_upperAngle) - { - if (m_limitState != e_atUpperLimit) - { - m_impulse.z = 0.0f; - } - m_limitState = e_atUpperLimit; - } - else - { - m_limitState = e_inactiveLimit; - m_impulse.z = 0.0f; - } - } - else - { - m_limitState = e_inactiveLimit; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_impulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P(m_impulse.x, m_impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_motorImpulse + m_impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_motorImpulse + m_impulse.z); - } - else - { - m_impulse.SetZero(); - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2RevoluteJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - bool fixedRotation = (iA + iB == 0.0f); - - // Solve motor constraint. - if (m_enableMotor && m_limitState != e_equalLimits && fixedRotation == false) - { - float32 Cdot = wB - wA - m_motorSpeed; - float32 impulse = -m_motorMass * Cdot; - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorTorque; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) - { - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 impulse = -m_mass.Solve33(Cdot); - - if (m_limitState == e_equalLimits) - { - m_impulse += impulse; - } - else if (m_limitState == e_atLowerLimit) - { - float32 newImpulse = m_impulse.z + impulse.z; - if (newImpulse < 0.0f) - { - b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); - b2Vec2 reduced = m_mass.Solve22(rhs); - impulse.x = reduced.x; - impulse.y = reduced.y; - impulse.z = -m_impulse.z; - m_impulse.x += reduced.x; - m_impulse.y += reduced.y; - m_impulse.z = 0.0f; - } - else - { - m_impulse += impulse; - } - } - else if (m_limitState == e_atUpperLimit) - { - float32 newImpulse = m_impulse.z + impulse.z; - if (newImpulse > 0.0f) - { - b2Vec2 rhs = -Cdot1 + m_impulse.z * b2Vec2(m_mass.ez.x, m_mass.ez.y); - b2Vec2 reduced = m_mass.Solve22(rhs); - impulse.x = reduced.x; - impulse.y = reduced.y; - impulse.z = -m_impulse.z; - m_impulse.x += reduced.x; - m_impulse.y += reduced.y; - m_impulse.z = 0.0f; - } - else - { - m_impulse += impulse; - } - } - - b2Vec2 P(impulse.x, impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); - } - else - { - // Solve point-to-point constraint - b2Vec2 Cdot = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - b2Vec2 impulse = m_mass.Solve22(-Cdot); - - m_impulse.x += impulse.x; - m_impulse.y += impulse.y; - - vA -= mA * impulse; - wA -= iA * b2Cross(m_rA, impulse); - - vB += mB * impulse; - wB += iB * b2Cross(m_rB, impulse); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2RevoluteJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 angularError = 0.0f; - float32 positionError = 0.0f; - - bool fixedRotation = (m_invIA + m_invIB == 0.0f); - - // Solve angular limit constraint. - if (m_enableLimit && m_limitState != e_inactiveLimit && fixedRotation == false) - { - float32 angle = aB - aA - m_referenceAngle; - float32 limitImpulse = 0.0f; - - if (m_limitState == e_equalLimits) - { - // Prevent large angular corrections - float32 C = b2Clamp(angle - m_lowerAngle, -b2_maxAngularCorrection, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * C; - angularError = b2Abs(C); - } - else if (m_limitState == e_atLowerLimit) - { - float32 C = angle - m_lowerAngle; - angularError = -C; - - // Prevent large angular corrections and allow some slop. - C = b2Clamp(C + b2_angularSlop, -b2_maxAngularCorrection, 0.0f); - limitImpulse = -m_motorMass * C; - } - else if (m_limitState == e_atUpperLimit) - { - float32 C = angle - m_upperAngle; - angularError = C; - - // Prevent large angular corrections and allow some slop. - C = b2Clamp(C - b2_angularSlop, 0.0f, b2_maxAngularCorrection); - limitImpulse = -m_motorMass * C; - } - - aA -= m_invIA * limitImpulse; - aB += m_invIB * limitImpulse; - } - - // Solve point-to-point constraint. - { - qA.Set(aA); - qB.Set(aB); - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - b2Vec2 C = cB + rB - cA - rA; - positionError = C.Length(); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat22 K; - K.ex.x = mA + mB + iA * rA.y * rA.y + iB * rB.y * rB.y; - K.ex.y = -iA * rA.x * rA.y - iB * rB.x * rB.y; - K.ey.x = K.ex.y; - K.ey.y = mA + mB + iA * rA.x * rA.x + iB * rB.x * rB.x; - - b2Vec2 impulse = -K.Solve(C); - - cA -= mA * impulse; - aA -= iA * b2Cross(rA, impulse); - - cB += mB * impulse; - aB += iB * b2Cross(rB, impulse); - } - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2RevoluteJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2RevoluteJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2RevoluteJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P(m_impulse.x, m_impulse.y); - return inv_dt * P; -} - -float32 b2RevoluteJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.z; -} - -float32 b2RevoluteJoint::GetJointAngle() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_sweep.a - bA->m_sweep.a - m_referenceAngle; -} - -float32 b2RevoluteJoint::GetJointSpeed() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_angularVelocity - bA->m_angularVelocity; -} - -bool b2RevoluteJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2RevoluteJoint::EnableMotor(bool flag) -{ - if (flag != m_enableMotor) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; - } -} - -float32 b2RevoluteJoint::GetMotorTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2RevoluteJoint::SetMotorSpeed(float32 speed) -{ - if (speed != m_motorSpeed) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; - } -} - -void b2RevoluteJoint::SetMaxMotorTorque(float32 torque) -{ - if (torque != m_maxMotorTorque) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorTorque = torque; - } -} - -bool b2RevoluteJoint::IsLimitEnabled() const -{ - return m_enableLimit; -} - -void b2RevoluteJoint::EnableLimit(bool flag) -{ - if (flag != m_enableLimit) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableLimit = flag; - m_impulse.z = 0.0f; - } -} - -float32 b2RevoluteJoint::GetLowerLimit() const -{ - return m_lowerAngle; -} - -float32 b2RevoluteJoint::GetUpperLimit() const -{ - return m_upperAngle; -} - -void b2RevoluteJoint::SetLimits(float32 lower, float32 upper) -{ - b2Assert(lower <= upper); - - if (lower != m_lowerAngle || upper != m_upperAngle) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_impulse.z = 0.0f; - m_lowerAngle = lower; - m_upperAngle = upper; - } -} - -void b2RevoluteJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2RevoluteJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.enableLimit = bool(%d);\n", m_enableLimit); - b2Log(" jd.lowerAngle = %.15lef;\n", m_lowerAngle); - b2Log(" jd.upperAngle = %.15lef;\n", m_upperAngle); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2RevoluteJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2RevoluteJoint.h deleted file mode 100644 index 06b1455..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2RevoluteJoint.h +++ /dev/null @@ -1,204 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_REVOLUTE_JOINT_H -#define B2_REVOLUTE_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Revolute joint definition. This requires defining an -/// anchor point where the bodies are joined. The definition -/// uses local anchor points so that the initial configuration -/// can violate the constraint slightly. You also need to -/// specify the initial relative angle for joint limits. This -/// helps when saving and loading a game. -/// The local anchor points are measured from the body's origin -/// rather than the center of mass because: -/// 1. you might not know where the center of mass will be. -/// 2. if you add/remove shapes from a body and recompute the mass, -/// the joints will be broken. -struct b2RevoluteJointDef : public b2JointDef -{ - b2RevoluteJointDef() - { - type = e_revoluteJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - referenceAngle = 0.0f; - lowerAngle = 0.0f; - upperAngle = 0.0f; - maxMotorTorque = 0.0f; - motorSpeed = 0.0f; - enableLimit = false; - enableMotor = false; - } - - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The bodyB angle minus bodyA angle in the reference state (radians). - float32 referenceAngle; - - /// A flag to enable joint limits. - bool enableLimit; - - /// The lower angle for the joint limit (radians). - float32 lowerAngle; - - /// The upper angle for the joint limit (radians). - float32 upperAngle; - - /// A flag to enable the joint motor. - bool enableMotor; - - /// The desired motor speed. Usually in radians per second. - float32 motorSpeed; - - /// The maximum motor torque used to achieve the desired motor speed. - /// Usually in N-m. - float32 maxMotorTorque; -}; - -/// A revolute joint constrains two bodies to share a common point while they -/// are free to rotate about the point. The relative rotation about the shared -/// point is the joint angle. You can limit the relative rotation with -/// a joint limit that specifies a lower and upper angle. You can use a motor -/// to drive the relative rotation about the shared point. A maximum motor torque -/// is provided so that infinite forces are not generated. -class b2RevoluteJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Get the current joint angle in radians. - float32 GetJointAngle() const; - - /// Get the current joint angle speed in radians per second. - float32 GetJointSpeed() const; - - /// Is the joint limit enabled? - bool IsLimitEnabled() const; - - /// Enable/disable the joint limit. - void EnableLimit(bool flag); - - /// Get the lower joint limit in radians. - float32 GetLowerLimit() const; - - /// Get the upper joint limit in radians. - float32 GetUpperLimit() const; - - /// Set the joint limits in radians. - void SetLimits(float32 lower, float32 upper); - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed in radians per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed in radians per second. - float32 GetMotorSpeed() const; - - /// Set the maximum motor torque, usually in N-m. - void SetMaxMotorTorque(float32 torque); - float32 GetMaxMotorTorque() const { return m_maxMotorTorque; } - - /// Get the reaction force given the inverse time step. - /// Unit is N. - b2Vec2 GetReactionForce(float32 inv_dt) const override; - - /// Get the reaction torque due to the joint limit given the inverse time step. - /// Unit is N*m. - float32 GetReactionTorque(float32 inv_dt) const override; - - /// Get the current motor torque given the inverse time step. - /// Unit is N*m. - float32 GetMotorTorque(float32 inv_dt) const; - - /// Dump to b2Log. - void Dump() override; - -protected: - - friend class b2Joint; - friend class b2GearJoint; - - b2RevoluteJoint(const b2RevoluteJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec3 m_impulse; - float32 m_motorImpulse; - - bool m_enableMotor; - float32 m_maxMotorTorque; - float32 m_motorSpeed; - - bool m_enableLimit; - float32 m_referenceAngle; - float32 m_lowerAngle; - float32 m_upperAngle; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat33 m_mass; // effective mass for point-to-point constraint. - float32 m_motorMass; // effective mass for motor/limit angular constraint. - b2LimitState m_limitState; -}; - -inline float32 b2RevoluteJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2RopeJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2RopeJoint.cpp deleted file mode 100644 index 86d27e7..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2RopeJoint.cpp +++ /dev/null @@ -1,241 +0,0 @@ -/* -* Copyright (c) 2007-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2RopeJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - - -// Limit: -// C = norm(pB - pA) - L -// u = (pB - pA) / norm(pB - pA) -// Cdot = dot(u, vB + cross(wB, rB) - vA - cross(wA, rA)) -// J = [-u -cross(rA, u) u cross(rB, u)] -// K = J * invM * JT -// = invMassA + invIA * cross(rA, u)^2 + invMassB + invIB * cross(rB, u)^2 - -b2RopeJoint::b2RopeJoint(const b2RopeJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - - m_maxLength = def->maxLength; - - m_mass = 0.0f; - m_impulse = 0.0f; - m_state = e_inactiveLimit; - m_length = 0.0f; -} - -void b2RopeJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - m_u = cB + m_rB - cA - m_rA; - - m_length = m_u.Length(); - - float32 C = m_length - m_maxLength; - if (C > 0.0f) - { - m_state = e_atUpperLimit; - } - else - { - m_state = e_inactiveLimit; - } - - if (m_length > b2_linearSlop) - { - m_u *= 1.0f / m_length; - } - else - { - m_u.SetZero(); - m_mass = 0.0f; - m_impulse = 0.0f; - return; - } - - // Compute effective mass. - float32 crA = b2Cross(m_rA, m_u); - float32 crB = b2Cross(m_rB, m_u); - float32 invMass = m_invMassA + m_invIA * crA * crA + m_invMassB + m_invIB * crB * crB; - - m_mass = invMass != 0.0f ? 1.0f / invMass : 0.0f; - - if (data.step.warmStarting) - { - // Scale the impulse to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - } - else - { - m_impulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2RopeJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Cdot = dot(u, v + cross(w, r)) - b2Vec2 vpA = vA + b2Cross(wA, m_rA); - b2Vec2 vpB = vB + b2Cross(wB, m_rB); - float32 C = m_length - m_maxLength; - float32 Cdot = b2Dot(m_u, vpB - vpA); - - // Predictive constraint. - if (C < 0.0f) - { - Cdot += data.step.inv_dt * C; - } - - float32 impulse = -m_mass * Cdot; - float32 oldImpulse = m_impulse; - m_impulse = b2Min(0.0f, m_impulse + impulse); - impulse = m_impulse - oldImpulse; - - b2Vec2 P = impulse * m_u; - vA -= m_invMassA * P; - wA -= m_invIA * b2Cross(m_rA, P); - vB += m_invMassB * P; - wB += m_invIB * b2Cross(m_rB, P); - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2RopeJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 u = cB + rB - cA - rA; - - float32 length = u.Normalize(); - float32 C = length - m_maxLength; - - C = b2Clamp(C, 0.0f, b2_maxLinearCorrection); - - float32 impulse = -m_mass * C; - b2Vec2 P = impulse * u; - - cA -= m_invMassA * P; - aA -= m_invIA * b2Cross(rA, P); - cB += m_invMassB * P; - aB += m_invIB * b2Cross(rB, P); - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return length - m_maxLength < b2_linearSlop; -} - -b2Vec2 b2RopeJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2RopeJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2RopeJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 F = (inv_dt * m_impulse) * m_u; - return F; -} - -float32 b2RopeJoint::GetReactionTorque(float32 inv_dt) const -{ - B2_NOT_USED(inv_dt); - return 0.0f; -} - -float32 b2RopeJoint::GetMaxLength() const -{ - return m_maxLength; -} - -b2LimitState b2RopeJoint::GetLimitState() const -{ - return m_state; -} - -void b2RopeJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2RopeJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.maxLength = %.15lef;\n", m_maxLength); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2RopeJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2RopeJoint.h deleted file mode 100644 index ef5d6f7..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2RopeJoint.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_ROPE_JOINT_H -#define B2_ROPE_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Rope joint definition. This requires two body anchor points and -/// a maximum lengths. -/// Note: by default the connected objects will not collide. -/// see collideConnected in b2JointDef. -struct b2RopeJointDef : public b2JointDef -{ - b2RopeJointDef() - { - type = e_ropeJoint; - localAnchorA.Set(-1.0f, 0.0f); - localAnchorB.Set(1.0f, 0.0f); - maxLength = 0.0f; - } - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The maximum length of the rope. - /// Warning: this must be larger than b2_linearSlop or - /// the joint will have no effect. - float32 maxLength; -}; - -/// A rope joint enforces a maximum distance between two points -/// on two bodies. It has no other effect. -/// Warning: if you attempt to change the maximum length during -/// the simulation you will get some non-physical behavior. -/// A model that would allow you to dynamically modify the length -/// would have some sponginess, so I chose not to implement it -/// that way. See b2DistanceJoint if you want to dynamically -/// control length. -class b2RopeJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - b2Vec2 GetReactionForce(float32 inv_dt) const override; - float32 GetReactionTorque(float32 inv_dt) const override; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Set/Get the maximum length of the rope. - void SetMaxLength(float32 length) { m_maxLength = length; } - float32 GetMaxLength() const; - - b2LimitState GetLimitState() const; - - /// Dump joint to dmLog - void Dump() override; - -protected: - - friend class b2Joint; - b2RopeJoint(const b2RopeJointDef* data); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_maxLength; - float32 m_length; - float32 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_u; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - float32 m_mass; - b2LimitState m_state; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2WeldJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2WeldJoint.cpp deleted file mode 100644 index b10cee8..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2WeldJoint.cpp +++ /dev/null @@ -1,344 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2WeldJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// Point-to-point constraint -// C = p2 - p1 -// Cdot = v2 - v1 -// = v2 + cross(w2, r2) - v1 - cross(w1, r1) -// J = [-I -r1_skew I r2_skew ] -// Identity used: -// w k % (rx i + ry j) = w * (-ry i + rx j) - -// Angle constraint -// C = angle2 - angle1 - referenceAngle -// Cdot = w2 - w1 -// J = [0 0 -1 0 0 1] -// K = invI1 + invI2 - -void b2WeldJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - referenceAngle = bodyB->GetAngle() - bodyA->GetAngle(); -} - -b2WeldJoint::b2WeldJoint(const b2WeldJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_referenceAngle = def->referenceAngle; - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_impulse.SetZero(); -} - -void b2WeldJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - m_rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - m_rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - // J = [-I -r1_skew I r2_skew] - // [ 0 -1 0 1] - // r_skew = [-ry; rx] - - // Matlab - // K = [ mA+r1y^2*iA+mB+r2y^2*iB, -r1y*iA*r1x-r2y*iB*r2x, -r1y*iA-r2y*iB] - // [ -r1y*iA*r1x-r2y*iB*r2x, mA+r1x^2*iA+mB+r2x^2*iB, r1x*iA+r2x*iB] - // [ -r1y*iA-r2y*iB, r1x*iA+r2x*iB, iA+iB] - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Mat33 K; - K.ex.x = mA + mB + m_rA.y * m_rA.y * iA + m_rB.y * m_rB.y * iB; - K.ey.x = -m_rA.y * m_rA.x * iA - m_rB.y * m_rB.x * iB; - K.ez.x = -m_rA.y * iA - m_rB.y * iB; - K.ex.y = K.ey.x; - K.ey.y = mA + mB + m_rA.x * m_rA.x * iA + m_rB.x * m_rB.x * iB; - K.ez.y = m_rA.x * iA + m_rB.x * iB; - K.ex.z = K.ez.x; - K.ey.z = K.ez.y; - K.ez.z = iA + iB; - - if (m_frequencyHz > 0.0f) - { - K.GetInverse22(&m_mass); - - float32 invM = iA + iB; - float32 m = invM > 0.0f ? 1.0f / invM : 0.0f; - - float32 C = aB - aA - m_referenceAngle; - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 d = 2.0f * m * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (d + h * k); - m_gamma = m_gamma != 0.0f ? 1.0f / m_gamma : 0.0f; - m_bias = C * h * k * m_gamma; - - invM += m_gamma; - m_mass.ez.z = invM != 0.0f ? 1.0f / invM : 0.0f; - } - else if (K.ez.z == 0.0f) - { - K.GetInverse22(&m_mass); - m_gamma = 0.0f; - m_bias = 0.0f; - } - else - { - K.GetSymInverse33(&m_mass); - m_gamma = 0.0f; - m_bias = 0.0f; - } - - if (data.step.warmStarting) - { - // Scale impulses to support a variable time step. - m_impulse *= data.step.dtRatio; - - b2Vec2 P(m_impulse.x, m_impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + m_impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + m_impulse.z); - } - else - { - m_impulse.SetZero(); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2WeldJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - if (m_frequencyHz > 0.0f) - { - float32 Cdot2 = wB - wA; - - float32 impulse2 = -m_mass.ez.z * (Cdot2 + m_bias + m_gamma * m_impulse.z); - m_impulse.z += impulse2; - - wA -= iA * impulse2; - wB += iB * impulse2; - - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - - b2Vec2 impulse1 = -b2Mul22(m_mass, Cdot1); - m_impulse.x += impulse1.x; - m_impulse.y += impulse1.y; - - b2Vec2 P = impulse1; - - vA -= mA * P; - wA -= iA * b2Cross(m_rA, P); - - vB += mB * P; - wB += iB * b2Cross(m_rB, P); - } - else - { - b2Vec2 Cdot1 = vB + b2Cross(wB, m_rB) - vA - b2Cross(wA, m_rA); - float32 Cdot2 = wB - wA; - b2Vec3 Cdot(Cdot1.x, Cdot1.y, Cdot2); - - b2Vec3 impulse = -b2Mul(m_mass, Cdot); - m_impulse += impulse; - - b2Vec2 P(impulse.x, impulse.y); - - vA -= mA * P; - wA -= iA * (b2Cross(m_rA, P) + impulse.z); - - vB += mB * P; - wB += iB * (b2Cross(m_rB, P) + impulse.z); - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2WeldJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - - float32 positionError, angularError; - - b2Mat33 K; - K.ex.x = mA + mB + rA.y * rA.y * iA + rB.y * rB.y * iB; - K.ey.x = -rA.y * rA.x * iA - rB.y * rB.x * iB; - K.ez.x = -rA.y * iA - rB.y * iB; - K.ex.y = K.ey.x; - K.ey.y = mA + mB + rA.x * rA.x * iA + rB.x * rB.x * iB; - K.ez.y = rA.x * iA + rB.x * iB; - K.ex.z = K.ez.x; - K.ey.z = K.ez.y; - K.ez.z = iA + iB; - - if (m_frequencyHz > 0.0f) - { - b2Vec2 C1 = cB + rB - cA - rA; - - positionError = C1.Length(); - angularError = 0.0f; - - b2Vec2 P = -K.Solve22(C1); - - cA -= mA * P; - aA -= iA * b2Cross(rA, P); - - cB += mB * P; - aB += iB * b2Cross(rB, P); - } - else - { - b2Vec2 C1 = cB + rB - cA - rA; - float32 C2 = aB - aA - m_referenceAngle; - - positionError = C1.Length(); - angularError = b2Abs(C2); - - b2Vec3 C(C1.x, C1.y, C2); - - b2Vec3 impulse; - if (K.ez.z > 0.0f) - { - impulse = -K.Solve33(C); - } - else - { - b2Vec2 impulse2 = -K.Solve22(C1); - impulse.Set(impulse2.x, impulse2.y, 0.0f); - } - - b2Vec2 P(impulse.x, impulse.y); - - cA -= mA * P; - aA -= iA * (b2Cross(rA, P) + impulse.z); - - cB += mB * P; - aB += iB * (b2Cross(rB, P) + impulse.z); - } - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return positionError <= b2_linearSlop && angularError <= b2_angularSlop; -} - -b2Vec2 b2WeldJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2WeldJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2WeldJoint::GetReactionForce(float32 inv_dt) const -{ - b2Vec2 P(m_impulse.x, m_impulse.y); - return inv_dt * P; -} - -float32 b2WeldJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_impulse.z; -} - -void b2WeldJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2WeldJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.referenceAngle = %.15lef;\n", m_referenceAngle); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2WeldJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2WeldJoint.h deleted file mode 100644 index 81ba235..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2WeldJoint.h +++ /dev/null @@ -1,126 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_WELD_JOINT_H -#define B2_WELD_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Weld joint definition. You need to specify local anchor points -/// where they are attached and the relative body angle. The position -/// of the anchor points is important for computing the reaction torque. -struct b2WeldJointDef : public b2JointDef -{ - b2WeldJointDef() - { - type = e_weldJoint; - localAnchorA.Set(0.0f, 0.0f); - localAnchorB.Set(0.0f, 0.0f); - referenceAngle = 0.0f; - frequencyHz = 0.0f; - dampingRatio = 0.0f; - } - - /// Initialize the bodies, anchors, and reference angle using a world - /// anchor point. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The bodyB angle minus bodyA angle in the reference state (radians). - float32 referenceAngle; - - /// The mass-spring-damper frequency in Hertz. Rotation only. - /// Disable softness with a value of 0. - float32 frequencyHz; - - /// The damping ratio. 0 = no damping, 1 = critical damping. - float32 dampingRatio; -}; - -/// A weld joint essentially glues two bodies together. A weld joint may -/// distort somewhat because the island constraint solver is approximate. -class b2WeldJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - b2Vec2 GetReactionForce(float32 inv_dt) const override; - float32 GetReactionTorque(float32 inv_dt) const override; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// Get the reference angle. - float32 GetReferenceAngle() const { return m_referenceAngle; } - - /// Set/get frequency in Hz. - void SetFrequency(float32 hz) { m_frequencyHz = hz; } - float32 GetFrequency() const { return m_frequencyHz; } - - /// Set/get damping ratio. - void SetDampingRatio(float32 ratio) { m_dampingRatio = ratio; } - float32 GetDampingRatio() const { return m_dampingRatio; } - - /// Dump to b2Log - void Dump() override; - -protected: - - friend class b2Joint; - - b2WeldJoint(const b2WeldJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - float32 m_frequencyHz; - float32 m_dampingRatio; - float32 m_bias; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - float32 m_referenceAngle; - float32 m_gamma; - b2Vec3 m_impulse; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_rA; - b2Vec2 m_rB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - b2Mat33 m_mass; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2WheelJoint.cpp b/libjin/3rdparty/Box2D/Dynamics/Joints/b2WheelJoint.cpp deleted file mode 100644 index a95311e..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2WheelJoint.cpp +++ /dev/null @@ -1,456 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/Joints/b2WheelJoint.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -// Linear constraint (point-to-line) -// d = pB - pA = xB + rB - xA - rA -// C = dot(ay, d) -// Cdot = dot(d, cross(wA, ay)) + dot(ay, vB + cross(wB, rB) - vA - cross(wA, rA)) -// = -dot(ay, vA) - dot(cross(d + rA, ay), wA) + dot(ay, vB) + dot(cross(rB, ay), vB) -// J = [-ay, -cross(d + rA, ay), ay, cross(rB, ay)] - -// Spring linear constraint -// C = dot(ax, d) -// Cdot = = -dot(ax, vA) - dot(cross(d + rA, ax), wA) + dot(ax, vB) + dot(cross(rB, ax), vB) -// J = [-ax -cross(d+rA, ax) ax cross(rB, ax)] - -// Motor rotational constraint -// Cdot = wB - wA -// J = [0 0 -1 0 0 1] - -void b2WheelJointDef::Initialize(b2Body* bA, b2Body* bB, const b2Vec2& anchor, const b2Vec2& axis) -{ - bodyA = bA; - bodyB = bB; - localAnchorA = bodyA->GetLocalPoint(anchor); - localAnchorB = bodyB->GetLocalPoint(anchor); - localAxisA = bodyA->GetLocalVector(axis); -} - -b2WheelJoint::b2WheelJoint(const b2WheelJointDef* def) -: b2Joint(def) -{ - m_localAnchorA = def->localAnchorA; - m_localAnchorB = def->localAnchorB; - m_localXAxisA = def->localAxisA; - m_localYAxisA = b2Cross(1.0f, m_localXAxisA); - - m_mass = 0.0f; - m_impulse = 0.0f; - m_motorMass = 0.0f; - m_motorImpulse = 0.0f; - m_springMass = 0.0f; - m_springImpulse = 0.0f; - - m_maxMotorTorque = def->maxMotorTorque; - m_motorSpeed = def->motorSpeed; - m_enableMotor = def->enableMotor; - - m_frequencyHz = def->frequencyHz; - m_dampingRatio = def->dampingRatio; - - m_bias = 0.0f; - m_gamma = 0.0f; - - m_ax.SetZero(); - m_ay.SetZero(); -} - -void b2WheelJoint::InitVelocityConstraints(const b2SolverData& data) -{ - m_indexA = m_bodyA->m_islandIndex; - m_indexB = m_bodyB->m_islandIndex; - m_localCenterA = m_bodyA->m_sweep.localCenter; - m_localCenterB = m_bodyB->m_sweep.localCenter; - m_invMassA = m_bodyA->m_invMass; - m_invMassB = m_bodyB->m_invMass; - m_invIA = m_bodyA->m_invI; - m_invIB = m_bodyB->m_invI; - - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - b2Rot qA(aA), qB(aB); - - // Compute the effective masses. - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = cB + rB - cA - rA; - - // Point to line constraint - { - m_ay = b2Mul(qA, m_localYAxisA); - m_sAy = b2Cross(d + rA, m_ay); - m_sBy = b2Cross(rB, m_ay); - - m_mass = mA + mB + iA * m_sAy * m_sAy + iB * m_sBy * m_sBy; - - if (m_mass > 0.0f) - { - m_mass = 1.0f / m_mass; - } - } - - // Spring constraint - m_springMass = 0.0f; - m_bias = 0.0f; - m_gamma = 0.0f; - if (m_frequencyHz > 0.0f) - { - m_ax = b2Mul(qA, m_localXAxisA); - m_sAx = b2Cross(d + rA, m_ax); - m_sBx = b2Cross(rB, m_ax); - - float32 invMass = mA + mB + iA * m_sAx * m_sAx + iB * m_sBx * m_sBx; - - if (invMass > 0.0f) - { - m_springMass = 1.0f / invMass; - - float32 C = b2Dot(d, m_ax); - - // Frequency - float32 omega = 2.0f * b2_pi * m_frequencyHz; - - // Damping coefficient - float32 damp = 2.0f * m_springMass * m_dampingRatio * omega; - - // Spring stiffness - float32 k = m_springMass * omega * omega; - - // magic formulas - float32 h = data.step.dt; - m_gamma = h * (damp + h * k); - if (m_gamma > 0.0f) - { - m_gamma = 1.0f / m_gamma; - } - - m_bias = C * h * k * m_gamma; - - m_springMass = invMass + m_gamma; - if (m_springMass > 0.0f) - { - m_springMass = 1.0f / m_springMass; - } - } - } - else - { - m_springImpulse = 0.0f; - } - - // Rotational motor - if (m_enableMotor) - { - m_motorMass = iA + iB; - if (m_motorMass > 0.0f) - { - m_motorMass = 1.0f / m_motorMass; - } - } - else - { - m_motorMass = 0.0f; - m_motorImpulse = 0.0f; - } - - if (data.step.warmStarting) - { - // Account for variable time step. - m_impulse *= data.step.dtRatio; - m_springImpulse *= data.step.dtRatio; - m_motorImpulse *= data.step.dtRatio; - - b2Vec2 P = m_impulse * m_ay + m_springImpulse * m_ax; - float32 LA = m_impulse * m_sAy + m_springImpulse * m_sAx + m_motorImpulse; - float32 LB = m_impulse * m_sBy + m_springImpulse * m_sBx + m_motorImpulse; - - vA -= m_invMassA * P; - wA -= m_invIA * LA; - - vB += m_invMassB * P; - wB += m_invIB * LB; - } - else - { - m_impulse = 0.0f; - m_springImpulse = 0.0f; - m_motorImpulse = 0.0f; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -void b2WheelJoint::SolveVelocityConstraints(const b2SolverData& data) -{ - float32 mA = m_invMassA, mB = m_invMassB; - float32 iA = m_invIA, iB = m_invIB; - - b2Vec2 vA = data.velocities[m_indexA].v; - float32 wA = data.velocities[m_indexA].w; - b2Vec2 vB = data.velocities[m_indexB].v; - float32 wB = data.velocities[m_indexB].w; - - // Solve spring constraint - { - float32 Cdot = b2Dot(m_ax, vB - vA) + m_sBx * wB - m_sAx * wA; - float32 impulse = -m_springMass * (Cdot + m_bias + m_gamma * m_springImpulse); - m_springImpulse += impulse; - - b2Vec2 P = impulse * m_ax; - float32 LA = impulse * m_sAx; - float32 LB = impulse * m_sBx; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - // Solve rotational motor constraint - { - float32 Cdot = wB - wA - m_motorSpeed; - float32 impulse = -m_motorMass * Cdot; - - float32 oldImpulse = m_motorImpulse; - float32 maxImpulse = data.step.dt * m_maxMotorTorque; - m_motorImpulse = b2Clamp(m_motorImpulse + impulse, -maxImpulse, maxImpulse); - impulse = m_motorImpulse - oldImpulse; - - wA -= iA * impulse; - wB += iB * impulse; - } - - // Solve point to line constraint - { - float32 Cdot = b2Dot(m_ay, vB - vA) + m_sBy * wB - m_sAy * wA; - float32 impulse = -m_mass * Cdot; - m_impulse += impulse; - - b2Vec2 P = impulse * m_ay; - float32 LA = impulse * m_sAy; - float32 LB = impulse * m_sBy; - - vA -= mA * P; - wA -= iA * LA; - - vB += mB * P; - wB += iB * LB; - } - - data.velocities[m_indexA].v = vA; - data.velocities[m_indexA].w = wA; - data.velocities[m_indexB].v = vB; - data.velocities[m_indexB].w = wB; -} - -bool b2WheelJoint::SolvePositionConstraints(const b2SolverData& data) -{ - b2Vec2 cA = data.positions[m_indexA].c; - float32 aA = data.positions[m_indexA].a; - b2Vec2 cB = data.positions[m_indexB].c; - float32 aB = data.positions[m_indexB].a; - - b2Rot qA(aA), qB(aB); - - b2Vec2 rA = b2Mul(qA, m_localAnchorA - m_localCenterA); - b2Vec2 rB = b2Mul(qB, m_localAnchorB - m_localCenterB); - b2Vec2 d = (cB - cA) + rB - rA; - - b2Vec2 ay = b2Mul(qA, m_localYAxisA); - - float32 sAy = b2Cross(d + rA, ay); - float32 sBy = b2Cross(rB, ay); - - float32 C = b2Dot(d, ay); - - float32 k = m_invMassA + m_invMassB + m_invIA * m_sAy * m_sAy + m_invIB * m_sBy * m_sBy; - - float32 impulse; - if (k != 0.0f) - { - impulse = - C / k; - } - else - { - impulse = 0.0f; - } - - b2Vec2 P = impulse * ay; - float32 LA = impulse * sAy; - float32 LB = impulse * sBy; - - cA -= m_invMassA * P; - aA -= m_invIA * LA; - cB += m_invMassB * P; - aB += m_invIB * LB; - - data.positions[m_indexA].c = cA; - data.positions[m_indexA].a = aA; - data.positions[m_indexB].c = cB; - data.positions[m_indexB].a = aB; - - return b2Abs(C) <= b2_linearSlop; -} - -b2Vec2 b2WheelJoint::GetAnchorA() const -{ - return m_bodyA->GetWorldPoint(m_localAnchorA); -} - -b2Vec2 b2WheelJoint::GetAnchorB() const -{ - return m_bodyB->GetWorldPoint(m_localAnchorB); -} - -b2Vec2 b2WheelJoint::GetReactionForce(float32 inv_dt) const -{ - return inv_dt * (m_impulse * m_ay + m_springImpulse * m_ax); -} - -float32 b2WheelJoint::GetReactionTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -float32 b2WheelJoint::GetJointTranslation() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - - b2Vec2 pA = bA->GetWorldPoint(m_localAnchorA); - b2Vec2 pB = bB->GetWorldPoint(m_localAnchorB); - b2Vec2 d = pB - pA; - b2Vec2 axis = bA->GetWorldVector(m_localXAxisA); - - float32 translation = b2Dot(d, axis); - return translation; -} - -float32 b2WheelJoint::GetJointLinearSpeed() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - - b2Vec2 rA = b2Mul(bA->m_xf.q, m_localAnchorA - bA->m_sweep.localCenter); - b2Vec2 rB = b2Mul(bB->m_xf.q, m_localAnchorB - bB->m_sweep.localCenter); - b2Vec2 p1 = bA->m_sweep.c + rA; - b2Vec2 p2 = bB->m_sweep.c + rB; - b2Vec2 d = p2 - p1; - b2Vec2 axis = b2Mul(bA->m_xf.q, m_localXAxisA); - - b2Vec2 vA = bA->m_linearVelocity; - b2Vec2 vB = bB->m_linearVelocity; - float32 wA = bA->m_angularVelocity; - float32 wB = bB->m_angularVelocity; - - float32 speed = b2Dot(d, b2Cross(wA, axis)) + b2Dot(axis, vB + b2Cross(wB, rB) - vA - b2Cross(wA, rA)); - return speed; -} - -float32 b2WheelJoint::GetJointAngle() const -{ - b2Body* bA = m_bodyA; - b2Body* bB = m_bodyB; - return bB->m_sweep.a - bA->m_sweep.a; -} - -float32 b2WheelJoint::GetJointAngularSpeed() const -{ - float32 wA = m_bodyA->m_angularVelocity; - float32 wB = m_bodyB->m_angularVelocity; - return wB - wA; -} - -bool b2WheelJoint::IsMotorEnabled() const -{ - return m_enableMotor; -} - -void b2WheelJoint::EnableMotor(bool flag) -{ - if (flag != m_enableMotor) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_enableMotor = flag; - } -} - -void b2WheelJoint::SetMotorSpeed(float32 speed) -{ - if (speed != m_motorSpeed) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_motorSpeed = speed; - } -} - -void b2WheelJoint::SetMaxMotorTorque(float32 torque) -{ - if (torque != m_maxMotorTorque) - { - m_bodyA->SetAwake(true); - m_bodyB->SetAwake(true); - m_maxMotorTorque = torque; - } -} - -float32 b2WheelJoint::GetMotorTorque(float32 inv_dt) const -{ - return inv_dt * m_motorImpulse; -} - -void b2WheelJoint::Dump() -{ - int32 indexA = m_bodyA->m_islandIndex; - int32 indexB = m_bodyB->m_islandIndex; - - b2Log(" b2WheelJointDef jd;\n"); - b2Log(" jd.bodyA = bodies[%d];\n", indexA); - b2Log(" jd.bodyB = bodies[%d];\n", indexB); - b2Log(" jd.collideConnected = bool(%d);\n", m_collideConnected); - b2Log(" jd.localAnchorA.Set(%.15lef, %.15lef);\n", m_localAnchorA.x, m_localAnchorA.y); - b2Log(" jd.localAnchorB.Set(%.15lef, %.15lef);\n", m_localAnchorB.x, m_localAnchorB.y); - b2Log(" jd.localAxisA.Set(%.15lef, %.15lef);\n", m_localXAxisA.x, m_localXAxisA.y); - b2Log(" jd.enableMotor = bool(%d);\n", m_enableMotor); - b2Log(" jd.motorSpeed = %.15lef;\n", m_motorSpeed); - b2Log(" jd.maxMotorTorque = %.15lef;\n", m_maxMotorTorque); - b2Log(" jd.frequencyHz = %.15lef;\n", m_frequencyHz); - b2Log(" jd.dampingRatio = %.15lef;\n", m_dampingRatio); - b2Log(" joints[%d] = m_world->CreateJoint(&jd);\n", m_index); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/Joints/b2WheelJoint.h b/libjin/3rdparty/Box2D/Dynamics/Joints/b2WheelJoint.h deleted file mode 100644 index be7ad66..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/Joints/b2WheelJoint.h +++ /dev/null @@ -1,216 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_WHEEL_JOINT_H -#define B2_WHEEL_JOINT_H - -#include "Box2D/Dynamics/Joints/b2Joint.h" - -/// Wheel joint definition. This requires defining a line of -/// motion using an axis and an anchor point. The definition uses local -/// anchor points and a local axis so that the initial configuration -/// can violate the constraint slightly. The joint translation is zero -/// when the local anchor points coincide in world space. Using local -/// anchors and a local axis helps when saving and loading a game. -struct b2WheelJointDef : public b2JointDef -{ - b2WheelJointDef() - { - type = e_wheelJoint; - localAnchorA.SetZero(); - localAnchorB.SetZero(); - localAxisA.Set(1.0f, 0.0f); - enableMotor = false; - maxMotorTorque = 0.0f; - motorSpeed = 0.0f; - frequencyHz = 2.0f; - dampingRatio = 0.7f; - } - - /// Initialize the bodies, anchors, axis, and reference angle using the world - /// anchor and world axis. - void Initialize(b2Body* bodyA, b2Body* bodyB, const b2Vec2& anchor, const b2Vec2& axis); - - /// The local anchor point relative to bodyA's origin. - b2Vec2 localAnchorA; - - /// The local anchor point relative to bodyB's origin. - b2Vec2 localAnchorB; - - /// The local translation axis in bodyA. - b2Vec2 localAxisA; - - /// Enable/disable the joint motor. - bool enableMotor; - - /// The maximum motor torque, usually in N-m. - float32 maxMotorTorque; - - /// The desired motor speed in radians per second. - float32 motorSpeed; - - /// Suspension frequency, zero indicates no suspension - float32 frequencyHz; - - /// Suspension damping ratio, one indicates critical damping - float32 dampingRatio; -}; - -/// A wheel joint. This joint provides two degrees of freedom: translation -/// along an axis fixed in bodyA and rotation in the plane. In other words, it is a point to -/// line constraint with a rotational motor and a linear spring/damper. -/// This joint is designed for vehicle suspensions. -class b2WheelJoint : public b2Joint -{ -public: - b2Vec2 GetAnchorA() const override; - b2Vec2 GetAnchorB() const override; - - b2Vec2 GetReactionForce(float32 inv_dt) const override; - float32 GetReactionTorque(float32 inv_dt) const override; - - /// The local anchor point relative to bodyA's origin. - const b2Vec2& GetLocalAnchorA() const { return m_localAnchorA; } - - /// The local anchor point relative to bodyB's origin. - const b2Vec2& GetLocalAnchorB() const { return m_localAnchorB; } - - /// The local joint axis relative to bodyA. - const b2Vec2& GetLocalAxisA() const { return m_localXAxisA; } - - /// Get the current joint translation, usually in meters. - float32 GetJointTranslation() const; - - /// Get the current joint linear speed, usually in meters per second. - float32 GetJointLinearSpeed() const; - - /// Get the current joint angle in radians. - float32 GetJointAngle() const; - - /// Get the current joint angular speed in radians per second. - float32 GetJointAngularSpeed() const; - - /// Is the joint motor enabled? - bool IsMotorEnabled() const; - - /// Enable/disable the joint motor. - void EnableMotor(bool flag); - - /// Set the motor speed, usually in radians per second. - void SetMotorSpeed(float32 speed); - - /// Get the motor speed, usually in radians per second. - float32 GetMotorSpeed() const; - - /// Set/Get the maximum motor force, usually in N-m. - void SetMaxMotorTorque(float32 torque); - float32 GetMaxMotorTorque() const; - - /// Get the current motor torque given the inverse time step, usually in N-m. - float32 GetMotorTorque(float32 inv_dt) const; - - /// Set/Get the spring frequency in hertz. Setting the frequency to zero disables the spring. - void SetSpringFrequencyHz(float32 hz); - float32 GetSpringFrequencyHz() const; - - /// Set/Get the spring damping ratio - void SetSpringDampingRatio(float32 ratio); - float32 GetSpringDampingRatio() const; - - /// Dump to b2Log - void Dump() override; - -protected: - - friend class b2Joint; - b2WheelJoint(const b2WheelJointDef* def); - - void InitVelocityConstraints(const b2SolverData& data) override; - void SolveVelocityConstraints(const b2SolverData& data) override; - bool SolvePositionConstraints(const b2SolverData& data) override; - - float32 m_frequencyHz; - float32 m_dampingRatio; - - // Solver shared - b2Vec2 m_localAnchorA; - b2Vec2 m_localAnchorB; - b2Vec2 m_localXAxisA; - b2Vec2 m_localYAxisA; - - float32 m_impulse; - float32 m_motorImpulse; - float32 m_springImpulse; - - float32 m_maxMotorTorque; - float32 m_motorSpeed; - bool m_enableMotor; - - // Solver temp - int32 m_indexA; - int32 m_indexB; - b2Vec2 m_localCenterA; - b2Vec2 m_localCenterB; - float32 m_invMassA; - float32 m_invMassB; - float32 m_invIA; - float32 m_invIB; - - b2Vec2 m_ax, m_ay; - float32 m_sAx, m_sBx; - float32 m_sAy, m_sBy; - - float32 m_mass; - float32 m_motorMass; - float32 m_springMass; - - float32 m_bias; - float32 m_gamma; -}; - -inline float32 b2WheelJoint::GetMotorSpeed() const -{ - return m_motorSpeed; -} - -inline float32 b2WheelJoint::GetMaxMotorTorque() const -{ - return m_maxMotorTorque; -} - -inline void b2WheelJoint::SetSpringFrequencyHz(float32 hz) -{ - m_frequencyHz = hz; -} - -inline float32 b2WheelJoint::GetSpringFrequencyHz() const -{ - return m_frequencyHz; -} - -inline void b2WheelJoint::SetSpringDampingRatio(float32 ratio) -{ - m_dampingRatio = ratio; -} - -inline float32 b2WheelJoint::GetSpringDampingRatio() const -{ - return m_dampingRatio; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/b2Body.cpp b/libjin/3rdparty/Box2D/Dynamics/b2Body.cpp deleted file mode 100644 index 54154b8..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2Body.cpp +++ /dev/null @@ -1,554 +0,0 @@ -/* -* Copyright (c) 2006-2007 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2World.h" -#include "Box2D/Dynamics/Contacts/b2Contact.h" -#include "Box2D/Dynamics/Joints/b2Joint.h" - -b2Body::b2Body(const b2BodyDef* bd, b2World* world) -{ - b2Assert(bd->position.IsValid()); - b2Assert(bd->linearVelocity.IsValid()); - b2Assert(b2IsValid(bd->angle)); - b2Assert(b2IsValid(bd->angularVelocity)); - b2Assert(b2IsValid(bd->angularDamping) && bd->angularDamping >= 0.0f); - b2Assert(b2IsValid(bd->linearDamping) && bd->linearDamping >= 0.0f); - - m_flags = 0; - - if (bd->bullet) - { - m_flags |= e_bulletFlag; - } - if (bd->fixedRotation) - { - m_flags |= e_fixedRotationFlag; - } - if (bd->allowSleep) - { - m_flags |= e_autoSleepFlag; - } - if (bd->awake) - { - m_flags |= e_awakeFlag; - } - if (bd->active) - { - m_flags |= e_activeFlag; - } - - m_world = world; - - m_xf.p = bd->position; - m_xf.q.Set(bd->angle); - - m_sweep.localCenter.SetZero(); - m_sweep.c0 = m_xf.p; - m_sweep.c = m_xf.p; - m_sweep.a0 = bd->angle; - m_sweep.a = bd->angle; - m_sweep.alpha0 = 0.0f; - - m_jointList = nullptr; - m_contactList = nullptr; - m_prev = nullptr; - m_next = nullptr; - - m_linearVelocity = bd->linearVelocity; - m_angularVelocity = bd->angularVelocity; - - m_linearDamping = bd->linearDamping; - m_angularDamping = bd->angularDamping; - m_gravityScale = bd->gravityScale; - - m_force.SetZero(); - m_torque = 0.0f; - - m_sleepTime = 0.0f; - - m_type = bd->type; - - if (m_type == b2_dynamicBody) - { - m_mass = 1.0f; - m_invMass = 1.0f; - } - else - { - m_mass = 0.0f; - m_invMass = 0.0f; - } - - m_I = 0.0f; - m_invI = 0.0f; - - m_userData = bd->userData; - - m_fixtureList = nullptr; - m_fixtureCount = 0; -} - -b2Body::~b2Body() -{ - // shapes and joints are destroyed in b2World::Destroy -} - -void b2Body::SetType(b2BodyType type) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - if (m_type == type) - { - return; - } - - m_type = type; - - ResetMassData(); - - if (m_type == b2_staticBody) - { - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_sweep.a0 = m_sweep.a; - m_sweep.c0 = m_sweep.c; - SynchronizeFixtures(); - } - - SetAwake(true); - - m_force.SetZero(); - m_torque = 0.0f; - - // Delete the attached contacts. - b2ContactEdge* ce = m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_world->m_contactManager.Destroy(ce0->contact); - } - m_contactList = nullptr; - - // Touch the proxies so that new contacts will be created (when appropriate) - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - int32 proxyCount = f->m_proxyCount; - for (int32 i = 0; i < proxyCount; ++i) - { - broadPhase->TouchProxy(f->m_proxies[i].proxyId); - } - } -} - -b2Fixture* b2Body::CreateFixture(const b2FixtureDef* def) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return nullptr; - } - - b2BlockAllocator* allocator = &m_world->m_blockAllocator; - - void* memory = allocator->Allocate(sizeof(b2Fixture)); - b2Fixture* fixture = new (memory) b2Fixture; - fixture->Create(allocator, this, def); - - if (m_flags & e_activeFlag) - { - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->CreateProxies(broadPhase, m_xf); - } - - fixture->m_next = m_fixtureList; - m_fixtureList = fixture; - ++m_fixtureCount; - - fixture->m_body = this; - - // Adjust mass properties if needed. - if (fixture->m_density > 0.0f) - { - ResetMassData(); - } - - // Let the world know we have a new fixture. This will cause new contacts - // to be created at the beginning of the next time step. - m_world->m_flags |= b2World::e_newFixture; - - return fixture; -} - -b2Fixture* b2Body::CreateFixture(const b2Shape* shape, float32 density) -{ - b2FixtureDef def; - def.shape = shape; - def.density = density; - - return CreateFixture(&def); -} - -void b2Body::DestroyFixture(b2Fixture* fixture) -{ - if (fixture == NULL) - { - return; - } - - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - b2Assert(fixture->m_body == this); - - // Remove the fixture from this body's singly linked list. - b2Assert(m_fixtureCount > 0); - b2Fixture** node = &m_fixtureList; - bool found = false; - while (*node != nullptr) - { - if (*node == fixture) - { - *node = fixture->m_next; - found = true; - break; - } - - node = &(*node)->m_next; - } - - // You tried to remove a shape that is not attached to this body. - b2Assert(found); - - // Destroy any contacts associated with the fixture. - b2ContactEdge* edge = m_contactList; - while (edge) - { - b2Contact* c = edge->contact; - edge = edge->next; - - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - - if (fixture == fixtureA || fixture == fixtureB) - { - // This destroys the contact and removes it from - // this body's contact list. - m_world->m_contactManager.Destroy(c); - } - } - - b2BlockAllocator* allocator = &m_world->m_blockAllocator; - - if (m_flags & e_activeFlag) - { - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - fixture->DestroyProxies(broadPhase); - } - - fixture->m_body = nullptr; - fixture->m_next = nullptr; - fixture->Destroy(allocator); - fixture->~b2Fixture(); - allocator->Free(fixture, sizeof(b2Fixture)); - - --m_fixtureCount; - - // Reset the mass data. - ResetMassData(); -} - -void b2Body::ResetMassData() -{ - // Compute mass data from shapes. Each shape has its own density. - m_mass = 0.0f; - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - m_sweep.localCenter.SetZero(); - - // Static and kinematic bodies have zero mass. - if (m_type == b2_staticBody || m_type == b2_kinematicBody) - { - m_sweep.c0 = m_xf.p; - m_sweep.c = m_xf.p; - m_sweep.a0 = m_sweep.a; - return; - } - - b2Assert(m_type == b2_dynamicBody); - - // Accumulate mass over all fixtures. - b2Vec2 localCenter = b2Vec2_zero; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - if (f->m_density == 0.0f) - { - continue; - } - - b2MassData massData; - f->GetMassData(&massData); - m_mass += massData.mass; - localCenter += massData.mass * massData.center; - m_I += massData.I; - } - - // Compute center of mass. - if (m_mass > 0.0f) - { - m_invMass = 1.0f / m_mass; - localCenter *= m_invMass; - } - else - { - // Force all dynamic bodies to have a positive mass. - m_mass = 1.0f; - m_invMass = 1.0f; - } - - if (m_I > 0.0f && (m_flags & e_fixedRotationFlag) == 0) - { - // Center the inertia about the center of mass. - m_I -= m_mass * b2Dot(localCenter, localCenter); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; - - } - else - { - m_I = 0.0f; - m_invI = 0.0f; - } - - // Move center of mass. - b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = localCenter; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - // Update center of mass velocity. - m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); -} - -void b2Body::SetMassData(const b2MassData* massData) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - if (m_type != b2_dynamicBody) - { - return; - } - - m_invMass = 0.0f; - m_I = 0.0f; - m_invI = 0.0f; - - m_mass = massData->mass; - if (m_mass <= 0.0f) - { - m_mass = 1.0f; - } - - m_invMass = 1.0f / m_mass; - - if (massData->I > 0.0f && (m_flags & b2Body::e_fixedRotationFlag) == 0) - { - m_I = massData->I - m_mass * b2Dot(massData->center, massData->center); - b2Assert(m_I > 0.0f); - m_invI = 1.0f / m_I; - } - - // Move center of mass. - b2Vec2 oldCenter = m_sweep.c; - m_sweep.localCenter = massData->center; - m_sweep.c0 = m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - - // Update center of mass velocity. - m_linearVelocity += b2Cross(m_angularVelocity, m_sweep.c - oldCenter); -} - -bool b2Body::ShouldCollide(const b2Body* other) const -{ - // At least one body should be dynamic. - if (m_type != b2_dynamicBody && other->m_type != b2_dynamicBody) - { - return false; - } - - // Does a joint prevent collision? - for (b2JointEdge* jn = m_jointList; jn; jn = jn->next) - { - if (jn->other == other) - { - if (jn->joint->m_collideConnected == false) - { - return false; - } - } - } - - return true; -} - -void b2Body::SetTransform(const b2Vec2& position, float32 angle) -{ - b2Assert(m_world->IsLocked() == false); - if (m_world->IsLocked() == true) - { - return; - } - - m_xf.q.Set(angle); - m_xf.p = position; - - m_sweep.c = b2Mul(m_xf, m_sweep.localCenter); - m_sweep.a = angle; - - m_sweep.c0 = m_sweep.c; - m_sweep.a0 = angle; - - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Synchronize(broadPhase, m_xf, m_xf); - } -} - -void b2Body::SynchronizeFixtures() -{ - b2Transform xf1; - xf1.q.Set(m_sweep.a0); - xf1.p = m_sweep.c0 - b2Mul(xf1.q, m_sweep.localCenter); - - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->Synchronize(broadPhase, xf1, m_xf); - } -} - -void b2Body::SetActive(bool flag) -{ - b2Assert(m_world->IsLocked() == false); - - if (flag == IsActive()) - { - return; - } - - if (flag) - { - m_flags |= e_activeFlag; - - // Create all proxies. - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->CreateProxies(broadPhase, m_xf); - } - - // Contacts are created the next time step. - } - else - { - m_flags &= ~e_activeFlag; - - // Destroy all proxies. - b2BroadPhase* broadPhase = &m_world->m_contactManager.m_broadPhase; - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - f->DestroyProxies(broadPhase); - } - - // Destroy the attached contacts. - b2ContactEdge* ce = m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_world->m_contactManager.Destroy(ce0->contact); - } - m_contactList = nullptr; - } -} - -void b2Body::SetFixedRotation(bool flag) -{ - bool status = (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; - if (status == flag) - { - return; - } - - if (flag) - { - m_flags |= e_fixedRotationFlag; - } - else - { - m_flags &= ~e_fixedRotationFlag; - } - - m_angularVelocity = 0.0f; - - ResetMassData(); -} - -void b2Body::Dump() -{ - int32 bodyIndex = m_islandIndex; - - b2Log("{\n"); - b2Log(" b2BodyDef bd;\n"); - b2Log(" bd.type = b2BodyType(%d);\n", m_type); - b2Log(" bd.position.Set(%.15lef, %.15lef);\n", m_xf.p.x, m_xf.p.y); - b2Log(" bd.angle = %.15lef;\n", m_sweep.a); - b2Log(" bd.linearVelocity.Set(%.15lef, %.15lef);\n", m_linearVelocity.x, m_linearVelocity.y); - b2Log(" bd.angularVelocity = %.15lef;\n", m_angularVelocity); - b2Log(" bd.linearDamping = %.15lef;\n", m_linearDamping); - b2Log(" bd.angularDamping = %.15lef;\n", m_angularDamping); - b2Log(" bd.allowSleep = bool(%d);\n", m_flags & e_autoSleepFlag); - b2Log(" bd.awake = bool(%d);\n", m_flags & e_awakeFlag); - b2Log(" bd.fixedRotation = bool(%d);\n", m_flags & e_fixedRotationFlag); - b2Log(" bd.bullet = bool(%d);\n", m_flags & e_bulletFlag); - b2Log(" bd.active = bool(%d);\n", m_flags & e_activeFlag); - b2Log(" bd.gravityScale = %.15lef;\n", m_gravityScale); - b2Log(" bodies[%d] = m_world->CreateBody(&bd);\n", m_islandIndex); - b2Log("\n"); - for (b2Fixture* f = m_fixtureList; f; f = f->m_next) - { - b2Log(" {\n"); - f->Dump(bodyIndex); - b2Log(" }\n"); - } - b2Log("}\n"); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/b2Body.h b/libjin/3rdparty/Box2D/Dynamics/b2Body.h deleted file mode 100644 index c191f6d..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2Body.h +++ /dev/null @@ -1,882 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_BODY_H -#define B2_BODY_H - -#include "Box2D/Common/b2Math.h" -#include "Box2D/Collision/Shapes/b2Shape.h" -#include <memory> - -class b2Fixture; -class b2Joint; -class b2Contact; -class b2Controller; -class b2World; -struct b2FixtureDef; -struct b2JointEdge; -struct b2ContactEdge; - -/// The body type. -/// static: zero mass, zero velocity, may be manually moved -/// kinematic: zero mass, non-zero velocity set by user, moved by solver -/// dynamic: positive mass, non-zero velocity determined by forces, moved by solver -enum b2BodyType -{ - b2_staticBody = 0, - b2_kinematicBody, - b2_dynamicBody - - // TODO_ERIN - //b2_bulletBody, -}; - -/// A body definition holds all the data needed to construct a rigid body. -/// You can safely re-use body definitions. Shapes are added to a body after construction. -struct b2BodyDef -{ - /// This constructor sets the body definition default values. - b2BodyDef() - { - userData = nullptr; - position.Set(0.0f, 0.0f); - angle = 0.0f; - linearVelocity.Set(0.0f, 0.0f); - angularVelocity = 0.0f; - linearDamping = 0.0f; - angularDamping = 0.0f; - allowSleep = true; - awake = true; - fixedRotation = false; - bullet = false; - type = b2_staticBody; - active = true; - gravityScale = 1.0f; - } - - /// The body type: static, kinematic, or dynamic. - /// Note: if a dynamic body would have zero mass, the mass is set to one. - b2BodyType type; - - /// The world position of the body. Avoid creating bodies at the origin - /// since this can lead to many overlapping shapes. - b2Vec2 position; - - /// The world angle of the body in radians. - float32 angle; - - /// The linear velocity of the body's origin in world co-ordinates. - b2Vec2 linearVelocity; - - /// The angular velocity of the body. - float32 angularVelocity; - - /// Linear damping is use to reduce the linear velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - /// Units are 1/time - float32 linearDamping; - - /// Angular damping is use to reduce the angular velocity. The damping parameter - /// can be larger than 1.0f but the damping effect becomes sensitive to the - /// time step when the damping parameter is large. - /// Units are 1/time - float32 angularDamping; - - /// Set this flag to false if this body should never fall asleep. Note that - /// this increases CPU usage. - bool allowSleep; - - /// Is this body initially awake or sleeping? - bool awake; - - /// Should this body be prevented from rotating? Useful for characters. - bool fixedRotation; - - /// Is this a fast moving body that should be prevented from tunneling through - /// other moving bodies? Note that all bodies are prevented from tunneling through - /// kinematic and static bodies. This setting is only considered on dynamic bodies. - /// @warning You should use this flag sparingly since it increases processing time. - bool bullet; - - /// Does this body start out active? - bool active; - - /// Use this to store application specific body data. - void* userData; - - /// Scale the gravity applied to this body. - float32 gravityScale; -}; - -/// A rigid body. These are created via b2World::CreateBody. -class b2Body -{ -public: - /// Creates a fixture and attach it to this body. Use this function if you need - /// to set some fixture parameters, like friction. Otherwise you can create the - /// fixture directly from a shape. - /// If the density is non-zero, this function automatically updates the mass of the body. - /// Contacts are not created until the next time step. - /// @param def the fixture definition. - /// @warning This function is locked during callbacks. - b2Fixture* CreateFixture(const b2FixtureDef* def); - - /// Creates a fixture from a shape and attach it to this body. - /// This is a convenience function. Use b2FixtureDef if you need to set parameters - /// like friction, restitution, user data, or filtering. - /// If the density is non-zero, this function automatically updates the mass of the body. - /// @param shape the shape to be cloned. - /// @param density the shape density (set to zero for static bodies). - /// @warning This function is locked during callbacks. - b2Fixture* CreateFixture(const b2Shape* shape, float32 density); - - /// Destroy a fixture. This removes the fixture from the broad-phase and - /// destroys all contacts associated with this fixture. This will - /// automatically adjust the mass of the body if the body is dynamic and the - /// fixture has positive density. - /// All fixtures attached to a body are implicitly destroyed when the body is destroyed. - /// @param fixture the fixture to be removed. - /// @warning This function is locked during callbacks. - void DestroyFixture(b2Fixture* fixture); - - /// Set the position of the body's origin and rotation. - /// Manipulating a body's transform may cause non-physical behavior. - /// Note: contacts are updated on the next call to b2World::Step. - /// @param position the world position of the body's local origin. - /// @param angle the world rotation in radians. - void SetTransform(const b2Vec2& position, float32 angle); - - /// Get the body transform for the body's origin. - /// @return the world transform of the body's origin. - const b2Transform& GetTransform() const; - - /// Get the world body origin position. - /// @return the world position of the body's origin. - const b2Vec2& GetPosition() const; - - /// Get the angle in radians. - /// @return the current world rotation angle in radians. - float32 GetAngle() const; - - /// Get the world position of the center of mass. - const b2Vec2& GetWorldCenter() const; - - /// Get the local position of the center of mass. - const b2Vec2& GetLocalCenter() const; - - /// Set the linear velocity of the center of mass. - /// @param v the new linear velocity of the center of mass. - void SetLinearVelocity(const b2Vec2& v); - - /// Get the linear velocity of the center of mass. - /// @return the linear velocity of the center of mass. - const b2Vec2& GetLinearVelocity() const; - - /// Set the angular velocity. - /// @param omega the new angular velocity in radians/second. - void SetAngularVelocity(float32 omega); - - /// Get the angular velocity. - /// @return the angular velocity in radians/second. - float32 GetAngularVelocity() const; - - /// Apply a force at a world point. If the force is not - /// applied at the center of mass, it will generate a torque and - /// affect the angular velocity. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - /// @param point the world position of the point of application. - /// @param wake also wake up the body - void ApplyForce(const b2Vec2& force, const b2Vec2& point, bool wake); - - /// Apply a force to the center of mass. This wakes up the body. - /// @param force the world force vector, usually in Newtons (N). - /// @param wake also wake up the body - void ApplyForceToCenter(const b2Vec2& force, bool wake); - - /// Apply a torque. This affects the angular velocity - /// without affecting the linear velocity of the center of mass. - /// @param torque about the z-axis (out of the screen), usually in N-m. - /// @param wake also wake up the body - void ApplyTorque(float32 torque, bool wake); - - /// Apply an impulse at a point. This immediately modifies the velocity. - /// It also modifies the angular velocity if the point of application - /// is not at the center of mass. This wakes up the body. - /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. - /// @param point the world position of the point of application. - /// @param wake also wake up the body - void ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point, bool wake); - - /// Apply an impulse to the center of mass. This immediately modifies the velocity. - /// @param impulse the world impulse vector, usually in N-seconds or kg-m/s. - /// @param wake also wake up the body - void ApplyLinearImpulseToCenter(const b2Vec2& impulse, bool wake); - - /// Apply an angular impulse. - /// @param impulse the angular impulse in units of kg*m*m/s - /// @param wake also wake up the body - void ApplyAngularImpulse(float32 impulse, bool wake); - - /// Get the total mass of the body. - /// @return the mass, usually in kilograms (kg). - float32 GetMass() const; - - /// Get the rotational inertia of the body about the local origin. - /// @return the rotational inertia, usually in kg-m^2. - float32 GetInertia() const; - - /// Get the mass data of the body. - /// @return a struct containing the mass, inertia and center of the body. - void GetMassData(b2MassData* data) const; - - /// Set the mass properties to override the mass properties of the fixtures. - /// Note that this changes the center of mass position. - /// Note that creating or destroying fixtures can also alter the mass. - /// This function has no effect if the body isn't dynamic. - /// @param massData the mass properties. - void SetMassData(const b2MassData* data); - - /// This resets the mass properties to the sum of the mass properties of the fixtures. - /// This normally does not need to be called unless you called SetMassData to override - /// the mass and you later want to reset the mass. - void ResetMassData(); - - /// Get the world coordinates of a point given the local coordinates. - /// @param localPoint a point on the body measured relative the the body's origin. - /// @return the same point expressed in world coordinates. - b2Vec2 GetWorldPoint(const b2Vec2& localPoint) const; - - /// Get the world coordinates of a vector given the local coordinates. - /// @param localVector a vector fixed in the body. - /// @return the same vector expressed in world coordinates. - b2Vec2 GetWorldVector(const b2Vec2& localVector) const; - - /// Gets a local point relative to the body's origin given a world point. - /// @param a point in world coordinates. - /// @return the corresponding local point relative to the body's origin. - b2Vec2 GetLocalPoint(const b2Vec2& worldPoint) const; - - /// Gets a local vector given a world vector. - /// @param a vector in world coordinates. - /// @return the corresponding local vector. - b2Vec2 GetLocalVector(const b2Vec2& worldVector) const; - - /// Get the world linear velocity of a world point attached to this body. - /// @param a point in world coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const; - - /// Get the world velocity of a local point. - /// @param a point in local coordinates. - /// @return the world velocity of a point. - b2Vec2 GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const; - - /// Get the linear damping of the body. - float32 GetLinearDamping() const; - - /// Set the linear damping of the body. - void SetLinearDamping(float32 linearDamping); - - /// Get the angular damping of the body. - float32 GetAngularDamping() const; - - /// Set the angular damping of the body. - void SetAngularDamping(float32 angularDamping); - - /// Get the gravity scale of the body. - float32 GetGravityScale() const; - - /// Set the gravity scale of the body. - void SetGravityScale(float32 scale); - - /// Set the type of this body. This may alter the mass and velocity. - void SetType(b2BodyType type); - - /// Get the type of this body. - b2BodyType GetType() const; - - /// Should this body be treated like a bullet for continuous collision detection? - void SetBullet(bool flag); - - /// Is this body treated like a bullet for continuous collision detection? - bool IsBullet() const; - - /// You can disable sleeping on this body. If you disable sleeping, the - /// body will be woken. - void SetSleepingAllowed(bool flag); - - /// Is this body allowed to sleep - bool IsSleepingAllowed() const; - - /// Set the sleep state of the body. A sleeping body has very - /// low CPU cost. - /// @param flag set to true to wake the body, false to put it to sleep. - void SetAwake(bool flag); - - /// Get the sleeping state of this body. - /// @return true if the body is awake. - bool IsAwake() const; - - /// Set the active state of the body. An inactive body is not - /// simulated and cannot be collided with or woken up. - /// If you pass a flag of true, all fixtures will be added to the - /// broad-phase. - /// If you pass a flag of false, all fixtures will be removed from - /// the broad-phase and all contacts will be destroyed. - /// Fixtures and joints are otherwise unaffected. You may continue - /// to create/destroy fixtures and joints on inactive bodies. - /// Fixtures on an inactive body are implicitly inactive and will - /// not participate in collisions, ray-casts, or queries. - /// Joints connected to an inactive body are implicitly inactive. - /// An inactive body is still owned by a b2World object and remains - /// in the body list. - void SetActive(bool flag); - - /// Get the active state of the body. - bool IsActive() const; - - /// Set this body to have fixed rotation. This causes the mass - /// to be reset. - void SetFixedRotation(bool flag); - - /// Does this body have fixed rotation? - bool IsFixedRotation() const; - - /// Get the list of all fixtures attached to this body. - b2Fixture* GetFixtureList(); - const b2Fixture* GetFixtureList() const; - - /// Get the list of all joints attached to this body. - b2JointEdge* GetJointList(); - const b2JointEdge* GetJointList() const; - - /// Get the list of all contacts attached to this body. - /// @warning this list changes during the time step and you may - /// miss some collisions if you don't use b2ContactListener. - b2ContactEdge* GetContactList(); - const b2ContactEdge* GetContactList() const; - - /// Get the next body in the world's body list. - b2Body* GetNext(); - const b2Body* GetNext() const; - - /// Get the user data pointer that was provided in the body definition. - void* GetUserData() const; - - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); - - /// Get the parent world of this body. - b2World* GetWorld(); - const b2World* GetWorld() const; - - /// Dump this body to a log file - void Dump(); - -private: - - friend class b2World; - friend class b2Island; - friend class b2ContactManager; - friend class b2ContactSolver; - friend class b2Contact; - - friend class b2DistanceJoint; - friend class b2FrictionJoint; - friend class b2GearJoint; - friend class b2MotorJoint; - friend class b2MouseJoint; - friend class b2PrismaticJoint; - friend class b2PulleyJoint; - friend class b2RevoluteJoint; - friend class b2RopeJoint; - friend class b2WeldJoint; - friend class b2WheelJoint; - - // m_flags - enum - { - e_islandFlag = 0x0001, - e_awakeFlag = 0x0002, - e_autoSleepFlag = 0x0004, - e_bulletFlag = 0x0008, - e_fixedRotationFlag = 0x0010, - e_activeFlag = 0x0020, - e_toiFlag = 0x0040 - }; - - b2Body(const b2BodyDef* bd, b2World* world); - ~b2Body(); - - void SynchronizeFixtures(); - void SynchronizeTransform(); - - // This is used to prevent connected bodies from colliding. - // It may lie, depending on the collideConnected flag. - bool ShouldCollide(const b2Body* other) const; - - void Advance(float32 t); - - b2BodyType m_type; - - uint16 m_flags; - - int32 m_islandIndex; - - b2Transform m_xf; // the body origin transform - b2Sweep m_sweep; // the swept motion for CCD - - b2Vec2 m_linearVelocity; - float32 m_angularVelocity; - - b2Vec2 m_force; - float32 m_torque; - - b2World* m_world; - b2Body* m_prev; - b2Body* m_next; - - b2Fixture* m_fixtureList; - int32 m_fixtureCount; - - b2JointEdge* m_jointList; - b2ContactEdge* m_contactList; - - float32 m_mass, m_invMass; - - // Rotational inertia about the center of mass. - float32 m_I, m_invI; - - float32 m_linearDamping; - float32 m_angularDamping; - float32 m_gravityScale; - - float32 m_sleepTime; - - void* m_userData; -}; - -inline b2BodyType b2Body::GetType() const -{ - return m_type; -} - -inline const b2Transform& b2Body::GetTransform() const -{ - return m_xf; -} - -inline const b2Vec2& b2Body::GetPosition() const -{ - return m_xf.p; -} - -inline float32 b2Body::GetAngle() const -{ - return m_sweep.a; -} - -inline const b2Vec2& b2Body::GetWorldCenter() const -{ - return m_sweep.c; -} - -inline const b2Vec2& b2Body::GetLocalCenter() const -{ - return m_sweep.localCenter; -} - -inline void b2Body::SetLinearVelocity(const b2Vec2& v) -{ - if (m_type == b2_staticBody) - { - return; - } - - if (b2Dot(v,v) > 0.0f) - { - SetAwake(true); - } - - m_linearVelocity = v; -} - -inline const b2Vec2& b2Body::GetLinearVelocity() const -{ - return m_linearVelocity; -} - -inline void b2Body::SetAngularVelocity(float32 w) -{ - if (m_type == b2_staticBody) - { - return; - } - - if (w * w > 0.0f) - { - SetAwake(true); - } - - m_angularVelocity = w; -} - -inline float32 b2Body::GetAngularVelocity() const -{ - return m_angularVelocity; -} - -inline float32 b2Body::GetMass() const -{ - return m_mass; -} - -inline float32 b2Body::GetInertia() const -{ - return m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); -} - -inline void b2Body::GetMassData(b2MassData* data) const -{ - data->mass = m_mass; - data->I = m_I + m_mass * b2Dot(m_sweep.localCenter, m_sweep.localCenter); - data->center = m_sweep.localCenter; -} - -inline b2Vec2 b2Body::GetWorldPoint(const b2Vec2& localPoint) const -{ - return b2Mul(m_xf, localPoint); -} - -inline b2Vec2 b2Body::GetWorldVector(const b2Vec2& localVector) const -{ - return b2Mul(m_xf.q, localVector); -} - -inline b2Vec2 b2Body::GetLocalPoint(const b2Vec2& worldPoint) const -{ - return b2MulT(m_xf, worldPoint); -} - -inline b2Vec2 b2Body::GetLocalVector(const b2Vec2& worldVector) const -{ - return b2MulT(m_xf.q, worldVector); -} - -inline b2Vec2 b2Body::GetLinearVelocityFromWorldPoint(const b2Vec2& worldPoint) const -{ - return m_linearVelocity + b2Cross(m_angularVelocity, worldPoint - m_sweep.c); -} - -inline b2Vec2 b2Body::GetLinearVelocityFromLocalPoint(const b2Vec2& localPoint) const -{ - return GetLinearVelocityFromWorldPoint(GetWorldPoint(localPoint)); -} - -inline float32 b2Body::GetLinearDamping() const -{ - return m_linearDamping; -} - -inline void b2Body::SetLinearDamping(float32 linearDamping) -{ - m_linearDamping = linearDamping; -} - -inline float32 b2Body::GetAngularDamping() const -{ - return m_angularDamping; -} - -inline void b2Body::SetAngularDamping(float32 angularDamping) -{ - m_angularDamping = angularDamping; -} - -inline float32 b2Body::GetGravityScale() const -{ - return m_gravityScale; -} - -inline void b2Body::SetGravityScale(float32 scale) -{ - m_gravityScale = scale; -} - -inline void b2Body::SetBullet(bool flag) -{ - if (flag) - { - m_flags |= e_bulletFlag; - } - else - { - m_flags &= ~e_bulletFlag; - } -} - -inline bool b2Body::IsBullet() const -{ - return (m_flags & e_bulletFlag) == e_bulletFlag; -} - -inline void b2Body::SetAwake(bool flag) -{ - if (flag) - { - m_flags |= e_awakeFlag; - m_sleepTime = 0.0f; - } - else - { - m_flags &= ~e_awakeFlag; - m_sleepTime = 0.0f; - m_linearVelocity.SetZero(); - m_angularVelocity = 0.0f; - m_force.SetZero(); - m_torque = 0.0f; - } -} - -inline bool b2Body::IsAwake() const -{ - return (m_flags & e_awakeFlag) == e_awakeFlag; -} - -inline bool b2Body::IsActive() const -{ - return (m_flags & e_activeFlag) == e_activeFlag; -} - -inline bool b2Body::IsFixedRotation() const -{ - return (m_flags & e_fixedRotationFlag) == e_fixedRotationFlag; -} - -inline void b2Body::SetSleepingAllowed(bool flag) -{ - if (flag) - { - m_flags |= e_autoSleepFlag; - } - else - { - m_flags &= ~e_autoSleepFlag; - SetAwake(true); - } -} - -inline bool b2Body::IsSleepingAllowed() const -{ - return (m_flags & e_autoSleepFlag) == e_autoSleepFlag; -} - -inline b2Fixture* b2Body::GetFixtureList() -{ - return m_fixtureList; -} - -inline const b2Fixture* b2Body::GetFixtureList() const -{ - return m_fixtureList; -} - -inline b2JointEdge* b2Body::GetJointList() -{ - return m_jointList; -} - -inline const b2JointEdge* b2Body::GetJointList() const -{ - return m_jointList; -} - -inline b2ContactEdge* b2Body::GetContactList() -{ - return m_contactList; -} - -inline const b2ContactEdge* b2Body::GetContactList() const -{ - return m_contactList; -} - -inline b2Body* b2Body::GetNext() -{ - return m_next; -} - -inline const b2Body* b2Body::GetNext() const -{ - return m_next; -} - -inline void b2Body::SetUserData(void* data) -{ - m_userData = data; -} - -inline void* b2Body::GetUserData() const -{ - return m_userData; -} - -inline void b2Body::ApplyForce(const b2Vec2& force, const b2Vec2& point, bool wake) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (wake && (m_flags & e_awakeFlag) == 0) - { - SetAwake(true); - } - - // Don't accumulate a force if the body is sleeping. - if (m_flags & e_awakeFlag) - { - m_force += force; - m_torque += b2Cross(point - m_sweep.c, force); - } -} - -inline void b2Body::ApplyForceToCenter(const b2Vec2& force, bool wake) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (wake && (m_flags & e_awakeFlag) == 0) - { - SetAwake(true); - } - - // Don't accumulate a force if the body is sleeping - if (m_flags & e_awakeFlag) - { - m_force += force; - } -} - -inline void b2Body::ApplyTorque(float32 torque, bool wake) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (wake && (m_flags & e_awakeFlag) == 0) - { - SetAwake(true); - } - - // Don't accumulate a force if the body is sleeping - if (m_flags & e_awakeFlag) - { - m_torque += torque; - } -} - -inline void b2Body::ApplyLinearImpulse(const b2Vec2& impulse, const b2Vec2& point, bool wake) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (wake && (m_flags & e_awakeFlag) == 0) - { - SetAwake(true); - } - - // Don't accumulate velocity if the body is sleeping - if (m_flags & e_awakeFlag) - { - m_linearVelocity += m_invMass * impulse; - m_angularVelocity += m_invI * b2Cross(point - m_sweep.c, impulse); - } -} - -inline void b2Body::ApplyLinearImpulseToCenter(const b2Vec2& impulse, bool wake) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (wake && (m_flags & e_awakeFlag) == 0) - { - SetAwake(true); - } - - // Don't accumulate velocity if the body is sleeping - if (m_flags & e_awakeFlag) - { - m_linearVelocity += m_invMass * impulse; - } -} - -inline void b2Body::ApplyAngularImpulse(float32 impulse, bool wake) -{ - if (m_type != b2_dynamicBody) - { - return; - } - - if (wake && (m_flags & e_awakeFlag) == 0) - { - SetAwake(true); - } - - // Don't accumulate velocity if the body is sleeping - if (m_flags & e_awakeFlag) - { - m_angularVelocity += m_invI * impulse; - } -} - -inline void b2Body::SynchronizeTransform() -{ - m_xf.q.Set(m_sweep.a); - m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); -} - -inline void b2Body::Advance(float32 alpha) -{ - // Advance to the new safe time. This doesn't sync the broad-phase. - m_sweep.Advance(alpha); - m_sweep.c = m_sweep.c0; - m_sweep.a = m_sweep.a0; - m_xf.q.Set(m_sweep.a); - m_xf.p = m_sweep.c - b2Mul(m_xf.q, m_sweep.localCenter); -} - -inline b2World* b2Body::GetWorld() -{ - return m_world; -} - -inline const b2World* b2Body::GetWorld() const -{ - return m_world; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/b2ContactManager.cpp b/libjin/3rdparty/Box2D/Dynamics/b2ContactManager.cpp deleted file mode 100644 index 051cc2f..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2ContactManager.cpp +++ /dev/null @@ -1,296 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/b2ContactManager.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2WorldCallbacks.h" -#include "Box2D/Dynamics/Contacts/b2Contact.h" - -b2ContactFilter b2_defaultFilter; -b2ContactListener b2_defaultListener; - -b2ContactManager::b2ContactManager() -{ - m_contactList = nullptr; - m_contactCount = 0; - m_contactFilter = &b2_defaultFilter; - m_contactListener = &b2_defaultListener; - m_allocator = nullptr; -} - -void b2ContactManager::Destroy(b2Contact* c) -{ - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - if (m_contactListener && c->IsTouching()) - { - m_contactListener->EndContact(c); - } - - // Remove from the world. - if (c->m_prev) - { - c->m_prev->m_next = c->m_next; - } - - if (c->m_next) - { - c->m_next->m_prev = c->m_prev; - } - - if (c == m_contactList) - { - m_contactList = c->m_next; - } - - // Remove from body 1 - if (c->m_nodeA.prev) - { - c->m_nodeA.prev->next = c->m_nodeA.next; - } - - if (c->m_nodeA.next) - { - c->m_nodeA.next->prev = c->m_nodeA.prev; - } - - if (&c->m_nodeA == bodyA->m_contactList) - { - bodyA->m_contactList = c->m_nodeA.next; - } - - // Remove from body 2 - if (c->m_nodeB.prev) - { - c->m_nodeB.prev->next = c->m_nodeB.next; - } - - if (c->m_nodeB.next) - { - c->m_nodeB.next->prev = c->m_nodeB.prev; - } - - if (&c->m_nodeB == bodyB->m_contactList) - { - bodyB->m_contactList = c->m_nodeB.next; - } - - // Call the factory. - b2Contact::Destroy(c, m_allocator); - --m_contactCount; -} - -// This is the top level collision call for the time step. Here -// all the narrow phase collision is processed for the world -// contact list. -void b2ContactManager::Collide() -{ - // Update awake contacts. - b2Contact* c = m_contactList; - while (c) - { - b2Fixture* fixtureA = c->GetFixtureA(); - b2Fixture* fixtureB = c->GetFixtureB(); - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - // Is this contact flagged for filtering? - if (c->m_flags & b2Contact::e_filterFlag) - { - // Should these bodies collide? - if (bodyB->ShouldCollide(bodyA) == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // Check user filtering. - if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // Clear the filtering flag. - c->m_flags &= ~b2Contact::e_filterFlag; - } - - bool activeA = bodyA->IsAwake() && bodyA->m_type != b2_staticBody; - bool activeB = bodyB->IsAwake() && bodyB->m_type != b2_staticBody; - - // At least one body must be awake and it must be dynamic or kinematic. - if (activeA == false && activeB == false) - { - c = c->GetNext(); - continue; - } - - int32 proxyIdA = fixtureA->m_proxies[indexA].proxyId; - int32 proxyIdB = fixtureB->m_proxies[indexB].proxyId; - bool overlap = m_broadPhase.TestOverlap(proxyIdA, proxyIdB); - - // Here we destroy contacts that cease to overlap in the broad-phase. - if (overlap == false) - { - b2Contact* cNuke = c; - c = cNuke->GetNext(); - Destroy(cNuke); - continue; - } - - // The contact persists. - c->Update(m_contactListener); - c = c->GetNext(); - } -} - -void b2ContactManager::FindNewContacts() -{ - m_broadPhase.UpdatePairs(this); -} - -void b2ContactManager::AddPair(void* proxyUserDataA, void* proxyUserDataB) -{ - b2FixtureProxy* proxyA = (b2FixtureProxy*)proxyUserDataA; - b2FixtureProxy* proxyB = (b2FixtureProxy*)proxyUserDataB; - - b2Fixture* fixtureA = proxyA->fixture; - b2Fixture* fixtureB = proxyB->fixture; - - int32 indexA = proxyA->childIndex; - int32 indexB = proxyB->childIndex; - - b2Body* bodyA = fixtureA->GetBody(); - b2Body* bodyB = fixtureB->GetBody(); - - // Are the fixtures on the same body? - if (bodyA == bodyB) - { - return; - } - - // TODO_ERIN use a hash table to remove a potential bottleneck when both - // bodies have a lot of contacts. - // Does a contact already exist? - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - b2Fixture* fA = edge->contact->GetFixtureA(); - b2Fixture* fB = edge->contact->GetFixtureB(); - int32 iA = edge->contact->GetChildIndexA(); - int32 iB = edge->contact->GetChildIndexB(); - - if (fA == fixtureA && fB == fixtureB && iA == indexA && iB == indexB) - { - // A contact already exists. - return; - } - - if (fA == fixtureB && fB == fixtureA && iA == indexB && iB == indexA) - { - // A contact already exists. - return; - } - } - - edge = edge->next; - } - - // Does a joint override collision? Is at least one body dynamic? - if (bodyB->ShouldCollide(bodyA) == false) - { - return; - } - - // Check user filtering. - if (m_contactFilter && m_contactFilter->ShouldCollide(fixtureA, fixtureB) == false) - { - return; - } - - // Call the factory. - b2Contact* c = b2Contact::Create(fixtureA, indexA, fixtureB, indexB, m_allocator); - if (c == nullptr) - { - return; - } - - // Contact creation may swap fixtures. - fixtureA = c->GetFixtureA(); - fixtureB = c->GetFixtureB(); - indexA = c->GetChildIndexA(); - indexB = c->GetChildIndexB(); - bodyA = fixtureA->GetBody(); - bodyB = fixtureB->GetBody(); - - // Insert into the world. - c->m_prev = nullptr; - c->m_next = m_contactList; - if (m_contactList != nullptr) - { - m_contactList->m_prev = c; - } - m_contactList = c; - - // Connect to island graph. - - // Connect to body A - c->m_nodeA.contact = c; - c->m_nodeA.other = bodyB; - - c->m_nodeA.prev = nullptr; - c->m_nodeA.next = bodyA->m_contactList; - if (bodyA->m_contactList != nullptr) - { - bodyA->m_contactList->prev = &c->m_nodeA; - } - bodyA->m_contactList = &c->m_nodeA; - - // Connect to body B - c->m_nodeB.contact = c; - c->m_nodeB.other = bodyA; - - c->m_nodeB.prev = nullptr; - c->m_nodeB.next = bodyB->m_contactList; - if (bodyB->m_contactList != nullptr) - { - bodyB->m_contactList->prev = &c->m_nodeB; - } - bodyB->m_contactList = &c->m_nodeB; - - // Wake up the bodies - if (fixtureA->IsSensor() == false && fixtureB->IsSensor() == false) - { - bodyA->SetAwake(true); - bodyB->SetAwake(true); - } - - ++m_contactCount; -} diff --git a/libjin/3rdparty/Box2D/Dynamics/b2ContactManager.h b/libjin/3rdparty/Box2D/Dynamics/b2ContactManager.h deleted file mode 100644 index 4c969e7..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2ContactManager.h +++ /dev/null @@ -1,52 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_CONTACT_MANAGER_H -#define B2_CONTACT_MANAGER_H - -#include "Box2D/Collision/b2BroadPhase.h" - -class b2Contact; -class b2ContactFilter; -class b2ContactListener; -class b2BlockAllocator; - -// Delegate of b2World. -class b2ContactManager -{ -public: - b2ContactManager(); - - // Broad-phase callback. - void AddPair(void* proxyUserDataA, void* proxyUserDataB); - - void FindNewContacts(); - - void Destroy(b2Contact* c); - - void Collide(); - - b2BroadPhase m_broadPhase; - b2Contact* m_contactList; - int32 m_contactCount; - b2ContactFilter* m_contactFilter; - b2ContactListener* m_contactListener; - b2BlockAllocator* m_allocator; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/b2Fixture.cpp b/libjin/3rdparty/Box2D/Dynamics/b2Fixture.cpp deleted file mode 100644 index 956b485..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2Fixture.cpp +++ /dev/null @@ -1,303 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/Contacts/b2Contact.h" -#include "Box2D/Dynamics/b2World.h" -#include "Box2D/Collision/Shapes/b2CircleShape.h" -#include "Box2D/Collision/Shapes/b2EdgeShape.h" -#include "Box2D/Collision/Shapes/b2PolygonShape.h" -#include "Box2D/Collision/Shapes/b2ChainShape.h" -#include "Box2D/Collision/b2BroadPhase.h" -#include "Box2D/Collision/b2Collision.h" -#include "Box2D/Common/b2BlockAllocator.h" - -b2Fixture::b2Fixture() -{ - m_userData = nullptr; - m_body = nullptr; - m_next = nullptr; - m_proxies = nullptr; - m_proxyCount = 0; - m_shape = nullptr; - m_density = 0.0f; -} - -void b2Fixture::Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def) -{ - m_userData = def->userData; - m_friction = def->friction; - m_restitution = def->restitution; - - m_body = body; - m_next = nullptr; - - m_filter = def->filter; - - m_isSensor = def->isSensor; - - m_shape = def->shape->Clone(allocator); - - // Reserve proxy space - int32 childCount = m_shape->GetChildCount(); - m_proxies = (b2FixtureProxy*)allocator->Allocate(childCount * sizeof(b2FixtureProxy)); - for (int32 i = 0; i < childCount; ++i) - { - m_proxies[i].fixture = nullptr; - m_proxies[i].proxyId = b2BroadPhase::e_nullProxy; - } - m_proxyCount = 0; - - m_density = def->density; -} - -void b2Fixture::Destroy(b2BlockAllocator* allocator) -{ - // The proxies must be destroyed before calling this. - b2Assert(m_proxyCount == 0); - - // Free the proxy array. - int32 childCount = m_shape->GetChildCount(); - allocator->Free(m_proxies, childCount * sizeof(b2FixtureProxy)); - m_proxies = nullptr; - - // Free the child shape. - switch (m_shape->m_type) - { - case b2Shape::e_circle: - { - b2CircleShape* s = (b2CircleShape*)m_shape; - s->~b2CircleShape(); - allocator->Free(s, sizeof(b2CircleShape)); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* s = (b2EdgeShape*)m_shape; - s->~b2EdgeShape(); - allocator->Free(s, sizeof(b2EdgeShape)); - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* s = (b2PolygonShape*)m_shape; - s->~b2PolygonShape(); - allocator->Free(s, sizeof(b2PolygonShape)); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* s = (b2ChainShape*)m_shape; - s->~b2ChainShape(); - allocator->Free(s, sizeof(b2ChainShape)); - } - break; - - default: - b2Assert(false); - break; - } - - m_shape = nullptr; -} - -void b2Fixture::CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf) -{ - b2Assert(m_proxyCount == 0); - - // Create proxies in the broad-phase. - m_proxyCount = m_shape->GetChildCount(); - - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - m_shape->ComputeAABB(&proxy->aabb, xf, i); - proxy->proxyId = broadPhase->CreateProxy(proxy->aabb, proxy); - proxy->fixture = this; - proxy->childIndex = i; - } -} - -void b2Fixture::DestroyProxies(b2BroadPhase* broadPhase) -{ - // Destroy proxies in the broad-phase. - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - broadPhase->DestroyProxy(proxy->proxyId); - proxy->proxyId = b2BroadPhase::e_nullProxy; - } - - m_proxyCount = 0; -} - -void b2Fixture::Synchronize(b2BroadPhase* broadPhase, const b2Transform& transform1, const b2Transform& transform2) -{ - if (m_proxyCount == 0) - { - return; - } - - for (int32 i = 0; i < m_proxyCount; ++i) - { - b2FixtureProxy* proxy = m_proxies + i; - - // Compute an AABB that covers the swept shape (may miss some rotation effect). - b2AABB aabb1, aabb2; - m_shape->ComputeAABB(&aabb1, transform1, proxy->childIndex); - m_shape->ComputeAABB(&aabb2, transform2, proxy->childIndex); - - proxy->aabb.Combine(aabb1, aabb2); - - b2Vec2 displacement = transform2.p - transform1.p; - - broadPhase->MoveProxy(proxy->proxyId, proxy->aabb, displacement); - } -} - -void b2Fixture::SetFilterData(const b2Filter& filter) -{ - m_filter = filter; - - Refilter(); -} - -void b2Fixture::Refilter() -{ - if (m_body == nullptr) - { - return; - } - - // Flag associated contacts for filtering. - b2ContactEdge* edge = m_body->GetContactList(); - while (edge) - { - b2Contact* contact = edge->contact; - b2Fixture* fixtureA = contact->GetFixtureA(); - b2Fixture* fixtureB = contact->GetFixtureB(); - if (fixtureA == this || fixtureB == this) - { - contact->FlagForFiltering(); - } - - edge = edge->next; - } - - b2World* world = m_body->GetWorld(); - - if (world == nullptr) - { - return; - } - - // Touch each proxy so that new pairs may be created - b2BroadPhase* broadPhase = &world->m_contactManager.m_broadPhase; - for (int32 i = 0; i < m_proxyCount; ++i) - { - broadPhase->TouchProxy(m_proxies[i].proxyId); - } -} - -void b2Fixture::SetSensor(bool sensor) -{ - if (sensor != m_isSensor) - { - m_body->SetAwake(true); - m_isSensor = sensor; - } -} - -void b2Fixture::Dump(int32 bodyIndex) -{ - b2Log(" b2FixtureDef fd;\n"); - b2Log(" fd.friction = %.15lef;\n", m_friction); - b2Log(" fd.restitution = %.15lef;\n", m_restitution); - b2Log(" fd.density = %.15lef;\n", m_density); - b2Log(" fd.isSensor = bool(%d);\n", m_isSensor); - b2Log(" fd.filter.categoryBits = uint16(%d);\n", m_filter.categoryBits); - b2Log(" fd.filter.maskBits = uint16(%d);\n", m_filter.maskBits); - b2Log(" fd.filter.groupIndex = int16(%d);\n", m_filter.groupIndex); - - switch (m_shape->m_type) - { - case b2Shape::e_circle: - { - b2CircleShape* s = (b2CircleShape*)m_shape; - b2Log(" b2CircleShape shape;\n"); - b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); - b2Log(" shape.m_p.Set(%.15lef, %.15lef);\n", s->m_p.x, s->m_p.y); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* s = (b2EdgeShape*)m_shape; - b2Log(" b2EdgeShape shape;\n"); - b2Log(" shape.m_radius = %.15lef;\n", s->m_radius); - b2Log(" shape.m_vertex0.Set(%.15lef, %.15lef);\n", s->m_vertex0.x, s->m_vertex0.y); - b2Log(" shape.m_vertex1.Set(%.15lef, %.15lef);\n", s->m_vertex1.x, s->m_vertex1.y); - b2Log(" shape.m_vertex2.Set(%.15lef, %.15lef);\n", s->m_vertex2.x, s->m_vertex2.y); - b2Log(" shape.m_vertex3.Set(%.15lef, %.15lef);\n", s->m_vertex3.x, s->m_vertex3.y); - b2Log(" shape.m_hasVertex0 = bool(%d);\n", s->m_hasVertex0); - b2Log(" shape.m_hasVertex3 = bool(%d);\n", s->m_hasVertex3); - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* s = (b2PolygonShape*)m_shape; - b2Log(" b2PolygonShape shape;\n"); - b2Log(" b2Vec2 vs[%d];\n", b2_maxPolygonVertices); - for (int32 i = 0; i < s->m_count; ++i) - { - b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); - } - b2Log(" shape.Set(vs, %d);\n", s->m_count); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* s = (b2ChainShape*)m_shape; - b2Log(" b2ChainShape shape;\n"); - b2Log(" b2Vec2 vs[%d];\n", s->m_count); - for (int32 i = 0; i < s->m_count; ++i) - { - b2Log(" vs[%d].Set(%.15lef, %.15lef);\n", i, s->m_vertices[i].x, s->m_vertices[i].y); - } - b2Log(" shape.CreateChain(vs, %d);\n", s->m_count); - b2Log(" shape.m_prevVertex.Set(%.15lef, %.15lef);\n", s->m_prevVertex.x, s->m_prevVertex.y); - b2Log(" shape.m_nextVertex.Set(%.15lef, %.15lef);\n", s->m_nextVertex.x, s->m_nextVertex.y); - b2Log(" shape.m_hasPrevVertex = bool(%d);\n", s->m_hasPrevVertex); - b2Log(" shape.m_hasNextVertex = bool(%d);\n", s->m_hasNextVertex); - } - break; - - default: - return; - } - - b2Log("\n"); - b2Log(" fd.shape = &shape;\n"); - b2Log("\n"); - b2Log(" bodies[%d]->CreateFixture(&fd);\n", bodyIndex); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/b2Fixture.h b/libjin/3rdparty/Box2D/Dynamics/b2Fixture.h deleted file mode 100644 index 9f7a8aa..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2Fixture.h +++ /dev/null @@ -1,345 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_FIXTURE_H -#define B2_FIXTURE_H - -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/Shapes/b2Shape.h" - -class b2BlockAllocator; -class b2Body; -class b2BroadPhase; -class b2Fixture; - -/// This holds contact filtering data. -struct b2Filter -{ - b2Filter() - { - categoryBits = 0x0001; - maskBits = 0xFFFF; - groupIndex = 0; - } - - /// The collision category bits. Normally you would just set one bit. - uint16 categoryBits; - - /// The collision mask bits. This states the categories that this - /// shape would accept for collision. - uint16 maskBits; - - /// Collision groups allow a certain group of objects to never collide (negative) - /// or always collide (positive). Zero means no collision group. Non-zero group - /// filtering always wins against the mask bits. - int16 groupIndex; -}; - -/// A fixture definition is used to create a fixture. This class defines an -/// abstract fixture definition. You can reuse fixture definitions safely. -struct b2FixtureDef -{ - /// The constructor sets the default fixture definition values. - b2FixtureDef() - { - shape = nullptr; - userData = nullptr; - friction = 0.2f; - restitution = 0.0f; - density = 0.0f; - isSensor = false; - } - - /// The shape, this must be set. The shape will be cloned, so you - /// can create the shape on the stack. - const b2Shape* shape; - - /// Use this to store application specific fixture data. - void* userData; - - /// The friction coefficient, usually in the range [0,1]. - float32 friction; - - /// The restitution (elasticity) usually in the range [0,1]. - float32 restitution; - - /// The density, usually in kg/m^2. - float32 density; - - /// A sensor shape collects contact information but never generates a collision - /// response. - bool isSensor; - - /// Contact filtering data. - b2Filter filter; -}; - -/// This proxy is used internally to connect fixtures to the broad-phase. -struct b2FixtureProxy -{ - b2AABB aabb; - b2Fixture* fixture; - int32 childIndex; - int32 proxyId; -}; - -/// A fixture is used to attach a shape to a body for collision detection. A fixture -/// inherits its transform from its parent. Fixtures hold additional non-geometric data -/// such as friction, collision filters, etc. -/// Fixtures are created via b2Body::CreateFixture. -/// @warning you cannot reuse fixtures. -class b2Fixture -{ -public: - /// Get the type of the child shape. You can use this to down cast to the concrete shape. - /// @return the shape type. - b2Shape::Type GetType() const; - - /// Get the child shape. You can modify the child shape, however you should not change the - /// number of vertices because this will crash some collision caching mechanisms. - /// Manipulating the shape may lead to non-physical behavior. - b2Shape* GetShape(); - const b2Shape* GetShape() const; - - /// Set if this fixture is a sensor. - void SetSensor(bool sensor); - - /// Is this fixture a sensor (non-solid)? - /// @return the true if the shape is a sensor. - bool IsSensor() const; - - /// Set the contact filtering data. This will not update contacts until the next time - /// step when either parent body is active and awake. - /// This automatically calls Refilter. - void SetFilterData(const b2Filter& filter); - - /// Get the contact filtering data. - const b2Filter& GetFilterData() const; - - /// Call this if you want to establish collision that was previously disabled by b2ContactFilter::ShouldCollide. - void Refilter(); - - /// Get the parent body of this fixture. This is nullptr if the fixture is not attached. - /// @return the parent body. - b2Body* GetBody(); - const b2Body* GetBody() const; - - /// Get the next fixture in the parent body's fixture list. - /// @return the next shape. - b2Fixture* GetNext(); - const b2Fixture* GetNext() const; - - /// Get the user data that was assigned in the fixture definition. Use this to - /// store your application specific data. - void* GetUserData() const; - - /// Set the user data. Use this to store your application specific data. - void SetUserData(void* data); - - /// Test a point for containment in this fixture. - /// @param p a point in world coordinates. - bool TestPoint(const b2Vec2& p) const; - - /// Cast a ray against this shape. - /// @param output the ray-cast results. - /// @param input the ray-cast input parameters. - bool RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const; - - /// Get the mass data for this fixture. The mass data is based on the density and - /// the shape. The rotational inertia is about the shape's origin. This operation - /// may be expensive. - void GetMassData(b2MassData* massData) const; - - /// Set the density of this fixture. This will _not_ automatically adjust the mass - /// of the body. You must call b2Body::ResetMassData to update the body's mass. - void SetDensity(float32 density); - - /// Get the density of this fixture. - float32 GetDensity() const; - - /// Get the coefficient of friction. - float32 GetFriction() const; - - /// Set the coefficient of friction. This will _not_ change the friction of - /// existing contacts. - void SetFriction(float32 friction); - - /// Get the coefficient of restitution. - float32 GetRestitution() const; - - /// Set the coefficient of restitution. This will _not_ change the restitution of - /// existing contacts. - void SetRestitution(float32 restitution); - - /// Get the fixture's AABB. This AABB may be enlarge and/or stale. - /// If you need a more accurate AABB, compute it using the shape and - /// the body transform. - const b2AABB& GetAABB(int32 childIndex) const; - - /// Dump this fixture to the log file. - void Dump(int32 bodyIndex); - -protected: - - friend class b2Body; - friend class b2World; - friend class b2Contact; - friend class b2ContactManager; - - b2Fixture(); - - // We need separation create/destroy functions from the constructor/destructor because - // the destructor cannot access the allocator (no destructor arguments allowed by C++). - void Create(b2BlockAllocator* allocator, b2Body* body, const b2FixtureDef* def); - void Destroy(b2BlockAllocator* allocator); - - // These support body activation/deactivation. - void CreateProxies(b2BroadPhase* broadPhase, const b2Transform& xf); - void DestroyProxies(b2BroadPhase* broadPhase); - - void Synchronize(b2BroadPhase* broadPhase, const b2Transform& xf1, const b2Transform& xf2); - - float32 m_density; - - b2Fixture* m_next; - b2Body* m_body; - - b2Shape* m_shape; - - float32 m_friction; - float32 m_restitution; - - b2FixtureProxy* m_proxies; - int32 m_proxyCount; - - b2Filter m_filter; - - bool m_isSensor; - - void* m_userData; -}; - -inline b2Shape::Type b2Fixture::GetType() const -{ - return m_shape->GetType(); -} - -inline b2Shape* b2Fixture::GetShape() -{ - return m_shape; -} - -inline const b2Shape* b2Fixture::GetShape() const -{ - return m_shape; -} - -inline bool b2Fixture::IsSensor() const -{ - return m_isSensor; -} - -inline const b2Filter& b2Fixture::GetFilterData() const -{ - return m_filter; -} - -inline void* b2Fixture::GetUserData() const -{ - return m_userData; -} - -inline void b2Fixture::SetUserData(void* data) -{ - m_userData = data; -} - -inline b2Body* b2Fixture::GetBody() -{ - return m_body; -} - -inline const b2Body* b2Fixture::GetBody() const -{ - return m_body; -} - -inline b2Fixture* b2Fixture::GetNext() -{ - return m_next; -} - -inline const b2Fixture* b2Fixture::GetNext() const -{ - return m_next; -} - -inline void b2Fixture::SetDensity(float32 density) -{ - b2Assert(b2IsValid(density) && density >= 0.0f); - m_density = density; -} - -inline float32 b2Fixture::GetDensity() const -{ - return m_density; -} - -inline float32 b2Fixture::GetFriction() const -{ - return m_friction; -} - -inline void b2Fixture::SetFriction(float32 friction) -{ - m_friction = friction; -} - -inline float32 b2Fixture::GetRestitution() const -{ - return m_restitution; -} - -inline void b2Fixture::SetRestitution(float32 restitution) -{ - m_restitution = restitution; -} - -inline bool b2Fixture::TestPoint(const b2Vec2& p) const -{ - return m_shape->TestPoint(m_body->GetTransform(), p); -} - -inline bool b2Fixture::RayCast(b2RayCastOutput* output, const b2RayCastInput& input, int32 childIndex) const -{ - return m_shape->RayCast(output, input, m_body->GetTransform(), childIndex); -} - -inline void b2Fixture::GetMassData(b2MassData* massData) const -{ - m_shape->ComputeMass(massData, m_density); -} - -inline const b2AABB& b2Fixture::GetAABB(int32 childIndex) const -{ - b2Assert(0 <= childIndex && childIndex < m_proxyCount); - return m_proxies[childIndex].aabb; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/b2Island.cpp b/libjin/3rdparty/Box2D/Dynamics/b2Island.cpp deleted file mode 100644 index dd19a8f..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2Island.cpp +++ /dev/null @@ -1,539 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Collision/b2Distance.h" -#include "Box2D/Dynamics/b2Island.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2World.h" -#include "Box2D/Dynamics/Contacts/b2Contact.h" -#include "Box2D/Dynamics/Contacts/b2ContactSolver.h" -#include "Box2D/Dynamics/Joints/b2Joint.h" -#include "Box2D/Common/b2StackAllocator.h" -#include "Box2D/Common/b2Timer.h" - -/* -Position Correction Notes -========================= -I tried the several algorithms for position correction of the 2D revolute joint. -I looked at these systems: -- simple pendulum (1m diameter sphere on massless 5m stick) with initial angular velocity of 100 rad/s. -- suspension bridge with 30 1m long planks of length 1m. -- multi-link chain with 30 1m long links. - -Here are the algorithms: - -Baumgarte - A fraction of the position error is added to the velocity error. There is no -separate position solver. - -Pseudo Velocities - After the velocity solver and position integration, -the position error, Jacobian, and effective mass are recomputed. Then -the velocity constraints are solved with pseudo velocities and a fraction -of the position error is added to the pseudo velocity error. The pseudo -velocities are initialized to zero and there is no warm-starting. After -the position solver, the pseudo velocities are added to the positions. -This is also called the First Order World method or the Position LCP method. - -Modified Nonlinear Gauss-Seidel (NGS) - Like Pseudo Velocities except the -position error is re-computed for each constraint and the positions are updated -after the constraint is solved. The radius vectors (aka Jacobians) are -re-computed too (otherwise the algorithm has horrible instability). The pseudo -velocity states are not needed because they are effectively zero at the beginning -of each iteration. Since we have the current position error, we allow the -iterations to terminate early if the error becomes smaller than b2_linearSlop. - -Full NGS or just NGS - Like Modified NGS except the effective mass are re-computed -each time a constraint is solved. - -Here are the results: -Baumgarte - this is the cheapest algorithm but it has some stability problems, -especially with the bridge. The chain links separate easily close to the root -and they jitter as they struggle to pull together. This is one of the most common -methods in the field. The big drawback is that the position correction artificially -affects the momentum, thus leading to instabilities and false bounce. I used a -bias factor of 0.2. A larger bias factor makes the bridge less stable, a smaller -factor makes joints and contacts more spongy. - -Pseudo Velocities - the is more stable than the Baumgarte method. The bridge is -stable. However, joints still separate with large angular velocities. Drag the -simple pendulum in a circle quickly and the joint will separate. The chain separates -easily and does not recover. I used a bias factor of 0.2. A larger value lead to -the bridge collapsing when a heavy cube drops on it. - -Modified NGS - this algorithm is better in some ways than Baumgarte and Pseudo -Velocities, but in other ways it is worse. The bridge and chain are much more -stable, but the simple pendulum goes unstable at high angular velocities. - -Full NGS - stable in all tests. The joints display good stiffness. The bridge -still sags, but this is better than infinite forces. - -Recommendations -Pseudo Velocities are not really worthwhile because the bridge and chain cannot -recover from joint separation. In other cases the benefit over Baumgarte is small. - -Modified NGS is not a robust method for the revolute joint due to the violent -instability seen in the simple pendulum. Perhaps it is viable with other constraint -types, especially scalar constraints where the effective mass is a scalar. - -This leaves Baumgarte and Full NGS. Baumgarte has small, but manageable instabilities -and is very fast. I don't think we can escape Baumgarte, especially in highly -demanding cases where high constraint fidelity is not needed. - -Full NGS is robust and easy on the eyes. I recommend this as an option for -higher fidelity simulation and certainly for suspension bridges and long chains. -Full NGS might be a good choice for ragdolls, especially motorized ragdolls where -joint separation can be problematic. The number of NGS iterations can be reduced -for better performance without harming robustness much. - -Each joint in a can be handled differently in the position solver. So I recommend -a system where the user can select the algorithm on a per joint basis. I would -probably default to the slower Full NGS and let the user select the faster -Baumgarte method in performance critical scenarios. -*/ - -/* -Cache Performance - -The Box2D solvers are dominated by cache misses. Data structures are designed -to increase the number of cache hits. Much of misses are due to random access -to body data. The constraint structures are iterated over linearly, which leads -to few cache misses. - -The bodies are not accessed during iteration. Instead read only data, such as -the mass values are stored with the constraints. The mutable data are the constraint -impulses and the bodies velocities/positions. The impulses are held inside the -constraint structures. The body velocities/positions are held in compact, temporary -arrays to increase the number of cache hits. Linear and angular velocity are -stored in a single array since multiple arrays lead to multiple misses. -*/ - -/* -2D Rotation - -R = [cos(theta) -sin(theta)] - [sin(theta) cos(theta) ] - -thetaDot = omega - -Let q1 = cos(theta), q2 = sin(theta). -R = [q1 -q2] - [q2 q1] - -q1Dot = -thetaDot * q2 -q2Dot = thetaDot * q1 - -q1_new = q1_old - dt * w * q2 -q2_new = q2_old + dt * w * q1 -then normalize. - -This might be faster than computing sin+cos. -However, we can compute sin+cos of the same angle fast. -*/ - -b2Island::b2Island( - int32 bodyCapacity, - int32 contactCapacity, - int32 jointCapacity, - b2StackAllocator* allocator, - b2ContactListener* listener) -{ - m_bodyCapacity = bodyCapacity; - m_contactCapacity = contactCapacity; - m_jointCapacity = jointCapacity; - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; - - m_allocator = allocator; - m_listener = listener; - - m_bodies = (b2Body**)m_allocator->Allocate(bodyCapacity * sizeof(b2Body*)); - m_contacts = (b2Contact**)m_allocator->Allocate(contactCapacity * sizeof(b2Contact*)); - m_joints = (b2Joint**)m_allocator->Allocate(jointCapacity * sizeof(b2Joint*)); - - m_velocities = (b2Velocity*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Velocity)); - m_positions = (b2Position*)m_allocator->Allocate(m_bodyCapacity * sizeof(b2Position)); -} - -b2Island::~b2Island() -{ - // Warning: the order should reverse the constructor order. - m_allocator->Free(m_positions); - m_allocator->Free(m_velocities); - m_allocator->Free(m_joints); - m_allocator->Free(m_contacts); - m_allocator->Free(m_bodies); -} - -void b2Island::Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep) -{ - b2Timer timer; - - float32 h = step.dt; - - // Integrate velocities and apply damping. Initialize the body state. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - - b2Vec2 c = b->m_sweep.c; - float32 a = b->m_sweep.a; - b2Vec2 v = b->m_linearVelocity; - float32 w = b->m_angularVelocity; - - // Store positions for continuous collision. - b->m_sweep.c0 = b->m_sweep.c; - b->m_sweep.a0 = b->m_sweep.a; - - if (b->m_type == b2_dynamicBody) - { - // Integrate velocities. - v += h * (b->m_gravityScale * gravity + b->m_invMass * b->m_force); - w += h * b->m_invI * b->m_torque; - - // Apply damping. - // ODE: dv/dt + c * v = 0 - // Solution: v(t) = v0 * exp(-c * t) - // Time step: v(t + dt) = v0 * exp(-c * (t + dt)) = v0 * exp(-c * t) * exp(-c * dt) = v * exp(-c * dt) - // v2 = exp(-c * dt) * v1 - // Pade approximation: - // v2 = v1 * 1 / (1 + c * dt) - v *= 1.0f / (1.0f + h * b->m_linearDamping); - w *= 1.0f / (1.0f + h * b->m_angularDamping); - } - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - } - - timer.Reset(); - - // Solver data - b2SolverData solverData; - solverData.step = step; - solverData.positions = m_positions; - solverData.velocities = m_velocities; - - // Initialize velocity constraints. - b2ContactSolverDef contactSolverDef; - contactSolverDef.step = step; - contactSolverDef.contacts = m_contacts; - contactSolverDef.count = m_contactCount; - contactSolverDef.positions = m_positions; - contactSolverDef.velocities = m_velocities; - contactSolverDef.allocator = m_allocator; - - b2ContactSolver contactSolver(&contactSolverDef); - contactSolver.InitializeVelocityConstraints(); - - if (step.warmStarting) - { - contactSolver.WarmStart(); - } - - for (int32 i = 0; i < m_jointCount; ++i) - { - m_joints[i]->InitVelocityConstraints(solverData); - } - - profile->solveInit = timer.GetMilliseconds(); - - // Solve velocity constraints - timer.Reset(); - for (int32 i = 0; i < step.velocityIterations; ++i) - { - for (int32 j = 0; j < m_jointCount; ++j) - { - m_joints[j]->SolveVelocityConstraints(solverData); - } - - contactSolver.SolveVelocityConstraints(); - } - - // Store impulses for warm starting - contactSolver.StoreImpulses(); - profile->solveVelocity = timer.GetMilliseconds(); - - // Integrate positions - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Vec2 c = m_positions[i].c; - float32 a = m_positions[i].a; - b2Vec2 v = m_velocities[i].v; - float32 w = m_velocities[i].w; - - // Check for large velocities - b2Vec2 translation = h * v; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - v *= ratio; - } - - float32 rotation = h * w; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - w *= ratio; - } - - // Integrate - c += h * v; - a += h * w; - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - } - - // Solve position constraints - timer.Reset(); - bool positionSolved = false; - for (int32 i = 0; i < step.positionIterations; ++i) - { - bool contactsOkay = contactSolver.SolvePositionConstraints(); - - bool jointsOkay = true; - for (int32 j = 0; j < m_jointCount; ++j) - { - bool jointOkay = m_joints[j]->SolvePositionConstraints(solverData); - jointsOkay = jointsOkay && jointOkay; - } - - if (contactsOkay && jointsOkay) - { - // Exit early if the position errors are small. - positionSolved = true; - break; - } - } - - // Copy state buffers back to the bodies - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* body = m_bodies[i]; - body->m_sweep.c = m_positions[i].c; - body->m_sweep.a = m_positions[i].a; - body->m_linearVelocity = m_velocities[i].v; - body->m_angularVelocity = m_velocities[i].w; - body->SynchronizeTransform(); - } - - profile->solvePosition = timer.GetMilliseconds(); - - Report(contactSolver.m_velocityConstraints); - - if (allowSleep) - { - float32 minSleepTime = b2_maxFloat; - - const float32 linTolSqr = b2_linearSleepTolerance * b2_linearSleepTolerance; - const float32 angTolSqr = b2_angularSleepTolerance * b2_angularSleepTolerance; - - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - if (b->GetType() == b2_staticBody) - { - continue; - } - - if ((b->m_flags & b2Body::e_autoSleepFlag) == 0 || - b->m_angularVelocity * b->m_angularVelocity > angTolSqr || - b2Dot(b->m_linearVelocity, b->m_linearVelocity) > linTolSqr) - { - b->m_sleepTime = 0.0f; - minSleepTime = 0.0f; - } - else - { - b->m_sleepTime += h; - minSleepTime = b2Min(minSleepTime, b->m_sleepTime); - } - } - - if (minSleepTime >= b2_timeToSleep && positionSolved) - { - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - b->SetAwake(false); - } - } - } -} - -void b2Island::SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB) -{ - b2Assert(toiIndexA < m_bodyCount); - b2Assert(toiIndexB < m_bodyCount); - - // Initialize the body state. - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Body* b = m_bodies[i]; - m_positions[i].c = b->m_sweep.c; - m_positions[i].a = b->m_sweep.a; - m_velocities[i].v = b->m_linearVelocity; - m_velocities[i].w = b->m_angularVelocity; - } - - b2ContactSolverDef contactSolverDef; - contactSolverDef.contacts = m_contacts; - contactSolverDef.count = m_contactCount; - contactSolverDef.allocator = m_allocator; - contactSolverDef.step = subStep; - contactSolverDef.positions = m_positions; - contactSolverDef.velocities = m_velocities; - b2ContactSolver contactSolver(&contactSolverDef); - - // Solve position constraints. - for (int32 i = 0; i < subStep.positionIterations; ++i) - { - bool contactsOkay = contactSolver.SolveTOIPositionConstraints(toiIndexA, toiIndexB); - if (contactsOkay) - { - break; - } - } - -#if 0 - // Is the new position really safe? - for (int32 i = 0; i < m_contactCount; ++i) - { - b2Contact* c = m_contacts[i]; - b2Fixture* fA = c->GetFixtureA(); - b2Fixture* fB = c->GetFixtureB(); - - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - - b2DistanceInput input; - input.proxyA.Set(fA->GetShape(), indexA); - input.proxyB.Set(fB->GetShape(), indexB); - input.transformA = bA->GetTransform(); - input.transformB = bB->GetTransform(); - input.useRadii = false; - - b2DistanceOutput output; - b2SimplexCache cache; - cache.count = 0; - b2Distance(&output, &cache, &input); - - if (output.distance == 0 || cache.count == 3) - { - cache.count += 0; - } - } -#endif - - // Leap of faith to new safe state. - m_bodies[toiIndexA]->m_sweep.c0 = m_positions[toiIndexA].c; - m_bodies[toiIndexA]->m_sweep.a0 = m_positions[toiIndexA].a; - m_bodies[toiIndexB]->m_sweep.c0 = m_positions[toiIndexB].c; - m_bodies[toiIndexB]->m_sweep.a0 = m_positions[toiIndexB].a; - - // No warm starting is needed for TOI events because warm - // starting impulses were applied in the discrete solver. - contactSolver.InitializeVelocityConstraints(); - - // Solve velocity constraints. - for (int32 i = 0; i < subStep.velocityIterations; ++i) - { - contactSolver.SolveVelocityConstraints(); - } - - // Don't store the TOI contact forces for warm starting - // because they can be quite large. - - float32 h = subStep.dt; - - // Integrate positions - for (int32 i = 0; i < m_bodyCount; ++i) - { - b2Vec2 c = m_positions[i].c; - float32 a = m_positions[i].a; - b2Vec2 v = m_velocities[i].v; - float32 w = m_velocities[i].w; - - // Check for large velocities - b2Vec2 translation = h * v; - if (b2Dot(translation, translation) > b2_maxTranslationSquared) - { - float32 ratio = b2_maxTranslation / translation.Length(); - v *= ratio; - } - - float32 rotation = h * w; - if (rotation * rotation > b2_maxRotationSquared) - { - float32 ratio = b2_maxRotation / b2Abs(rotation); - w *= ratio; - } - - // Integrate - c += h * v; - a += h * w; - - m_positions[i].c = c; - m_positions[i].a = a; - m_velocities[i].v = v; - m_velocities[i].w = w; - - // Sync bodies - b2Body* body = m_bodies[i]; - body->m_sweep.c = c; - body->m_sweep.a = a; - body->m_linearVelocity = v; - body->m_angularVelocity = w; - body->SynchronizeTransform(); - } - - Report(contactSolver.m_velocityConstraints); -} - -void b2Island::Report(const b2ContactVelocityConstraint* constraints) -{ - if (m_listener == nullptr) - { - return; - } - - for (int32 i = 0; i < m_contactCount; ++i) - { - b2Contact* c = m_contacts[i]; - - const b2ContactVelocityConstraint* vc = constraints + i; - - b2ContactImpulse impulse; - impulse.count = vc->pointCount; - for (int32 j = 0; j < vc->pointCount; ++j) - { - impulse.normalImpulses[j] = vc->points[j].normalImpulse; - impulse.tangentImpulses[j] = vc->points[j].tangentImpulse; - } - - m_listener->PostSolve(c, &impulse); - } -} diff --git a/libjin/3rdparty/Box2D/Dynamics/b2Island.h b/libjin/3rdparty/Box2D/Dynamics/b2Island.h deleted file mode 100644 index 68f6d4b..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2Island.h +++ /dev/null @@ -1,93 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_ISLAND_H -#define B2_ISLAND_H - -#include "Box2D/Common/b2Math.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -class b2Contact; -class b2Joint; -class b2StackAllocator; -class b2ContactListener; -struct b2ContactVelocityConstraint; -struct b2Profile; - -/// This is an internal class. -class b2Island -{ -public: - b2Island(int32 bodyCapacity, int32 contactCapacity, int32 jointCapacity, - b2StackAllocator* allocator, b2ContactListener* listener); - ~b2Island(); - - void Clear() - { - m_bodyCount = 0; - m_contactCount = 0; - m_jointCount = 0; - } - - void Solve(b2Profile* profile, const b2TimeStep& step, const b2Vec2& gravity, bool allowSleep); - - void SolveTOI(const b2TimeStep& subStep, int32 toiIndexA, int32 toiIndexB); - - void Add(b2Body* body) - { - b2Assert(m_bodyCount < m_bodyCapacity); - body->m_islandIndex = m_bodyCount; - m_bodies[m_bodyCount] = body; - ++m_bodyCount; - } - - void Add(b2Contact* contact) - { - b2Assert(m_contactCount < m_contactCapacity); - m_contacts[m_contactCount++] = contact; - } - - void Add(b2Joint* joint) - { - b2Assert(m_jointCount < m_jointCapacity); - m_joints[m_jointCount++] = joint; - } - - void Report(const b2ContactVelocityConstraint* constraints); - - b2StackAllocator* m_allocator; - b2ContactListener* m_listener; - - b2Body** m_bodies; - b2Contact** m_contacts; - b2Joint** m_joints; - - b2Position* m_positions; - b2Velocity* m_velocities; - - int32 m_bodyCount; - int32 m_jointCount; - int32 m_contactCount; - - int32 m_bodyCapacity; - int32 m_contactCapacity; - int32 m_jointCapacity; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/b2TimeStep.h b/libjin/3rdparty/Box2D/Dynamics/b2TimeStep.h deleted file mode 100644 index 72a4838..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2TimeStep.h +++ /dev/null @@ -1,70 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_TIME_STEP_H -#define B2_TIME_STEP_H - -#include "Box2D/Common/b2Math.h" - -/// Profiling data. Times are in milliseconds. -struct b2Profile -{ - float32 step; - float32 collide; - float32 solve; - float32 solveInit; - float32 solveVelocity; - float32 solvePosition; - float32 broadphase; - float32 solveTOI; -}; - -/// This is an internal structure. -struct b2TimeStep -{ - float32 dt; // time step - float32 inv_dt; // inverse time step (0 if dt == 0). - float32 dtRatio; // dt * inv_dt0 - int32 velocityIterations; - int32 positionIterations; - bool warmStarting; -}; - -/// This is an internal structure. -struct b2Position -{ - b2Vec2 c; - float32 a; -}; - -/// This is an internal structure. -struct b2Velocity -{ - b2Vec2 v; - float32 w; -}; - -/// Solver Data -struct b2SolverData -{ - b2TimeStep step; - b2Position* positions; - b2Velocity* velocities; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/b2World.cpp b/libjin/3rdparty/Box2D/Dynamics/b2World.cpp deleted file mode 100644 index f21812e..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2World.cpp +++ /dev/null @@ -1,1366 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/b2World.h" -#include "Box2D/Dynamics/b2Body.h" -#include "Box2D/Dynamics/b2Fixture.h" -#include "Box2D/Dynamics/b2Island.h" -#include "Box2D/Dynamics/Joints/b2PulleyJoint.h" -#include "Box2D/Dynamics/Contacts/b2Contact.h" -#include "Box2D/Dynamics/Contacts/b2ContactSolver.h" -#include "Box2D/Collision/b2Collision.h" -#include "Box2D/Collision/b2BroadPhase.h" -#include "Box2D/Collision/Shapes/b2CircleShape.h" -#include "Box2D/Collision/Shapes/b2EdgeShape.h" -#include "Box2D/Collision/Shapes/b2ChainShape.h" -#include "Box2D/Collision/Shapes/b2PolygonShape.h" -#include "Box2D/Collision/b2TimeOfImpact.h" -#include "Box2D/Common/b2Draw.h" -#include "Box2D/Common/b2Timer.h" -#include <new> - -b2World::b2World(const b2Vec2& gravity) -{ - m_destructionListener = nullptr; - m_debugDraw = nullptr; - - m_bodyList = nullptr; - m_jointList = nullptr; - - m_bodyCount = 0; - m_jointCount = 0; - - m_warmStarting = true; - m_continuousPhysics = true; - m_subStepping = false; - - m_stepComplete = true; - - m_allowSleep = true; - m_gravity = gravity; - - m_flags = e_clearForces; - - m_inv_dt0 = 0.0f; - - m_contactManager.m_allocator = &m_blockAllocator; - - memset(&m_profile, 0, sizeof(b2Profile)); -} - -b2World::~b2World() -{ - // Some shapes allocate using b2Alloc. - b2Body* b = m_bodyList; - while (b) - { - b2Body* bNext = b->m_next; - - b2Fixture* f = b->m_fixtureList; - while (f) - { - b2Fixture* fNext = f->m_next; - f->m_proxyCount = 0; - f->Destroy(&m_blockAllocator); - f = fNext; - } - - b = bNext; - } -} - -void b2World::SetDestructionListener(b2DestructionListener* listener) -{ - m_destructionListener = listener; -} - -void b2World::SetContactFilter(b2ContactFilter* filter) -{ - m_contactManager.m_contactFilter = filter; -} - -void b2World::SetContactListener(b2ContactListener* listener) -{ - m_contactManager.m_contactListener = listener; -} - -void b2World::SetDebugDraw(b2Draw* debugDraw) -{ - m_debugDraw = debugDraw; -} - -b2Body* b2World::CreateBody(const b2BodyDef* def) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return nullptr; - } - - void* mem = m_blockAllocator.Allocate(sizeof(b2Body)); - b2Body* b = new (mem) b2Body(def, this); - - // Add to world doubly linked list. - b->m_prev = nullptr; - b->m_next = m_bodyList; - if (m_bodyList) - { - m_bodyList->m_prev = b; - } - m_bodyList = b; - ++m_bodyCount; - - return b; -} - -void b2World::DestroyBody(b2Body* b) -{ - b2Assert(m_bodyCount > 0); - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return; - } - - // Delete the attached joints. - b2JointEdge* je = b->m_jointList; - while (je) - { - b2JointEdge* je0 = je; - je = je->next; - - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(je0->joint); - } - - DestroyJoint(je0->joint); - - b->m_jointList = je; - } - b->m_jointList = nullptr; - - // Delete the attached contacts. - b2ContactEdge* ce = b->m_contactList; - while (ce) - { - b2ContactEdge* ce0 = ce; - ce = ce->next; - m_contactManager.Destroy(ce0->contact); - } - b->m_contactList = nullptr; - - // Delete the attached fixtures. This destroys broad-phase proxies. - b2Fixture* f = b->m_fixtureList; - while (f) - { - b2Fixture* f0 = f; - f = f->m_next; - - if (m_destructionListener) - { - m_destructionListener->SayGoodbye(f0); - } - - f0->DestroyProxies(&m_contactManager.m_broadPhase); - f0->Destroy(&m_blockAllocator); - f0->~b2Fixture(); - m_blockAllocator.Free(f0, sizeof(b2Fixture)); - - b->m_fixtureList = f; - b->m_fixtureCount -= 1; - } - b->m_fixtureList = nullptr; - b->m_fixtureCount = 0; - - // Remove world body list. - if (b->m_prev) - { - b->m_prev->m_next = b->m_next; - } - - if (b->m_next) - { - b->m_next->m_prev = b->m_prev; - } - - if (b == m_bodyList) - { - m_bodyList = b->m_next; - } - - --m_bodyCount; - b->~b2Body(); - m_blockAllocator.Free(b, sizeof(b2Body)); -} - -b2Joint* b2World::CreateJoint(const b2JointDef* def) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return nullptr; - } - - b2Joint* j = b2Joint::Create(def, &m_blockAllocator); - - // Connect to the world list. - j->m_prev = nullptr; - j->m_next = m_jointList; - if (m_jointList) - { - m_jointList->m_prev = j; - } - m_jointList = j; - ++m_jointCount; - - // Connect to the bodies' doubly linked lists. - j->m_edgeA.joint = j; - j->m_edgeA.other = j->m_bodyB; - j->m_edgeA.prev = nullptr; - j->m_edgeA.next = j->m_bodyA->m_jointList; - if (j->m_bodyA->m_jointList) j->m_bodyA->m_jointList->prev = &j->m_edgeA; - j->m_bodyA->m_jointList = &j->m_edgeA; - - j->m_edgeB.joint = j; - j->m_edgeB.other = j->m_bodyA; - j->m_edgeB.prev = nullptr; - j->m_edgeB.next = j->m_bodyB->m_jointList; - if (j->m_bodyB->m_jointList) j->m_bodyB->m_jointList->prev = &j->m_edgeB; - j->m_bodyB->m_jointList = &j->m_edgeB; - - b2Body* bodyA = def->bodyA; - b2Body* bodyB = def->bodyB; - - // If the joint prevents collisions, then flag any contacts for filtering. - if (def->collideConnected == false) - { - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - // Flag the contact for filtering at the next time step (where either - // body is awake). - edge->contact->FlagForFiltering(); - } - - edge = edge->next; - } - } - - // Note: creating a joint doesn't wake the bodies. - - return j; -} - -void b2World::DestroyJoint(b2Joint* j) -{ - b2Assert(IsLocked() == false); - if (IsLocked()) - { - return; - } - - bool collideConnected = j->m_collideConnected; - - // Remove from the doubly linked list. - if (j->m_prev) - { - j->m_prev->m_next = j->m_next; - } - - if (j->m_next) - { - j->m_next->m_prev = j->m_prev; - } - - if (j == m_jointList) - { - m_jointList = j->m_next; - } - - // Disconnect from island graph. - b2Body* bodyA = j->m_bodyA; - b2Body* bodyB = j->m_bodyB; - - // Wake up connected bodies. - bodyA->SetAwake(true); - bodyB->SetAwake(true); - - // Remove from body 1. - if (j->m_edgeA.prev) - { - j->m_edgeA.prev->next = j->m_edgeA.next; - } - - if (j->m_edgeA.next) - { - j->m_edgeA.next->prev = j->m_edgeA.prev; - } - - if (&j->m_edgeA == bodyA->m_jointList) - { - bodyA->m_jointList = j->m_edgeA.next; - } - - j->m_edgeA.prev = nullptr; - j->m_edgeA.next = nullptr; - - // Remove from body 2 - if (j->m_edgeB.prev) - { - j->m_edgeB.prev->next = j->m_edgeB.next; - } - - if (j->m_edgeB.next) - { - j->m_edgeB.next->prev = j->m_edgeB.prev; - } - - if (&j->m_edgeB == bodyB->m_jointList) - { - bodyB->m_jointList = j->m_edgeB.next; - } - - j->m_edgeB.prev = nullptr; - j->m_edgeB.next = nullptr; - - b2Joint::Destroy(j, &m_blockAllocator); - - b2Assert(m_jointCount > 0); - --m_jointCount; - - // If the joint prevents collisions, then flag any contacts for filtering. - if (collideConnected == false) - { - b2ContactEdge* edge = bodyB->GetContactList(); - while (edge) - { - if (edge->other == bodyA) - { - // Flag the contact for filtering at the next time step (where either - // body is awake). - edge->contact->FlagForFiltering(); - } - - edge = edge->next; - } - } -} - -// -void b2World::SetAllowSleeping(bool flag) -{ - if (flag == m_allowSleep) - { - return; - } - - m_allowSleep = flag; - if (m_allowSleep == false) - { - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->SetAwake(true); - } - } -} - -// Find islands, integrate and solve constraints, solve position constraints -void b2World::Solve(const b2TimeStep& step) -{ - m_profile.solveInit = 0.0f; - m_profile.solveVelocity = 0.0f; - m_profile.solvePosition = 0.0f; - - // Size the island for the worst case. - b2Island island(m_bodyCount, - m_contactManager.m_contactCount, - m_jointCount, - &m_stackAllocator, - m_contactManager.m_contactListener); - - // Clear all the island flags. - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - c->m_flags &= ~b2Contact::e_islandFlag; - } - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_islandFlag = false; - } - - // Build and simulate all awake islands. - int32 stackSize = m_bodyCount; - b2Body** stack = (b2Body**)m_stackAllocator.Allocate(stackSize * sizeof(b2Body*)); - for (b2Body* seed = m_bodyList; seed; seed = seed->m_next) - { - if (seed->m_flags & b2Body::e_islandFlag) - { - continue; - } - - if (seed->IsAwake() == false || seed->IsActive() == false) - { - continue; - } - - // The seed can be dynamic or kinematic. - if (seed->GetType() == b2_staticBody) - { - continue; - } - - // Reset island and stack. - island.Clear(); - int32 stackCount = 0; - stack[stackCount++] = seed; - seed->m_flags |= b2Body::e_islandFlag; - - // Perform a depth first search (DFS) on the constraint graph. - while (stackCount > 0) - { - // Grab the next body off the stack and add it to the island. - b2Body* b = stack[--stackCount]; - b2Assert(b->IsActive() == true); - island.Add(b); - - // Make sure the body is awake (without resetting sleep timer). - b->m_flags |= b2Body::e_awakeFlag; - - // To keep islands as small as possible, we don't - // propagate islands across static bodies. - if (b->GetType() == b2_staticBody) - { - continue; - } - - // Search all contacts connected to this body. - for (b2ContactEdge* ce = b->m_contactList; ce; ce = ce->next) - { - b2Contact* contact = ce->contact; - - // Has this contact already been added to an island? - if (contact->m_flags & b2Contact::e_islandFlag) - { - continue; - } - - // Is this contact solid and touching? - if (contact->IsEnabled() == false || - contact->IsTouching() == false) - { - continue; - } - - // Skip sensors. - bool sensorA = contact->m_fixtureA->m_isSensor; - bool sensorB = contact->m_fixtureB->m_isSensor; - if (sensorA || sensorB) - { - continue; - } - - island.Add(contact); - contact->m_flags |= b2Contact::e_islandFlag; - - b2Body* other = ce->other; - - // Was the other body already added to this island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - - // Search all joints connect to this body. - for (b2JointEdge* je = b->m_jointList; je; je = je->next) - { - if (je->joint->m_islandFlag == true) - { - continue; - } - - b2Body* other = je->other; - - // Don't simulate joints connected to inactive bodies. - if (other->IsActive() == false) - { - continue; - } - - island.Add(je->joint); - je->joint->m_islandFlag = true; - - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - b2Assert(stackCount < stackSize); - stack[stackCount++] = other; - other->m_flags |= b2Body::e_islandFlag; - } - } - - b2Profile profile; - island.Solve(&profile, step, m_gravity, m_allowSleep); - m_profile.solveInit += profile.solveInit; - m_profile.solveVelocity += profile.solveVelocity; - m_profile.solvePosition += profile.solvePosition; - - // Post solve cleanup. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - // Allow static bodies to participate in other islands. - b2Body* b = island.m_bodies[i]; - if (b->GetType() == b2_staticBody) - { - b->m_flags &= ~b2Body::e_islandFlag; - } - } - } - - m_stackAllocator.Free(stack); - - { - b2Timer timer; - // Synchronize fixtures, check for out of range bodies. - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - // If a body was not in an island then it did not move. - if ((b->m_flags & b2Body::e_islandFlag) == 0) - { - continue; - } - - if (b->GetType() == b2_staticBody) - { - continue; - } - - // Update fixtures (for broad-phase). - b->SynchronizeFixtures(); - } - - // Look for new contacts. - m_contactManager.FindNewContacts(); - m_profile.broadphase = timer.GetMilliseconds(); - } -} - -// Find TOI contacts and solve them. -void b2World::SolveTOI(const b2TimeStep& step) -{ - b2Island island(2 * b2_maxTOIContacts, b2_maxTOIContacts, 0, &m_stackAllocator, m_contactManager.m_contactListener); - - if (m_stepComplete) - { - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_flags &= ~b2Body::e_islandFlag; - b->m_sweep.alpha0 = 0.0f; - } - - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Invalidate TOI - c->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - c->m_toiCount = 0; - c->m_toi = 1.0f; - } - } - - // Find TOI events and solve them. - for (;;) - { - // Find the first TOI. - b2Contact* minContact = nullptr; - float32 minAlpha = 1.0f; - - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->m_next) - { - // Is this contact disabled? - if (c->IsEnabled() == false) - { - continue; - } - - // Prevent excessive sub-stepping. - if (c->m_toiCount > b2_maxSubSteps) - { - continue; - } - - float32 alpha = 1.0f; - if (c->m_flags & b2Contact::e_toiFlag) - { - // This contact has a valid cached TOI. - alpha = c->m_toi; - } - else - { - b2Fixture* fA = c->GetFixtureA(); - b2Fixture* fB = c->GetFixtureB(); - - // Is there a sensor? - if (fA->IsSensor() || fB->IsSensor()) - { - continue; - } - - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - b2BodyType typeA = bA->m_type; - b2BodyType typeB = bB->m_type; - b2Assert(typeA == b2_dynamicBody || typeB == b2_dynamicBody); - - bool activeA = bA->IsAwake() && typeA != b2_staticBody; - bool activeB = bB->IsAwake() && typeB != b2_staticBody; - - // Is at least one body active (awake and dynamic or kinematic)? - if (activeA == false && activeB == false) - { - continue; - } - - bool collideA = bA->IsBullet() || typeA != b2_dynamicBody; - bool collideB = bB->IsBullet() || typeB != b2_dynamicBody; - - // Are these two non-bullet dynamic bodies? - if (collideA == false && collideB == false) - { - continue; - } - - // Compute the TOI for this contact. - // Put the sweeps onto the same time interval. - float32 alpha0 = bA->m_sweep.alpha0; - - if (bA->m_sweep.alpha0 < bB->m_sweep.alpha0) - { - alpha0 = bB->m_sweep.alpha0; - bA->m_sweep.Advance(alpha0); - } - else if (bB->m_sweep.alpha0 < bA->m_sweep.alpha0) - { - alpha0 = bA->m_sweep.alpha0; - bB->m_sweep.Advance(alpha0); - } - - b2Assert(alpha0 < 1.0f); - - int32 indexA = c->GetChildIndexA(); - int32 indexB = c->GetChildIndexB(); - - // Compute the time of impact in interval [0, minTOI] - b2TOIInput input; - input.proxyA.Set(fA->GetShape(), indexA); - input.proxyB.Set(fB->GetShape(), indexB); - input.sweepA = bA->m_sweep; - input.sweepB = bB->m_sweep; - input.tMax = 1.0f; - - b2TOIOutput output; - b2TimeOfImpact(&output, &input); - - // Beta is the fraction of the remaining portion of the . - float32 beta = output.t; - if (output.state == b2TOIOutput::e_touching) - { - alpha = b2Min(alpha0 + (1.0f - alpha0) * beta, 1.0f); - } - else - { - alpha = 1.0f; - } - - c->m_toi = alpha; - c->m_flags |= b2Contact::e_toiFlag; - } - - if (alpha < minAlpha) - { - // This is the minimum TOI found so far. - minContact = c; - minAlpha = alpha; - } - } - - if (minContact == nullptr || 1.0f - 10.0f * b2_epsilon < minAlpha) - { - // No more TOI events. Done! - m_stepComplete = true; - break; - } - - // Advance the bodies to the TOI. - b2Fixture* fA = minContact->GetFixtureA(); - b2Fixture* fB = minContact->GetFixtureB(); - b2Body* bA = fA->GetBody(); - b2Body* bB = fB->GetBody(); - - b2Sweep backup1 = bA->m_sweep; - b2Sweep backup2 = bB->m_sweep; - - bA->Advance(minAlpha); - bB->Advance(minAlpha); - - // The TOI contact likely has some new contact points. - minContact->Update(m_contactManager.m_contactListener); - minContact->m_flags &= ~b2Contact::e_toiFlag; - ++minContact->m_toiCount; - - // Is the contact solid? - if (minContact->IsEnabled() == false || minContact->IsTouching() == false) - { - // Restore the sweeps. - minContact->SetEnabled(false); - bA->m_sweep = backup1; - bB->m_sweep = backup2; - bA->SynchronizeTransform(); - bB->SynchronizeTransform(); - continue; - } - - bA->SetAwake(true); - bB->SetAwake(true); - - // Build the island - island.Clear(); - island.Add(bA); - island.Add(bB); - island.Add(minContact); - - bA->m_flags |= b2Body::e_islandFlag; - bB->m_flags |= b2Body::e_islandFlag; - minContact->m_flags |= b2Contact::e_islandFlag; - - // Get contacts on bodyA and bodyB. - b2Body* bodies[2] = {bA, bB}; - for (int32 i = 0; i < 2; ++i) - { - b2Body* body = bodies[i]; - if (body->m_type == b2_dynamicBody) - { - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - if (island.m_bodyCount == island.m_bodyCapacity) - { - break; - } - - if (island.m_contactCount == island.m_contactCapacity) - { - break; - } - - b2Contact* contact = ce->contact; - - // Has this contact already been added to the island? - if (contact->m_flags & b2Contact::e_islandFlag) - { - continue; - } - - // Only add static, kinematic, or bullet bodies. - b2Body* other = ce->other; - if (other->m_type == b2_dynamicBody && - body->IsBullet() == false && other->IsBullet() == false) - { - continue; - } - - // Skip sensors. - bool sensorA = contact->m_fixtureA->m_isSensor; - bool sensorB = contact->m_fixtureB->m_isSensor; - if (sensorA || sensorB) - { - continue; - } - - // Tentatively advance the body to the TOI. - b2Sweep backup = other->m_sweep; - if ((other->m_flags & b2Body::e_islandFlag) == 0) - { - other->Advance(minAlpha); - } - - // Update the contact points - contact->Update(m_contactManager.m_contactListener); - - // Was the contact disabled by the user? - if (contact->IsEnabled() == false) - { - other->m_sweep = backup; - other->SynchronizeTransform(); - continue; - } - - // Are there contact points? - if (contact->IsTouching() == false) - { - other->m_sweep = backup; - other->SynchronizeTransform(); - continue; - } - - // Add the contact to the island - contact->m_flags |= b2Contact::e_islandFlag; - island.Add(contact); - - // Has the other body already been added to the island? - if (other->m_flags & b2Body::e_islandFlag) - { - continue; - } - - // Add the other body to the island. - other->m_flags |= b2Body::e_islandFlag; - - if (other->m_type != b2_staticBody) - { - other->SetAwake(true); - } - - island.Add(other); - } - } - } - - b2TimeStep subStep; - subStep.dt = (1.0f - minAlpha) * step.dt; - subStep.inv_dt = 1.0f / subStep.dt; - subStep.dtRatio = 1.0f; - subStep.positionIterations = 20; - subStep.velocityIterations = step.velocityIterations; - subStep.warmStarting = false; - island.SolveTOI(subStep, bA->m_islandIndex, bB->m_islandIndex); - - // Reset island flags and synchronize broad-phase proxies. - for (int32 i = 0; i < island.m_bodyCount; ++i) - { - b2Body* body = island.m_bodies[i]; - body->m_flags &= ~b2Body::e_islandFlag; - - if (body->m_type != b2_dynamicBody) - { - continue; - } - - body->SynchronizeFixtures(); - - // Invalidate all contact TOIs on this displaced body. - for (b2ContactEdge* ce = body->m_contactList; ce; ce = ce->next) - { - ce->contact->m_flags &= ~(b2Contact::e_toiFlag | b2Contact::e_islandFlag); - } - } - - // Commit fixture proxy movements to the broad-phase so that new contacts are created. - // Also, some contacts can be destroyed. - m_contactManager.FindNewContacts(); - - if (m_subStepping) - { - m_stepComplete = false; - break; - } - } -} - -void b2World::Step(float32 dt, int32 velocityIterations, int32 positionIterations) -{ - b2Timer stepTimer; - - // If new fixtures were added, we need to find the new contacts. - if (m_flags & e_newFixture) - { - m_contactManager.FindNewContacts(); - m_flags &= ~e_newFixture; - } - - m_flags |= e_locked; - - b2TimeStep step; - step.dt = dt; - step.velocityIterations = velocityIterations; - step.positionIterations = positionIterations; - if (dt > 0.0f) - { - step.inv_dt = 1.0f / dt; - } - else - { - step.inv_dt = 0.0f; - } - - step.dtRatio = m_inv_dt0 * dt; - - step.warmStarting = m_warmStarting; - - // Update contacts. This is where some contacts are destroyed. - { - b2Timer timer; - m_contactManager.Collide(); - m_profile.collide = timer.GetMilliseconds(); - } - - // Integrate velocities, solve velocity constraints, and integrate positions. - if (m_stepComplete && step.dt > 0.0f) - { - b2Timer timer; - Solve(step); - m_profile.solve = timer.GetMilliseconds(); - } - - // Handle TOI events. - if (m_continuousPhysics && step.dt > 0.0f) - { - b2Timer timer; - SolveTOI(step); - m_profile.solveTOI = timer.GetMilliseconds(); - } - - if (step.dt > 0.0f) - { - m_inv_dt0 = step.inv_dt; - } - - if (m_flags & e_clearForces) - { - ClearForces(); - } - - m_flags &= ~e_locked; - - m_profile.step = stepTimer.GetMilliseconds(); -} - -void b2World::ClearForces() -{ - for (b2Body* body = m_bodyList; body; body = body->GetNext()) - { - body->m_force.SetZero(); - body->m_torque = 0.0f; - } -} - -struct b2WorldQueryWrapper -{ - bool QueryCallback(int32 proxyId) - { - b2FixtureProxy* proxy = (b2FixtureProxy*)broadPhase->GetUserData(proxyId); - return callback->ReportFixture(proxy->fixture); - } - - const b2BroadPhase* broadPhase; - b2QueryCallback* callback; -}; - -void b2World::QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const -{ - b2WorldQueryWrapper wrapper; - wrapper.broadPhase = &m_contactManager.m_broadPhase; - wrapper.callback = callback; - m_contactManager.m_broadPhase.Query(&wrapper, aabb); -} - -struct b2WorldRayCastWrapper -{ - float32 RayCastCallback(const b2RayCastInput& input, int32 proxyId) - { - void* userData = broadPhase->GetUserData(proxyId); - b2FixtureProxy* proxy = (b2FixtureProxy*)userData; - b2Fixture* fixture = proxy->fixture; - int32 index = proxy->childIndex; - b2RayCastOutput output; - bool hit = fixture->RayCast(&output, input, index); - - if (hit) - { - float32 fraction = output.fraction; - b2Vec2 point = (1.0f - fraction) * input.p1 + fraction * input.p2; - return callback->ReportFixture(fixture, point, output.normal, fraction); - } - - return input.maxFraction; - } - - const b2BroadPhase* broadPhase; - b2RayCastCallback* callback; -}; - -void b2World::RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const -{ - b2WorldRayCastWrapper wrapper; - wrapper.broadPhase = &m_contactManager.m_broadPhase; - wrapper.callback = callback; - b2RayCastInput input; - input.maxFraction = 1.0f; - input.p1 = point1; - input.p2 = point2; - m_contactManager.m_broadPhase.RayCast(&wrapper, input); -} - -void b2World::DrawShape(b2Fixture* fixture, const b2Transform& xf, const b2Color& color) -{ - switch (fixture->GetType()) - { - case b2Shape::e_circle: - { - b2CircleShape* circle = (b2CircleShape*)fixture->GetShape(); - - b2Vec2 center = b2Mul(xf, circle->m_p); - float32 radius = circle->m_radius; - b2Vec2 axis = b2Mul(xf.q, b2Vec2(1.0f, 0.0f)); - - m_debugDraw->DrawSolidCircle(center, radius, axis, color); - } - break; - - case b2Shape::e_edge: - { - b2EdgeShape* edge = (b2EdgeShape*)fixture->GetShape(); - b2Vec2 v1 = b2Mul(xf, edge->m_vertex1); - b2Vec2 v2 = b2Mul(xf, edge->m_vertex2); - m_debugDraw->DrawSegment(v1, v2, color); - } - break; - - case b2Shape::e_chain: - { - b2ChainShape* chain = (b2ChainShape*)fixture->GetShape(); - int32 count = chain->m_count; - const b2Vec2* vertices = chain->m_vertices; - - b2Color ghostColor(0.75f * color.r, 0.75f * color.g, 0.75f * color.b, color.a); - - b2Vec2 v1 = b2Mul(xf, vertices[0]); - m_debugDraw->DrawPoint(v1, 4.0f, color); - - if (chain->m_hasPrevVertex) - { - b2Vec2 vp = b2Mul(xf, chain->m_prevVertex); - m_debugDraw->DrawSegment(vp, v1, ghostColor); - m_debugDraw->DrawCircle(vp, 0.1f, ghostColor); - } - - for (int32 i = 1; i < count; ++i) - { - b2Vec2 v2 = b2Mul(xf, vertices[i]); - m_debugDraw->DrawSegment(v1, v2, color); - m_debugDraw->DrawPoint(v2, 4.0f, color); - v1 = v2; - } - - if (chain->m_hasNextVertex) - { - b2Vec2 vn = b2Mul(xf, chain->m_nextVertex); - m_debugDraw->DrawSegment(v1, vn, ghostColor); - m_debugDraw->DrawCircle(vn, 0.1f, ghostColor); - } - } - break; - - case b2Shape::e_polygon: - { - b2PolygonShape* poly = (b2PolygonShape*)fixture->GetShape(); - int32 vertexCount = poly->m_count; - b2Assert(vertexCount <= b2_maxPolygonVertices); - b2Vec2 vertices[b2_maxPolygonVertices]; - - for (int32 i = 0; i < vertexCount; ++i) - { - vertices[i] = b2Mul(xf, poly->m_vertices[i]); - } - - m_debugDraw->DrawSolidPolygon(vertices, vertexCount, color); - } - break; - - default: - break; - } -} - -void b2World::DrawJoint(b2Joint* joint) -{ - b2Body* bodyA = joint->GetBodyA(); - b2Body* bodyB = joint->GetBodyB(); - const b2Transform& xf1 = bodyA->GetTransform(); - const b2Transform& xf2 = bodyB->GetTransform(); - b2Vec2 x1 = xf1.p; - b2Vec2 x2 = xf2.p; - b2Vec2 p1 = joint->GetAnchorA(); - b2Vec2 p2 = joint->GetAnchorB(); - - b2Color color(0.5f, 0.8f, 0.8f); - - switch (joint->GetType()) - { - case e_distanceJoint: - m_debugDraw->DrawSegment(p1, p2, color); - break; - - case e_pulleyJoint: - { - b2PulleyJoint* pulley = (b2PulleyJoint*)joint; - b2Vec2 s1 = pulley->GetGroundAnchorA(); - b2Vec2 s2 = pulley->GetGroundAnchorB(); - m_debugDraw->DrawSegment(s1, p1, color); - m_debugDraw->DrawSegment(s2, p2, color); - m_debugDraw->DrawSegment(s1, s2, color); - } - break; - - case e_mouseJoint: - { - b2Color c; - c.Set(0.0f, 1.0f, 0.0f); - m_debugDraw->DrawPoint(p1, 4.0f, c); - m_debugDraw->DrawPoint(p2, 4.0f, c); - - c.Set(0.8f, 0.8f, 0.8f); - m_debugDraw->DrawSegment(p1, p2, c); - - } - break; - - default: - m_debugDraw->DrawSegment(x1, p1, color); - m_debugDraw->DrawSegment(p1, p2, color); - m_debugDraw->DrawSegment(x2, p2, color); - } -} - -void b2World::DrawDebugData() -{ - if (m_debugDraw == nullptr) - { - return; - } - - uint32 flags = m_debugDraw->GetFlags(); - - if (flags & b2Draw::e_shapeBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - const b2Transform& xf = b->GetTransform(); - for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) - { - if (b->IsActive() == false) - { - DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.3f)); - } - else if (b->GetType() == b2_staticBody) - { - DrawShape(f, xf, b2Color(0.5f, 0.9f, 0.5f)); - } - else if (b->GetType() == b2_kinematicBody) - { - DrawShape(f, xf, b2Color(0.5f, 0.5f, 0.9f)); - } - else if (b->IsAwake() == false) - { - DrawShape(f, xf, b2Color(0.6f, 0.6f, 0.6f)); - } - else - { - DrawShape(f, xf, b2Color(0.9f, 0.7f, 0.7f)); - } - } - } - } - - if (flags & b2Draw::e_jointBit) - { - for (b2Joint* j = m_jointList; j; j = j->GetNext()) - { - DrawJoint(j); - } - } - - if (flags & b2Draw::e_pairBit) - { - b2Color color(0.3f, 0.9f, 0.9f); - for (b2Contact* c = m_contactManager.m_contactList; c; c = c->GetNext()) - { - //b2Fixture* fixtureA = c->GetFixtureA(); - //b2Fixture* fixtureB = c->GetFixtureB(); - - //b2Vec2 cA = fixtureA->GetAABB().GetCenter(); - //b2Vec2 cB = fixtureB->GetAABB().GetCenter(); - - //g_debugDraw->DrawSegment(cA, cB, color); - } - } - - if (flags & b2Draw::e_aabbBit) - { - b2Color color(0.9f, 0.3f, 0.9f); - b2BroadPhase* bp = &m_contactManager.m_broadPhase; - - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - if (b->IsActive() == false) - { - continue; - } - - for (b2Fixture* f = b->GetFixtureList(); f; f = f->GetNext()) - { - for (int32 i = 0; i < f->m_proxyCount; ++i) - { - b2FixtureProxy* proxy = f->m_proxies + i; - b2AABB aabb = bp->GetFatAABB(proxy->proxyId); - b2Vec2 vs[4]; - vs[0].Set(aabb.lowerBound.x, aabb.lowerBound.y); - vs[1].Set(aabb.upperBound.x, aabb.lowerBound.y); - vs[2].Set(aabb.upperBound.x, aabb.upperBound.y); - vs[3].Set(aabb.lowerBound.x, aabb.upperBound.y); - - m_debugDraw->DrawPolygon(vs, 4, color); - } - } - } - } - - if (flags & b2Draw::e_centerOfMassBit) - { - for (b2Body* b = m_bodyList; b; b = b->GetNext()) - { - b2Transform xf = b->GetTransform(); - xf.p = b->GetWorldCenter(); - m_debugDraw->DrawTransform(xf); - } - } -} - -int32 b2World::GetProxyCount() const -{ - return m_contactManager.m_broadPhase.GetProxyCount(); -} - -int32 b2World::GetTreeHeight() const -{ - return m_contactManager.m_broadPhase.GetTreeHeight(); -} - -int32 b2World::GetTreeBalance() const -{ - return m_contactManager.m_broadPhase.GetTreeBalance(); -} - -float32 b2World::GetTreeQuality() const -{ - return m_contactManager.m_broadPhase.GetTreeQuality(); -} - -void b2World::ShiftOrigin(const b2Vec2& newOrigin) -{ - b2Assert((m_flags & e_locked) == 0); - if ((m_flags & e_locked) == e_locked) - { - return; - } - - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_xf.p -= newOrigin; - b->m_sweep.c0 -= newOrigin; - b->m_sweep.c -= newOrigin; - } - - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->ShiftOrigin(newOrigin); - } - - m_contactManager.m_broadPhase.ShiftOrigin(newOrigin); -} - -void b2World::Dump() -{ - if ((m_flags & e_locked) == e_locked) - { - return; - } - - b2Log("b2Vec2 g(%.15lef, %.15lef);\n", m_gravity.x, m_gravity.y); - b2Log("m_world->SetGravity(g);\n"); - - b2Log("b2Body** bodies = (b2Body**)b2Alloc(%d * sizeof(b2Body*));\n", m_bodyCount); - b2Log("b2Joint** joints = (b2Joint**)b2Alloc(%d * sizeof(b2Joint*));\n", m_jointCount); - int32 i = 0; - for (b2Body* b = m_bodyList; b; b = b->m_next) - { - b->m_islandIndex = i; - b->Dump(); - ++i; - } - - i = 0; - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - j->m_index = i; - ++i; - } - - // First pass on joints, skip gear joints. - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - if (j->m_type == e_gearJoint) - { - continue; - } - - b2Log("{\n"); - j->Dump(); - b2Log("}\n"); - } - - // Second pass on joints, only gear joints. - for (b2Joint* j = m_jointList; j; j = j->m_next) - { - if (j->m_type != e_gearJoint) - { - continue; - } - - b2Log("{\n"); - j->Dump(); - b2Log("}\n"); - } - - b2Log("b2Free(joints);\n"); - b2Log("b2Free(bodies);\n"); - b2Log("joints = nullptr;\n"); - b2Log("bodies = nullptr;\n"); -} diff --git a/libjin/3rdparty/Box2D/Dynamics/b2World.h b/libjin/3rdparty/Box2D/Dynamics/b2World.h deleted file mode 100644 index d5ad20c..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2World.h +++ /dev/null @@ -1,354 +0,0 @@ -/* -* Copyright (c) 2006-2011 Erin Catto http://www.box2d.org -* -* 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 B2_WORLD_H -#define B2_WORLD_H - -#include "Box2D/Common/b2Math.h" -#include "Box2D/Common/b2BlockAllocator.h" -#include "Box2D/Common/b2StackAllocator.h" -#include "Box2D/Dynamics/b2ContactManager.h" -#include "Box2D/Dynamics/b2WorldCallbacks.h" -#include "Box2D/Dynamics/b2TimeStep.h" - -struct b2AABB; -struct b2BodyDef; -struct b2Color; -struct b2JointDef; -class b2Body; -class b2Draw; -class b2Fixture; -class b2Joint; - -/// The world class manages all physics entities, dynamic simulation, -/// and asynchronous queries. The world also contains efficient memory -/// management facilities. -class b2World -{ -public: - /// Construct a world object. - /// @param gravity the world gravity vector. - b2World(const b2Vec2& gravity); - - /// Destruct the world. All physics entities are destroyed and all heap memory is released. - ~b2World(); - - /// Register a destruction listener. The listener is owned by you and must - /// remain in scope. - void SetDestructionListener(b2DestructionListener* listener); - - /// Register a contact filter to provide specific control over collision. - /// Otherwise the default filter is used (b2_defaultFilter). The listener is - /// owned by you and must remain in scope. - void SetContactFilter(b2ContactFilter* filter); - - /// Register a contact event listener. The listener is owned by you and must - /// remain in scope. - void SetContactListener(b2ContactListener* listener); - - /// Register a routine for debug drawing. The debug draw functions are called - /// inside with b2World::DrawDebugData method. The debug draw object is owned - /// by you and must remain in scope. - void SetDebugDraw(b2Draw* debugDraw); - - /// Create a rigid body given a definition. No reference to the definition - /// is retained. - /// @warning This function is locked during callbacks. - b2Body* CreateBody(const b2BodyDef* def); - - /// Destroy a rigid body given a definition. No reference to the definition - /// is retained. This function is locked during callbacks. - /// @warning This automatically deletes all associated shapes and joints. - /// @warning This function is locked during callbacks. - void DestroyBody(b2Body* body); - - /// Create a joint to constrain bodies together. No reference to the definition - /// is retained. This may cause the connected bodies to cease colliding. - /// @warning This function is locked during callbacks. - b2Joint* CreateJoint(const b2JointDef* def); - - /// Destroy a joint. This may cause the connected bodies to begin colliding. - /// @warning This function is locked during callbacks. - void DestroyJoint(b2Joint* joint); - - /// Take a time step. This performs collision detection, integration, - /// and constraint solution. - /// @param timeStep the amount of time to simulate, this should not vary. - /// @param velocityIterations for the velocity constraint solver. - /// @param positionIterations for the position constraint solver. - void Step( float32 timeStep, - int32 velocityIterations, - int32 positionIterations); - - /// Manually clear the force buffer on all bodies. By default, forces are cleared automatically - /// after each call to Step. The default behavior is modified by calling SetAutoClearForces. - /// The purpose of this function is to support sub-stepping. Sub-stepping is often used to maintain - /// a fixed sized time step under a variable frame-rate. - /// When you perform sub-stepping you will disable auto clearing of forces and instead call - /// ClearForces after all sub-steps are complete in one pass of your game loop. - /// @see SetAutoClearForces - void ClearForces(); - - /// Call this to draw shapes and other debug draw data. This is intentionally non-const. - void DrawDebugData(); - - /// Query the world for all fixtures that potentially overlap the - /// provided AABB. - /// @param callback a user implemented callback class. - /// @param aabb the query box. - void QueryAABB(b2QueryCallback* callback, const b2AABB& aabb) const; - - /// Ray-cast the world for all fixtures in the path of the ray. Your callback - /// controls whether you get the closest point, any point, or n-points. - /// The ray-cast ignores shapes that contain the starting point. - /// @param callback a user implemented callback class. - /// @param point1 the ray starting point - /// @param point2 the ray ending point - void RayCast(b2RayCastCallback* callback, const b2Vec2& point1, const b2Vec2& point2) const; - - /// Get the world body list. With the returned body, use b2Body::GetNext to get - /// the next body in the world list. A nullptr body indicates the end of the list. - /// @return the head of the world body list. - b2Body* GetBodyList(); - const b2Body* GetBodyList() const; - - /// Get the world joint list. With the returned joint, use b2Joint::GetNext to get - /// the next joint in the world list. A nullptr joint indicates the end of the list. - /// @return the head of the world joint list. - b2Joint* GetJointList(); - const b2Joint* GetJointList() const; - - /// Get the world contact list. With the returned contact, use b2Contact::GetNext to get - /// the next contact in the world list. A nullptr contact indicates the end of the list. - /// @return the head of the world contact list. - /// @warning contacts are created and destroyed in the middle of a time step. - /// Use b2ContactListener to avoid missing contacts. - b2Contact* GetContactList(); - const b2Contact* GetContactList() const; - - /// Enable/disable sleep. - void SetAllowSleeping(bool flag); - bool GetAllowSleeping() const { return m_allowSleep; } - - /// Enable/disable warm starting. For testing. - void SetWarmStarting(bool flag) { m_warmStarting = flag; } - bool GetWarmStarting() const { return m_warmStarting; } - - /// Enable/disable continuous physics. For testing. - void SetContinuousPhysics(bool flag) { m_continuousPhysics = flag; } - bool GetContinuousPhysics() const { return m_continuousPhysics; } - - /// Enable/disable single stepped continuous physics. For testing. - void SetSubStepping(bool flag) { m_subStepping = flag; } - bool GetSubStepping() const { return m_subStepping; } - - /// Get the number of broad-phase proxies. - int32 GetProxyCount() const; - - /// Get the number of bodies. - int32 GetBodyCount() const; - - /// Get the number of joints. - int32 GetJointCount() const; - - /// Get the number of contacts (each may have 0 or more contact points). - int32 GetContactCount() const; - - /// Get the height of the dynamic tree. - int32 GetTreeHeight() const; - - /// Get the balance of the dynamic tree. - int32 GetTreeBalance() const; - - /// Get the quality metric of the dynamic tree. The smaller the better. - /// The minimum is 1. - float32 GetTreeQuality() const; - - /// Change the global gravity vector. - void SetGravity(const b2Vec2& gravity); - - /// Get the global gravity vector. - b2Vec2 GetGravity() const; - - /// Is the world locked (in the middle of a time step). - bool IsLocked() const; - - /// Set flag to control automatic clearing of forces after each time step. - void SetAutoClearForces(bool flag); - - /// Get the flag that controls automatic clearing of forces after each time step. - bool GetAutoClearForces() const; - - /// Shift the world origin. Useful for large worlds. - /// The body shift formula is: position -= newOrigin - /// @param newOrigin the new origin with respect to the old origin - void ShiftOrigin(const b2Vec2& newOrigin); - - /// Get the contact manager for testing. - const b2ContactManager& GetContactManager() const; - - /// Get the current profile. - const b2Profile& GetProfile() const; - - /// Dump the world into the log file. - /// @warning this should be called outside of a time step. - void Dump(); - -private: - - // m_flags - enum - { - e_newFixture = 0x0001, - e_locked = 0x0002, - e_clearForces = 0x0004 - }; - - friend class b2Body; - friend class b2Fixture; - friend class b2ContactManager; - friend class b2Controller; - - void Solve(const b2TimeStep& step); - void SolveTOI(const b2TimeStep& step); - - void DrawJoint(b2Joint* joint); - void DrawShape(b2Fixture* shape, const b2Transform& xf, const b2Color& color); - - b2BlockAllocator m_blockAllocator; - b2StackAllocator m_stackAllocator; - - int32 m_flags; - - b2ContactManager m_contactManager; - - b2Body* m_bodyList; - b2Joint* m_jointList; - - int32 m_bodyCount; - int32 m_jointCount; - - b2Vec2 m_gravity; - bool m_allowSleep; - - b2DestructionListener* m_destructionListener; - b2Draw* m_debugDraw; - - // This is used to compute the time step ratio to - // support a variable time step. - float32 m_inv_dt0; - - // These are for debugging the solver. - bool m_warmStarting; - bool m_continuousPhysics; - bool m_subStepping; - - bool m_stepComplete; - - b2Profile m_profile; -}; - -inline b2Body* b2World::GetBodyList() -{ - return m_bodyList; -} - -inline const b2Body* b2World::GetBodyList() const -{ - return m_bodyList; -} - -inline b2Joint* b2World::GetJointList() -{ - return m_jointList; -} - -inline const b2Joint* b2World::GetJointList() const -{ - return m_jointList; -} - -inline b2Contact* b2World::GetContactList() -{ - return m_contactManager.m_contactList; -} - -inline const b2Contact* b2World::GetContactList() const -{ - return m_contactManager.m_contactList; -} - -inline int32 b2World::GetBodyCount() const -{ - return m_bodyCount; -} - -inline int32 b2World::GetJointCount() const -{ - return m_jointCount; -} - -inline int32 b2World::GetContactCount() const -{ - return m_contactManager.m_contactCount; -} - -inline void b2World::SetGravity(const b2Vec2& gravity) -{ - m_gravity = gravity; -} - -inline b2Vec2 b2World::GetGravity() const -{ - return m_gravity; -} - -inline bool b2World::IsLocked() const -{ - return (m_flags & e_locked) == e_locked; -} - -inline void b2World::SetAutoClearForces(bool flag) -{ - if (flag) - { - m_flags |= e_clearForces; - } - else - { - m_flags &= ~e_clearForces; - } -} - -/// Get the flag that controls automatic clearing of forces after each time step. -inline bool b2World::GetAutoClearForces() const -{ - return (m_flags & e_clearForces) == e_clearForces; -} - -inline const b2ContactManager& b2World::GetContactManager() const -{ - return m_contactManager; -} - -inline const b2Profile& b2World::GetProfile() const -{ - return m_profile; -} - -#endif diff --git a/libjin/3rdparty/Box2D/Dynamics/b2WorldCallbacks.cpp b/libjin/3rdparty/Box2D/Dynamics/b2WorldCallbacks.cpp deleted file mode 100644 index fe71073..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2WorldCallbacks.cpp +++ /dev/null @@ -1,36 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 "Box2D/Dynamics/b2WorldCallbacks.h" -#include "Box2D/Dynamics/b2Fixture.h" - -// Return true if contact calculations should be performed between these two shapes. -// If you implement your own collision filter you may want to build from this implementation. -bool b2ContactFilter::ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB) -{ - const b2Filter& filterA = fixtureA->GetFilterData(); - const b2Filter& filterB = fixtureB->GetFilterData(); - - if (filterA.groupIndex == filterB.groupIndex && filterA.groupIndex != 0) - { - return filterA.groupIndex > 0; - } - - bool collide = (filterA.maskBits & filterB.categoryBits) != 0 && (filterA.categoryBits & filterB.maskBits) != 0; - return collide; -} diff --git a/libjin/3rdparty/Box2D/Dynamics/b2WorldCallbacks.h b/libjin/3rdparty/Box2D/Dynamics/b2WorldCallbacks.h deleted file mode 100644 index 3d5580a..0000000 --- a/libjin/3rdparty/Box2D/Dynamics/b2WorldCallbacks.h +++ /dev/null @@ -1,155 +0,0 @@ -/* -* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org -* -* 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 B2_WORLD_CALLBACKS_H -#define B2_WORLD_CALLBACKS_H - -#include "Box2D/Common/b2Settings.h" - -struct b2Vec2; -struct b2Transform; -class b2Fixture; -class b2Body; -class b2Joint; -class b2Contact; -struct b2ContactResult; -struct b2Manifold; - -/// Joints and fixtures are destroyed when their associated -/// body is destroyed. Implement this listener so that you -/// may nullify references to these joints and shapes. -class b2DestructionListener -{ -public: - virtual ~b2DestructionListener() {} - - /// Called when any joint is about to be destroyed due - /// to the destruction of one of its attached bodies. - virtual void SayGoodbye(b2Joint* joint) = 0; - - /// Called when any fixture is about to be destroyed due - /// to the destruction of its parent body. - virtual void SayGoodbye(b2Fixture* fixture) = 0; -}; - -/// Implement this class to provide collision filtering. In other words, you can implement -/// this class if you want finer control over contact creation. -class b2ContactFilter -{ -public: - virtual ~b2ContactFilter() {} - - /// Return true if contact calculations should be performed between these two shapes. - /// @warning for performance reasons this is only called when the AABBs begin to overlap. - virtual bool ShouldCollide(b2Fixture* fixtureA, b2Fixture* fixtureB); -}; - -/// Contact impulses for reporting. Impulses are used instead of forces because -/// sub-step forces may approach infinity for rigid body collisions. These -/// match up one-to-one with the contact points in b2Manifold. -struct b2ContactImpulse -{ - float32 normalImpulses[b2_maxManifoldPoints]; - float32 tangentImpulses[b2_maxManifoldPoints]; - int32 count; -}; - -/// Implement this class to get contact information. You can use these results for -/// things like sounds and game logic. You can also get contact results by -/// traversing the contact lists after the time step. However, you might miss -/// some contacts because continuous physics leads to sub-stepping. -/// Additionally you may receive multiple callbacks for the same contact in a -/// single time step. -/// You should strive to make your callbacks efficient because there may be -/// many callbacks per time step. -/// @warning You cannot create/destroy Box2D entities inside these callbacks. -class b2ContactListener -{ -public: - virtual ~b2ContactListener() {} - - /// Called when two fixtures begin to touch. - virtual void BeginContact(b2Contact* contact) { B2_NOT_USED(contact); } - - /// Called when two fixtures cease to touch. - virtual void EndContact(b2Contact* contact) { B2_NOT_USED(contact); } - - /// This is called after a contact is updated. This allows you to inspect a - /// contact before it goes to the solver. If you are careful, you can modify the - /// contact manifold (e.g. disable contact). - /// A copy of the old manifold is provided so that you can detect changes. - /// Note: this is called only for awake bodies. - /// Note: this is called even when the number of contact points is zero. - /// Note: this is not called for sensors. - /// Note: if you set the number of contact points to zero, you will not - /// get an EndContact callback. However, you may get a BeginContact callback - /// the next step. - virtual void PreSolve(b2Contact* contact, const b2Manifold* oldManifold) - { - B2_NOT_USED(contact); - B2_NOT_USED(oldManifold); - } - - /// This lets you inspect a contact after the solver is finished. This is useful - /// for inspecting impulses. - /// Note: the contact manifold does not include time of impact impulses, which can be - /// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly - /// in a separate data structure. - /// Note: this is only called for contacts that are touching, solid, and awake. - virtual void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse) - { - B2_NOT_USED(contact); - B2_NOT_USED(impulse); - } -}; - -/// Callback class for AABB queries. -/// See b2World::Query -class b2QueryCallback -{ -public: - virtual ~b2QueryCallback() {} - - /// Called for each fixture found in the query AABB. - /// @return false to terminate the query. - virtual bool ReportFixture(b2Fixture* fixture) = 0; -}; - -/// Callback class for ray casts. -/// See b2World::RayCast -class b2RayCastCallback -{ -public: - virtual ~b2RayCastCallback() {} - - /// Called for each fixture found in the query. You control how the ray cast - /// proceeds by returning a float: - /// return -1: ignore this fixture and continue - /// return 0: terminate the ray cast - /// return fraction: clip the ray to this point - /// return 1: don't clip the ray and continue - /// @param fixture the fixture hit by the ray - /// @param point the point of initial intersection - /// @param normal the normal vector at the point of intersection - /// @return -1 to filter, 0 to terminate, fraction to clip the ray for - /// closest hit, 1 to continue - virtual float32 ReportFixture( b2Fixture* fixture, const b2Vec2& point, - const b2Vec2& normal, float32 fraction) = 0; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/Rope/b2Rope.cpp b/libjin/3rdparty/Box2D/Rope/b2Rope.cpp deleted file mode 100644 index 847b11d..0000000 --- a/libjin/3rdparty/Box2D/Rope/b2Rope.cpp +++ /dev/null @@ -1,259 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://box2d.org -* -* 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 "Box2D/Rope/b2Rope.h" -#include "Box2D/Common/b2Draw.h" - -b2Rope::b2Rope() -{ - m_count = 0; - m_ps = nullptr; - m_p0s = nullptr; - m_vs = nullptr; - m_ims = nullptr; - m_Ls = nullptr; - m_as = nullptr; - m_gravity.SetZero(); - m_k2 = 1.0f; - m_k3 = 0.1f; -} - -b2Rope::~b2Rope() -{ - b2Free(m_ps); - b2Free(m_p0s); - b2Free(m_vs); - b2Free(m_ims); - b2Free(m_Ls); - b2Free(m_as); -} - -void b2Rope::Initialize(const b2RopeDef* def) -{ - b2Assert(def->count >= 3); - m_count = def->count; - m_ps = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_p0s = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_vs = (b2Vec2*)b2Alloc(m_count * sizeof(b2Vec2)); - m_ims = (float32*)b2Alloc(m_count * sizeof(float32)); - - for (int32 i = 0; i < m_count; ++i) - { - m_ps[i] = def->vertices[i]; - m_p0s[i] = def->vertices[i]; - m_vs[i].SetZero(); - - float32 m = def->masses[i]; - if (m > 0.0f) - { - m_ims[i] = 1.0f / m; - } - else - { - m_ims[i] = 0.0f; - } - } - - int32 count2 = m_count - 1; - int32 count3 = m_count - 2; - m_Ls = (float32*)b2Alloc(count2 * sizeof(float32)); - m_as = (float32*)b2Alloc(count3 * sizeof(float32)); - - for (int32 i = 0; i < count2; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i+1]; - m_Ls[i] = b2Distance(p1, p2); - } - - for (int32 i = 0; i < count3; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 p3 = m_ps[i + 2]; - - b2Vec2 d1 = p2 - p1; - b2Vec2 d2 = p3 - p2; - - float32 a = b2Cross(d1, d2); - float32 b = b2Dot(d1, d2); - - m_as[i] = b2Atan2(a, b); - } - - m_gravity = def->gravity; - m_damping = def->damping; - m_k2 = def->k2; - m_k3 = def->k3; -} - -void b2Rope::Step(float32 h, int32 iterations) -{ - if (h == 0.0) - { - return; - } - - float32 d = expf(- h * m_damping); - - for (int32 i = 0; i < m_count; ++i) - { - m_p0s[i] = m_ps[i]; - if (m_ims[i] > 0.0f) - { - m_vs[i] += h * m_gravity; - } - m_vs[i] *= d; - m_ps[i] += h * m_vs[i]; - - } - - for (int32 i = 0; i < iterations; ++i) - { - SolveC2(); - SolveC3(); - SolveC2(); - } - - float32 inv_h = 1.0f / h; - for (int32 i = 0; i < m_count; ++i) - { - m_vs[i] = inv_h * (m_ps[i] - m_p0s[i]); - } -} - -void b2Rope::SolveC2() -{ - int32 count2 = m_count - 1; - - for (int32 i = 0; i < count2; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - - b2Vec2 d = p2 - p1; - float32 L = d.Normalize(); - - float32 im1 = m_ims[i]; - float32 im2 = m_ims[i + 1]; - - if (im1 + im2 == 0.0f) - { - continue; - } - - float32 s1 = im1 / (im1 + im2); - float32 s2 = im2 / (im1 + im2); - - p1 -= m_k2 * s1 * (m_Ls[i] - L) * d; - p2 += m_k2 * s2 * (m_Ls[i] - L) * d; - - m_ps[i] = p1; - m_ps[i + 1] = p2; - } -} - -void b2Rope::SetAngle(float32 angle) -{ - int32 count3 = m_count - 2; - for (int32 i = 0; i < count3; ++i) - { - m_as[i] = angle; - } -} - -void b2Rope::SolveC3() -{ - int32 count3 = m_count - 2; - - for (int32 i = 0; i < count3; ++i) - { - b2Vec2 p1 = m_ps[i]; - b2Vec2 p2 = m_ps[i + 1]; - b2Vec2 p3 = m_ps[i + 2]; - - float32 m1 = m_ims[i]; - float32 m2 = m_ims[i + 1]; - float32 m3 = m_ims[i + 2]; - - b2Vec2 d1 = p2 - p1; - b2Vec2 d2 = p3 - p2; - - float32 L1sqr = d1.LengthSquared(); - float32 L2sqr = d2.LengthSquared(); - - if (L1sqr * L2sqr == 0.0f) - { - continue; - } - - float32 a = b2Cross(d1, d2); - float32 b = b2Dot(d1, d2); - - float32 angle = b2Atan2(a, b); - - b2Vec2 Jd1 = (-1.0f / L1sqr) * d1.Skew(); - b2Vec2 Jd2 = (1.0f / L2sqr) * d2.Skew(); - - b2Vec2 J1 = -Jd1; - b2Vec2 J2 = Jd1 - Jd2; - b2Vec2 J3 = Jd2; - - float32 mass = m1 * b2Dot(J1, J1) + m2 * b2Dot(J2, J2) + m3 * b2Dot(J3, J3); - if (mass == 0.0f) - { - continue; - } - - mass = 1.0f / mass; - - float32 C = angle - m_as[i]; - - while (C > b2_pi) - { - angle -= 2 * b2_pi; - C = angle - m_as[i]; - } - - while (C < -b2_pi) - { - angle += 2.0f * b2_pi; - C = angle - m_as[i]; - } - - float32 impulse = - m_k3 * mass * C; - - p1 += (m1 * impulse) * J1; - p2 += (m2 * impulse) * J2; - p3 += (m3 * impulse) * J3; - - m_ps[i] = p1; - m_ps[i + 1] = p2; - m_ps[i + 2] = p3; - } -} - -void b2Rope::Draw(b2Draw* draw) const -{ - b2Color c(0.4f, 0.5f, 0.7f); - - for (int32 i = 0; i < m_count - 1; ++i) - { - draw->DrawSegment(m_ps[i], m_ps[i+1], c); - } -} diff --git a/libjin/3rdparty/Box2D/Rope/b2Rope.h b/libjin/3rdparty/Box2D/Rope/b2Rope.h deleted file mode 100644 index 40be9e7..0000000 --- a/libjin/3rdparty/Box2D/Rope/b2Rope.h +++ /dev/null @@ -1,115 +0,0 @@ -/* -* Copyright (c) 2011 Erin Catto http://www.box2d.org -* -* 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 B2_ROPE_H -#define B2_ROPE_H - -#include "Box2D/Common/b2Math.h" - -class b2Draw; - -/// -struct b2RopeDef -{ - b2RopeDef() - { - vertices = nullptr; - count = 0; - masses = nullptr; - gravity.SetZero(); - damping = 0.1f; - k2 = 0.9f; - k3 = 0.1f; - } - - /// - b2Vec2* vertices; - - /// - int32 count; - - /// - float32* masses; - - /// - b2Vec2 gravity; - - /// - float32 damping; - - /// Stretching stiffness - float32 k2; - - /// Bending stiffness. Values above 0.5 can make the simulation blow up. - float32 k3; -}; - -/// -class b2Rope -{ -public: - b2Rope(); - ~b2Rope(); - - /// - void Initialize(const b2RopeDef* def); - - /// - void Step(float32 timeStep, int32 iterations); - - /// - int32 GetVertexCount() const - { - return m_count; - } - - /// - const b2Vec2* GetVertices() const - { - return m_ps; - } - - /// - void Draw(b2Draw* draw) const; - - /// - void SetAngle(float32 angle); - -private: - - void SolveC2(); - void SolveC3(); - - int32 m_count; - b2Vec2* m_ps; - b2Vec2* m_p0s; - b2Vec2* m_vs; - - float32* m_ims; - - float32* m_Ls; - float32* m_as; - - b2Vec2 m_gravity; - float32 m_damping; - - float32 m_k2; - float32 m_k3; -}; - -#endif diff --git a/libjin/3rdparty/Box2D/manual.docx b/libjin/3rdparty/Box2D/manual.docx Binary files differdeleted file mode 100644 index 1228e2a..0000000 --- a/libjin/3rdparty/Box2D/manual.docx +++ /dev/null diff --git a/libjin/3rdparty/Box2D/manual_Chinese.docx b/libjin/3rdparty/Box2D/manual_Chinese.docx Binary files differdeleted file mode 100644 index 37592c8..0000000 --- a/libjin/3rdparty/Box2D/manual_Chinese.docx +++ /dev/null diff --git a/libjin/3rdparty/smount/smount.c b/libjin/3rdparty/smount/smount.c index 3006fa3..2b4e9b9 100644 --- a/libjin/3rdparty/smount/smount.c +++ b/libjin/3rdparty/smount/smount.c @@ -147,10 +147,18 @@ void *smtread(smtShared* S, const char *path, unsigned int *size) size = (unsigned int*)malloc(sizeof(unsigned int)); } char *r = concat(S->mount->path, "/", path, NULL); - if (!r) return NULL; + if (!r) + { + free(size); + return NULL; + } FILE *fp = fopen(r, "rb"); free(r); - if (!fp) return 0; + if (!fp) + { + free(size); + return 0; + } /* Get file size */ fseek(fp, 0, SEEK_END); *size = ftell(fp); diff --git a/libjin/3rdparty/stb/stb.h b/libjin/3rdparty/stb/stb.h deleted file mode 100644 index 971cb03..0000000 --- a/libjin/3rdparty/stb/stb.h +++ /dev/null @@ -1,14571 +0,0 @@ -/* stb.h - v2.31 - Sean's Tool Box -- public domain -- http://nothings.org/stb.h -no warranty is offered or implied; use this code at your own risk - -This is a single header file with a bunch of useful utilities -for getting stuff done in C/C++. - -Documentation: http://nothings.org/stb/stb_h.html -Unit tests: http://nothings.org/stb/stb.c - - -============================================================================ -You MUST - -#define STB_DEFINE - -in EXACTLY _one_ C or C++ file that includes this header, BEFORE the -include, like this: - -#define STB_DEFINE -#include "stb.h" - -All other files should just #include "stb.h" without the #define. -============================================================================ - - -Version History - -2.31 stb_ucharcmp -2.30 MinGW fix -2.29 attempt to fix use of swprintf() -2.28 various new functionality -2.27 test _WIN32 not WIN32 in STB_THREADS -2.26 various warning & bugfixes -2.25 various warning & bugfixes -2.24 various warning & bugfixes -2.23 fix 2.22 -2.22 64-bit fixes from '!='; fix stb_sdict_copy() to have preferred name -2.21 utf-8 decoder rejects "overlong" encodings; attempted 64-bit improvements -2.20 fix to hash "copy" function--reported by someone with handle "!=" -2.19 ??? -2.18 stb_readdir_subdirs_mask -2.17 stb_cfg_dir -2.16 fix stb_bgio_, add stb_bgio_stat(); begin a streaming wrapper -2.15 upgraded hash table template to allow: -- aggregate keys (explicit comparison func for EMPTY and DEL keys) -- "static" implementations (so they can be culled if unused) -2.14 stb_mprintf -2.13 reduce identifiable strings in STB_NO_STB_STRINGS -2.12 fix STB_ONLY -- lots of uint32s, TRUE/FALSE things had crept in -2.11 fix bug in stb_dirtree_get() which caused "c://path" sorts of stuff -2.10 STB_F(), STB_I() inline constants (also KI,KU,KF,KD) -2.09 stb_box_face_vertex_axis_side -2.08 bugfix stb_trimwhite() -2.07 colored printing in windows (why are we in 1985?) -2.06 comparison functions are now functions-that-return-functions and -accept a struct-offset as a parameter (not thread-safe) -2.05 compile and pass tests under Linux (but no threads); thread cleanup -2.04 stb_cubic_bezier_1d, smoothstep, avoid dependency on registry -2.03 ? -2.02 remove integrated documentation -2.01 integrate various fixes; stb_force_uniprocessor -2.00 revised stb_dupe to use multiple hashes -1.99 stb_charcmp -1.98 stb_arr_deleten, stb_arr_insertn -1.97 fix stb_newell_normal() -1.96 stb_hash_number() -1.95 hack stb__rec_max; clean up recursion code to use new functions -1.94 stb_dirtree; rename stb_extra to stb_ptrmap -1.93 stb_sem_new() API cleanup (no blockflag-starts blocked; use 'extra') -1.92 stb_threadqueue--multi reader/writer queue, fixed size or resizeable -1.91 stb_bgio_* for reading disk asynchronously -1.90 stb_mutex uses CRITICAL_REGION; new stb_sync primitive for thread -joining; workqueue supports stb_sync instead of stb_semaphore -1.89 support ';' in constant-string wildcards; stb_mutex wrapper (can -implement with EnterCriticalRegion eventually) -1.88 portable threading API (only for win32 so far); worker thread queue -1.87 fix wildcard handling in stb_readdir_recursive -1.86 support ';' in wildcards -1.85 make stb_regex work with non-constant strings; -beginnings of stb_introspect() -1.84 (forgot to make notes) -1.83 whoops, stb_keep_if_different wasn't deleting the temp file -1.82 bring back stb_compress from stb_file.h for cmirror -1.81 various bugfixes, STB_FASTMALLOC_INIT inits FASTMALLOC in release -1.80 stb_readdir returns utf8; write own utf8-utf16 because lib was wrong -1.79 stb_write -1.78 calloc() support for malloc wrapper, STB_FASTMALLOC -1.77 STB_FASTMALLOC -1.76 STB_STUA - Lua-like language; (stb_image, stb_csample, stb_bilinear) -1.75 alloc/free array of blocks; stb_hheap bug; a few stb_ps_ funcs; -hash*getkey, hash*copy; stb_bitset; stb_strnicmp; bugfix stb_bst -1.74 stb_replaceinplace; use stdlib C function to convert utf8 to UTF-16 -1.73 fix performance bug & leak in stb_ischar (C++ port lost a 'static') -1.72 remove stb_block, stb_block_manager, stb_decompress (to stb_file.h) -1.71 stb_trimwhite, stb_tokens_nested, etc. -1.70 back out 1.69 because it might problemize mixed builds; stb_filec() -1.69 (stb_file returns 'char *' in C++) -1.68 add a special 'tree root' data type for stb_bst; stb_arr_end -1.67 full C++ port. (stb_block_manager) -1.66 stb_newell_normal -1.65 stb_lex_item_wild -- allow wildcard items which MUST match entirely -1.64 stb_data -1.63 stb_log_name -1.62 stb_define_sort; C++ cleanup -1.61 stb_hash_fast -- Paul Hsieh's hash function (beats Bob Jenkins'?) -1.60 stb_delete_directory_recursive -1.59 stb_readdir_recursive -1.58 stb_bst variant with parent pointer for O(1) iteration, not O(log N) -1.57 replace LCG random with Mersenne Twister (found a public domain one) -1.56 stb_perfect_hash, stb_ischar, stb_regex -1.55 new stb_bst API allows multiple BSTs per node (e.g. secondary keys) -1.54 bugfix: stb_define_hash, stb_wildmatch, regexp -1.53 stb_define_hash; recoded stb_extra, stb_sdict use it -1.52 stb_rand_define, stb_bst, stb_reverse -1.51 fix 'stb_arr_setlen(NULL, 0)' -1.50 stb_wordwrap -1.49 minor improvements to enable the scripting language -1.48 better approach for stb_arr using stb_malloc; more invasive, clearer -1.47 stb_lex (lexes stb.h at 1.5ML/s on 3Ghz P4; 60/70% of optimal/flex) -1.46 stb_wrapper_*, STB_MALLOC_WRAPPER -1.45 lightly tested DFA acceleration of regexp searching -1.44 wildcard matching & searching; regexp matching & searching -1.43 stb_temp -1.42 allow stb_arr to use stb_malloc/realloc; note this is global -1.41 make it compile in C++; (disable stb_arr in C++) -1.40 stb_dupe tweak; stb_swap; stb_substr -1.39 stb_dupe; improve stb_file_max to be less stupid -1.38 stb_sha1_file: generate sha1 for file, even > 4GB -1.37 stb_file_max; partial support for utf8 filenames in Windows -1.36 remove STB__NO_PREFIX - poor interaction with IDE, not worth it -streamline stb_arr to make it separately publishable -1.35 bugfixes for stb_sdict, stb_malloc(0), stristr -1.34 (streaming interfaces for stb_compress) -1.33 stb_alloc; bug in stb_getopt; remove stb_overflow -1.32 (stb_compress returns, smaller&faster; encode window & 64-bit len) -1.31 stb_prefix_count -1.30 (STB__NO_PREFIX - remove stb_ prefixes for personal projects) -1.29 stb_fput_varlen64, etc. -1.28 stb_sha1 -1.27 ? -1.26 stb_extra -1.25 ? -1.24 stb_copyfile -1.23 stb_readdir -1.22 ? -1.21 ? -1.20 ? -1.19 ? -1.18 ? -1.17 ? -1.16 ? -1.15 stb_fixpath, stb_splitpath, stb_strchr2 -1.14 stb_arr -1.13 ?stb, stb_log, stb_fatal -1.12 ?stb_hash2 -1.11 miniML -1.10 stb_crc32, stb_adler32 -1.09 stb_sdict -1.08 stb_bitreverse, stb_ispow2, stb_big32 -stb_fopen, stb_fput_varlen, stb_fput_ranged -stb_fcmp, stb_feq -1.07 (stb_encompress) -1.06 stb_compress -1.05 stb_tokens, (stb_hheap) -1.04 stb_rand -1.03 ?(s-strings) -1.02 ?stb_filelen, stb_tokens -1.01 stb_tolower -1.00 stb_hash, stb_intcmp -stb_file, stb_stringfile, stb_fgets -stb_prefix, stb_strlower, stb_strtok -stb_image -(stb_array), (stb_arena) - -Parenthesized items have since been removed. - -LICENSE - -See end of file for license information. - -CREDITS - -Written by Sean Barrett. - -Fixes: -Philipp Wiesemann -Robert Nix -r-lyeh -blackpawn -github:Mojofreem -Ryan Whitworth -Vincent Isambart -Mike Sartain -Eugene Opalev -Tim Sjostrand -github:infatum -Dave Butler (Croepha) -*/ - -#include <stdarg.h> - -#ifndef STB__INCLUDE_STB_H -#define STB__INCLUDE_STB_H - -#define STB_VERSION 1 - -#ifdef STB_INTROSPECT -#define STB_DEFINE -#endif - -#ifdef STB_DEFINE_THREADS -#ifndef STB_DEFINE -#define STB_DEFINE -#endif -#ifndef STB_THREADS -#define STB_THREADS -#endif -#endif - -#if defined(_WIN32) && !defined(__MINGW32__) -#ifndef _CRT_SECURE_NO_WARNINGS -#define _CRT_SECURE_NO_WARNINGS -#endif -#ifndef _CRT_NONSTDC_NO_DEPRECATE -#define _CRT_NONSTDC_NO_DEPRECATE -#endif -#ifndef _CRT_NON_CONFORMING_SWPRINTFS -#define _CRT_NON_CONFORMING_SWPRINTFS -#endif -#if !defined(_MSC_VER) || _MSC_VER > 1700 -#include <intrin.h> // _BitScanReverse -#endif -#endif - -#include <stdlib.h> // stdlib could have min/max -#include <stdio.h> // need FILE -#include <string.h> // stb_define_hash needs memcpy/memset -#include <time.h> // stb_dirtree -#ifdef __MINGW32__ -#include <fcntl.h> // O_RDWR -#endif - -#ifdef STB_PERSONAL -typedef int Bool; -#define False 0 -#define True 1 -#endif - -#ifdef STB_MALLOC_WRAPPER_PAGED -#define STB_MALLOC_WRAPPER_DEBUG -#endif -#ifdef STB_MALLOC_WRAPPER_DEBUG -#define STB_MALLOC_WRAPPER -#endif -#ifdef STB_MALLOC_WRAPPER_FASTMALLOC -#define STB_FASTMALLOC -#define STB_MALLOC_WRAPPER -#endif - -#ifdef STB_FASTMALLOC -#ifndef _WIN32 -#undef STB_FASTMALLOC -#endif -#endif - -#ifdef STB_DEFINE -#include <assert.h> -#include <stdarg.h> -#include <stddef.h> -#include <ctype.h> -#include <math.h> -#ifndef _WIN32 -#include <unistd.h> -#else -#include <io.h> // _mktemp -#include <direct.h> // _rmdir -#endif -#include <sys/types.h> // stat()/_stat() -#include <sys/stat.h> // stat()/_stat() -#endif - -#define stb_min(a,b) ((a) < (b) ? (a) : (b)) -#define stb_max(a,b) ((a) > (b) ? (a) : (b)) - -#ifndef STB_ONLY -#if !defined(__cplusplus) && !defined(min) && !defined(max) -#define min(x,y) stb_min(x,y) -#define max(x,y) stb_max(x,y) -#endif - -#ifndef M_PI -#define M_PI 3.14159265358979323846f -#endif - -#ifndef TRUE -#define TRUE 1 -#define FALSE 0 -#endif - -#ifndef deg2rad -#define deg2rad(a) ((a)*(M_PI/180)) -#endif -#ifndef rad2deg -#define rad2deg(a) ((a)*(180/M_PI)) -#endif - -#ifndef swap -#ifndef __cplusplus -#define swap(TYPE,a,b) \ - do { TYPE stb__t; stb__t = (a); (a) = (b); (b) = stb__t; } while (0) -#endif -#endif - -typedef unsigned char uint8; -typedef signed char int8; -typedef unsigned short uint16; -typedef signed short int16; -#if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32) -typedef unsigned long uint32; -typedef signed long int32; -#else -typedef unsigned int uint32; -typedef signed int int32; -#endif - -typedef unsigned char uchar; -typedef unsigned short ushort; -typedef unsigned int uint; -typedef unsigned long ulong; - -// produce compile errors if the sizes aren't right -typedef char stb__testsize16[sizeof(int16) == 2]; -typedef char stb__testsize32[sizeof(int32) == 4]; -#endif - -#ifndef STB_TRUE -#define STB_TRUE 1 -#define STB_FALSE 0 -#endif - -// if we're STB_ONLY, can't rely on uint32 or even uint, so all the -// variables we'll use herein need typenames prefixed with 'stb': -typedef unsigned char stb_uchar; -typedef unsigned char stb_uint8; -typedef unsigned int stb_uint; -typedef unsigned short stb_uint16; -typedef short stb_int16; -typedef signed char stb_int8; -#if defined(STB_USE_LONG_FOR_32_BIT_INT) || defined(STB_LONG32) -typedef unsigned long stb_uint32; -typedef long stb_int32; -#else -typedef unsigned int stb_uint32; -typedef int stb_int32; -#endif -typedef char stb__testsize2_16[sizeof(stb_uint16) == 2 ? 1 : -1]; -typedef char stb__testsize2_32[sizeof(stb_uint32) == 4 ? 1 : -1]; - -#ifdef _MSC_VER -typedef unsigned __int64 stb_uint64; -typedef __int64 stb_int64; -#define STB_IMM_UINT64(literalui64) (literalui64##ui64) -#define STB_IMM_INT64(literali64) (literali64##i64) -#else -// ?? -typedef unsigned long long stb_uint64; -typedef long long stb_int64; -#define STB_IMM_UINT64(literalui64) (literalui64##ULL) -#define STB_IMM_INT64(literali64) (literali64##LL) -#endif -typedef char stb__testsize2_64[sizeof(stb_uint64) == 8 ? 1 : -1]; - -// add platform-specific ways of checking for sizeof(char*) == 8, -// and make those define STB_PTR64 -#if defined(_WIN64) || defined(__x86_64__) || defined(__ia64__) || defined(__LP64__) -#define STB_PTR64 -#endif - -#ifdef STB_PTR64 -typedef char stb__testsize2_ptr[sizeof(char *) == 8]; -typedef stb_uint64 stb_uinta; -typedef stb_int64 stb_inta; -#else -typedef char stb__testsize2_ptr[sizeof(char *) == 4]; -typedef stb_uint32 stb_uinta; -typedef stb_int32 stb_inta; -#endif -typedef char stb__testsize2_uinta[sizeof(stb_uinta) == sizeof(char*) ? 1 : -1]; - -// if so, we should define an int type that is the pointer size. until then, -// we'll have to make do with this (which is not the same at all!) - -typedef union -{ - unsigned int i; - void * p; -} stb_uintptr; - - -#ifdef __cplusplus -#define STB_EXTERN extern "C" -#else -#define STB_EXTERN extern -#endif - -// check for well-known debug defines -#if defined(DEBUG) || defined(_DEBUG) || defined(DBG) -#ifndef NDEBUG -#define STB_DEBUG -#endif -#endif - -#ifdef STB_DEBUG -#include <assert.h> -#endif - - -STB_EXTERN void stb_wrapper_malloc(void *newp, int sz, char *file, int line); -STB_EXTERN void stb_wrapper_free(void *oldp, char *file, int line); -STB_EXTERN void stb_wrapper_realloc(void *oldp, void *newp, int sz, char *file, int line); -STB_EXTERN void stb_wrapper_calloc(size_t num, size_t sz, char *file, int line); -STB_EXTERN void stb_wrapper_listall(void(*func)(void *ptr, int sz, char *file, int line)); -STB_EXTERN void stb_wrapper_dump(char *filename); -STB_EXTERN int stb_wrapper_allocsize(void *oldp); -STB_EXTERN void stb_wrapper_check(void *oldp); - -#ifdef STB_DEFINE -// this is a special function used inside malloc wrapper -// to do allocations that aren't tracked (to avoid -// reentrancy). Of course if someone _else_ wraps realloc, -// this breaks, but if they're doing that AND the malloc -// wrapper they need to explicitly check for reentrancy. -// -// only define realloc_raw() and we do realloc(NULL,sz) -// for malloc() and realloc(p,0) for free(). -static void * stb__realloc_raw(void *p, int sz) -{ - if (p == NULL) return malloc(sz); - if (sz == 0) { free(p); return NULL; } - return realloc(p, sz); -} -#endif - -#ifdef _WIN32 -STB_EXTERN void * stb_smalloc(size_t sz); -STB_EXTERN void stb_sfree(void *p); -STB_EXTERN void * stb_srealloc(void *p, size_t sz); -STB_EXTERN void * stb_scalloc(size_t n, size_t sz); -STB_EXTERN char * stb_sstrdup(char *s); -#endif - -#ifdef STB_FASTMALLOC -#define malloc stb_smalloc -#define free stb_sfree -#define realloc stb_srealloc -#define strdup stb_sstrdup -#define calloc stb_scalloc -#endif - -#ifndef STB_MALLOC_ALLCHECK -#define stb__check(p) 1 -#else -#ifndef STB_MALLOC_WRAPPER -#error STB_MALLOC_ALLCHECK requires STB_MALLOC_WRAPPER -#else -#define stb__check(p) stb_mcheck(p) -#endif -#endif - -#ifdef STB_MALLOC_WRAPPER -STB_EXTERN void * stb__malloc(int, char *, int); -STB_EXTERN void * stb__realloc(void *, int, char *, int); -STB_EXTERN void * stb__calloc(size_t n, size_t s, char *, int); -STB_EXTERN void stb__free(void *, char *file, int); -STB_EXTERN char * stb__strdup(char *s, char *file, int); -STB_EXTERN void stb_malloc_checkall(void); -STB_EXTERN void stb_malloc_check_counter(int init_delay, int rep_delay); -#ifndef STB_MALLOC_WRAPPER_DEBUG -#define stb_mcheck(p) 1 -#else -STB_EXTERN int stb_mcheck(void *); -#endif - - -#ifdef STB_DEFINE - -#ifdef STB_MALLOC_WRAPPER_DEBUG -#define STB__PAD 32 -#define STB__BIAS 16 -#define STB__SIG 0x51b01234 -#define STB__FIXSIZE(sz) (((sz+3) & ~3) + STB__PAD) -#define STB__ptr(x,y) ((char *) (x) + (y)) -#else -#define STB__ptr(x,y) (x) -#define STB__FIXSIZE(sz) (sz) -#endif - -#ifdef STB_MALLOC_WRAPPER_DEBUG -int stb_mcheck(void *p) -{ - unsigned int sz; - if (p == NULL) return 1; - p = ((char *)p) - STB__BIAS; - sz = *(unsigned int *)p; - assert(*(unsigned int *)STB__ptr(p, 4) == STB__SIG); - assert(*(unsigned int *)STB__ptr(p, 8) == STB__SIG); - assert(*(unsigned int *)STB__ptr(p, 12) == STB__SIG); - assert(*(unsigned int *)STB__ptr(p, sz - 4) == STB__SIG + 1); - assert(*(unsigned int *)STB__ptr(p, sz - 8) == STB__SIG + 1); - assert(*(unsigned int *)STB__ptr(p, sz - 12) == STB__SIG + 1); - assert(*(unsigned int *)STB__ptr(p, sz - 16) == STB__SIG + 1); - stb_wrapper_check(STB__ptr(p, STB__BIAS)); - return 1; -} - -static void stb__check2(void *p, int sz, char *file, int line) -{ - stb_mcheck(p); -} - -void stb_malloc_checkall(void) -{ - stb_wrapper_listall(stb__check2); -} -#else -void stb_malloc_checkall(void) { } -#endif - -static int stb__malloc_wait = (1 << 30), stb__malloc_next_wait = (1 << 30), stb__malloc_iter; -void stb_malloc_check_counter(int init_delay, int rep_delay) -{ - stb__malloc_wait = init_delay; - stb__malloc_next_wait = rep_delay; -} - -void stb_mcheck_all(void) -{ -#ifdef STB_MALLOC_WRAPPER_DEBUG - ++stb__malloc_iter; - if (--stb__malloc_wait <= 0) { - stb_malloc_checkall(); - stb__malloc_wait = stb__malloc_next_wait; - } -#endif -} - -#ifdef STB_MALLOC_WRAPPER_PAGED -#define STB__WINDOWS_PAGE (1 << 12) -#ifndef _WINDOWS_ -STB_EXTERN __declspec(dllimport) void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect); -STB_EXTERN __declspec(dllimport) int __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype); -#endif -#endif - -static void *stb__malloc_final(int sz) -{ -#ifdef STB_MALLOC_WRAPPER_PAGED - int aligned = (sz + STB__WINDOWS_PAGE - 1) & ~(STB__WINDOWS_PAGE - 1); - char *p = VirtualAlloc(NULL, aligned + STB__WINDOWS_PAGE, 0x2000, 0x04); // RESERVE, READWRITE - if (p == NULL) return p; - VirtualAlloc(p, aligned, 0x1000, 0x04); // COMMIT, READWRITE - return p; -#else - return malloc(sz); -#endif -} - -static void stb__free_final(void *p) -{ -#ifdef STB_MALLOC_WRAPPER_PAGED - VirtualFree(p, 0, 0x8000); // RELEASE -#else - free(p); -#endif -} - -int stb__malloc_failure; -static void *stb__realloc_final(void *p, int sz, int old_sz) -{ -#ifdef STB_MALLOC_WRAPPER_PAGED - void *q = stb__malloc_final(sz); - if (q == NULL) - return ++stb__malloc_failure, q; - // @TODO: deal with p being smaller! - memcpy(q, p, sz < old_sz ? sz : old_sz); - stb__free_final(p); - return q; -#else - return realloc(p, sz); -#endif -} - -void stb__free(void *p, char *file, int line) -{ - stb_mcheck_all(); - if (!p) return; -#ifdef STB_MALLOC_WRAPPER_DEBUG - stb_mcheck(p); -#endif - stb_wrapper_free(p, file, line); -#ifdef STB_MALLOC_WRAPPER_DEBUG - p = STB__ptr(p, -STB__BIAS); - *(unsigned int *)STB__ptr(p, 0) = 0xdeadbeef; - *(unsigned int *)STB__ptr(p, 4) = 0xdeadbeef; - *(unsigned int *)STB__ptr(p, 8) = 0xdeadbeef; - *(unsigned int *)STB__ptr(p, 12) = 0xdeadbeef; -#endif - stb__free_final(p); -} - -void * stb__malloc(int sz, char *file, int line) -{ - void *p; - stb_mcheck_all(); - if (sz == 0) return NULL; - p = stb__malloc_final(STB__FIXSIZE(sz)); - if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz)); - if (p == NULL) p = stb__malloc_final(STB__FIXSIZE(sz)); - if (p == NULL) { - ++stb__malloc_failure; -#ifdef STB_MALLOC_WRAPPER_DEBUG - stb_malloc_checkall(); -#endif - return p; - } -#ifdef STB_MALLOC_WRAPPER_DEBUG - * (int *)STB__ptr(p, 0) = STB__FIXSIZE(sz); - *(unsigned int *)STB__ptr(p, 4) = STB__SIG; - *(unsigned int *)STB__ptr(p, 8) = STB__SIG; - *(unsigned int *)STB__ptr(p, 12) = STB__SIG; - *(unsigned int *)STB__ptr(p, STB__FIXSIZE(sz) - 4) = STB__SIG + 1; - *(unsigned int *)STB__ptr(p, STB__FIXSIZE(sz) - 8) = STB__SIG + 1; - *(unsigned int *)STB__ptr(p, STB__FIXSIZE(sz) - 12) = STB__SIG + 1; - *(unsigned int *)STB__ptr(p, STB__FIXSIZE(sz) - 16) = STB__SIG + 1; - p = STB__ptr(p, STB__BIAS); -#endif - stb_wrapper_malloc(p, sz, file, line); - return p; -} - -void * stb__realloc(void *p, int sz, char *file, int line) -{ - void *q; - - stb_mcheck_all(); - if (p == NULL) return stb__malloc(sz, file, line); - if (sz == 0) { stb__free(p, file, line); return NULL; } - -#ifdef STB_MALLOC_WRAPPER_DEBUG - stb_mcheck(p); - p = STB__ptr(p, -STB__BIAS); -#endif -#ifdef STB_MALLOC_WRAPPER_PAGED - { - int n = stb_wrapper_allocsize(STB__ptr(p, STB__BIAS)); - if (!n) - stb_wrapper_check(STB__ptr(p, STB__BIAS)); - q = stb__realloc_final(p, STB__FIXSIZE(sz), STB__FIXSIZE(n)); - } -#else - q = realloc(p, STB__FIXSIZE(sz)); -#endif - if (q == NULL) - return ++stb__malloc_failure, q; -#ifdef STB_MALLOC_WRAPPER_DEBUG - * (int *)STB__ptr(q, 0) = STB__FIXSIZE(sz); - *(unsigned int *)STB__ptr(q, 4) = STB__SIG; - *(unsigned int *)STB__ptr(q, 8) = STB__SIG; - *(unsigned int *)STB__ptr(q, 12) = STB__SIG; - *(unsigned int *)STB__ptr(q, STB__FIXSIZE(sz) - 4) = STB__SIG + 1; - *(unsigned int *)STB__ptr(q, STB__FIXSIZE(sz) - 8) = STB__SIG + 1; - *(unsigned int *)STB__ptr(q, STB__FIXSIZE(sz) - 12) = STB__SIG + 1; - *(unsigned int *)STB__ptr(q, STB__FIXSIZE(sz) - 16) = STB__SIG + 1; - - q = STB__ptr(q, STB__BIAS); - p = STB__ptr(p, STB__BIAS); -#endif - stb_wrapper_realloc(p, q, sz, file, line); - return q; -} - -STB_EXTERN int stb_log2_ceil(unsigned int); -static void *stb__calloc(size_t n, size_t sz, char *file, int line) -{ - void *q; - stb_mcheck_all(); - if (n == 0 || sz == 0) return NULL; - if (stb_log2_ceil(n) + stb_log2_ceil(sz) >= 32) return NULL; - q = stb__malloc(n*sz, file, line); - if (q) memset(q, 0, n*sz); - return q; -} - -char * stb__strdup(char *s, char *file, int line) -{ - char *p; - stb_mcheck_all(); - p = stb__malloc(strlen(s) + 1, file, line); - if (!p) return p; - strcpy(p, s); - return p; -} -#endif // STB_DEFINE - -#ifdef STB_FASTMALLOC -#undef malloc -#undef realloc -#undef free -#undef strdup -#undef calloc -#endif - -// include everything that might define these, BEFORE making macros -#include <stdlib.h> -#include <string.h> -#include <malloc.h> - -#define malloc(s) stb__malloc ( s, __FILE__, __LINE__) -#define realloc(p,s) stb__realloc(p,s, __FILE__, __LINE__) -#define calloc(n,s) stb__calloc (n,s, __FILE__, __LINE__) -#define free(p) stb__free (p, __FILE__, __LINE__) -#define strdup(p) stb__strdup (p, __FILE__, __LINE__) - -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Windows pretty display -// - -STB_EXTERN void stbprint(const char *fmt, ...); -STB_EXTERN char *stb_sprintf(const char *fmt, ...); -STB_EXTERN char *stb_mprintf(const char *fmt, ...); -STB_EXTERN int stb_snprintf(char *s, size_t n, const char *fmt, ...); -STB_EXTERN int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v); - -#ifdef STB_DEFINE - -int stb_vsnprintf(char *s, size_t n, const char *fmt, va_list v) -{ - int res; -#ifdef _WIN32 - // Could use "_vsnprintf_s(s, n, _TRUNCATE, fmt, v)" ? - res = _vsnprintf(s, n, fmt, v); -#else - res = vsnprintf(s, n, fmt, v); -#endif - if (n) s[n - 1] = 0; - // Unix returns length output would require, Windows returns negative when truncated. - return (res >= (int)n || res < 0) ? -1 : res; -} - -int stb_snprintf(char *s, size_t n, const char *fmt, ...) -{ - int res; - va_list v; - va_start(v, fmt); - res = stb_vsnprintf(s, n, fmt, v); - va_end(v); - return res; -} - -char *stb_sprintf(const char *fmt, ...) -{ - static char buffer[1024]; - va_list v; - va_start(v, fmt); - stb_vsnprintf(buffer, 1024, fmt, v); - va_end(v); - return buffer; -} - -char *stb_mprintf(const char *fmt, ...) -{ - static char buffer[1024]; - va_list v; - va_start(v, fmt); - stb_vsnprintf(buffer, 1024, fmt, v); - va_end(v); - return strdup(buffer); -} - -#ifdef _WIN32 - -#ifndef _WINDOWS_ -STB_EXTERN __declspec(dllimport) int __stdcall WriteConsoleA(void *, const void *, unsigned int, unsigned int *, void *); -STB_EXTERN __declspec(dllimport) void * __stdcall GetStdHandle(unsigned int); -STB_EXTERN __declspec(dllimport) int __stdcall SetConsoleTextAttribute(void *, unsigned short); -#endif - -static void stb__print_one(void *handle, char *s, int len) -{ - if (len) - if (WriteConsoleA(handle, s, len, NULL, NULL)) - fwrite(s, 1, len, stdout); // if it fails, maybe redirected, so do normal -} - -static void stb__print(char *s) -{ - void *handle = GetStdHandle((unsigned int)-11); // STD_OUTPUT_HANDLE - int pad = 0; // number of padding characters to add - - char *t = s; - while (*s) { - int lpad; - while (*s && *s != '{') { - if (pad) { - if (*s == '\r' || *s == '\n') - pad = 0; - else if (s[0] == ' ' && s[1] == ' ') { - stb__print_one(handle, t, s - t); - t = s; - while (pad) { - stb__print_one(handle, t, 1); - --pad; - } - } - } - ++s; - } - if (!*s) break; - stb__print_one(handle, t, s - t); - if (s[1] == '{') { - ++s; - continue; - } - - if (s[1] == '#') { - t = s + 3; - if (isxdigit(s[2])) - if (isdigit(s[2])) - SetConsoleTextAttribute(handle, s[2] - '0'); - else - SetConsoleTextAttribute(handle, tolower(s[2]) - 'a' + 10); - else { - SetConsoleTextAttribute(handle, 0x0f); - t = s + 2; - } - } - else if (s[1] == '!') { - SetConsoleTextAttribute(handle, 0x0c); - t = s + 2; - } - else if (s[1] == '@') { - SetConsoleTextAttribute(handle, 0x09); - t = s + 2; - } - else if (s[1] == '$') { - SetConsoleTextAttribute(handle, 0x0a); - t = s + 2; - } - else { - SetConsoleTextAttribute(handle, 0x08); // 0,7,8,15 => shades of grey - t = s + 1; - } - - lpad = (t - s); - s = t; - while (*s && *s != '}') ++s; - if (!*s) break; - stb__print_one(handle, t, s - t); - if (s[1] == '}') { - t = s + 2; - } - else { - pad += 1 + lpad; - t = s + 1; - } - s = t; - SetConsoleTextAttribute(handle, 0x07); - } - stb__print_one(handle, t, s - t); - SetConsoleTextAttribute(handle, 0x07); -} - -void stbprint(const char *fmt, ...) -{ - int res; - char buffer[1024]; - char *tbuf = buffer; - va_list v; - - va_start(v, fmt); - res = stb_vsnprintf(buffer, sizeof(buffer), fmt, v); - va_end(v); - - if (res < 0) { - tbuf = (char *)malloc(16384); - va_start(v, fmt); - res = _vsnprintf(tbuf, 16384, fmt, v); - va_end(v); - tbuf[16383] = 0; - } - - stb__print(tbuf); - - if (tbuf != buffer) - free(tbuf); -} - -#else // _WIN32 -void stbprint(const char *fmt, ...) -{ - va_list v; - va_start(v, fmt); - vprintf(fmt, v); - va_end(v); -} -#endif // _WIN32 -#endif // STB_DEFINE - - - -////////////////////////////////////////////////////////////////////////////// -// -// Windows UTF8 filename handling -// -// Windows stupidly treats 8-bit filenames as some dopey code page, -// rather than utf-8. If we want to use utf8 filenames, we have to -// convert them to WCHAR explicitly and call WCHAR versions of the -// file functions. So, ok, we do. - - -#ifdef _WIN32 -#define stb__fopen(x,y) _wfopen((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y)) -#define stb__windows(x,y) x -#else -#define stb__fopen(x,y) fopen(x,y) -#define stb__windows(x,y) y -#endif - - -typedef unsigned short stb__wchar; - -STB_EXTERN stb__wchar * stb_from_utf8(stb__wchar *buffer, char *str, int n); -STB_EXTERN char * stb_to_utf8(char *buffer, stb__wchar *str, int n); - -STB_EXTERN stb__wchar *stb__from_utf8(char *str); -STB_EXTERN stb__wchar *stb__from_utf8_alt(char *str); -STB_EXTERN char *stb__to_utf8(stb__wchar *str); - - -#ifdef STB_DEFINE -stb__wchar * stb_from_utf8(stb__wchar *buffer, char *ostr, int n) -{ - unsigned char *str = (unsigned char *)ostr; - stb_uint32 c; - int i = 0; - --n; - while (*str) { - if (i >= n) - return NULL; - if (!(*str & 0x80)) - buffer[i++] = *str++; - else if ((*str & 0xe0) == 0xc0) { - if (*str < 0xc2) return NULL; - c = (*str++ & 0x1f) << 6; - if ((*str & 0xc0) != 0x80) return NULL; - buffer[i++] = c + (*str++ & 0x3f); - } - else if ((*str & 0xf0) == 0xe0) { - if (*str == 0xe0 && (str[1] < 0xa0 || str[1] > 0xbf)) return NULL; - if (*str == 0xed && str[1] > 0x9f) return NULL; // str[1] < 0x80 is checked below - c = (*str++ & 0x0f) << 12; - if ((*str & 0xc0) != 0x80) return NULL; - c += (*str++ & 0x3f) << 6; - if ((*str & 0xc0) != 0x80) return NULL; - buffer[i++] = c + (*str++ & 0x3f); - } - else if ((*str & 0xf8) == 0xf0) { - if (*str > 0xf4) return NULL; - if (*str == 0xf0 && (str[1] < 0x90 || str[1] > 0xbf)) return NULL; - if (*str == 0xf4 && str[1] > 0x8f) return NULL; // str[1] < 0x80 is checked below - c = (*str++ & 0x07) << 18; - if ((*str & 0xc0) != 0x80) return NULL; - c += (*str++ & 0x3f) << 12; - if ((*str & 0xc0) != 0x80) return NULL; - c += (*str++ & 0x3f) << 6; - if ((*str & 0xc0) != 0x80) return NULL; - c += (*str++ & 0x3f); - // utf-8 encodings of values used in surrogate pairs are invalid - if ((c & 0xFFFFF800) == 0xD800) return NULL; - if (c >= 0x10000) { - c -= 0x10000; - if (i + 2 > n) return NULL; - buffer[i++] = 0xD800 | (0x3ff & (c >> 10)); - buffer[i++] = 0xDC00 | (0x3ff & (c)); - } - } - else - return NULL; - } - buffer[i] = 0; - return buffer; -} - -char * stb_to_utf8(char *buffer, stb__wchar *str, int n) -{ - int i = 0; - --n; - while (*str) { - if (*str < 0x80) { - if (i + 1 > n) return NULL; - buffer[i++] = (char)*str++; - } - else if (*str < 0x800) { - if (i + 2 > n) return NULL; - buffer[i++] = 0xc0 + (*str >> 6); - buffer[i++] = 0x80 + (*str & 0x3f); - str += 1; - } - else if (*str >= 0xd800 && *str < 0xdc00) { - stb_uint32 c; - if (i + 4 > n) return NULL; - c = ((str[0] - 0xd800) << 10) + ((str[1]) - 0xdc00) + 0x10000; - buffer[i++] = 0xf0 + (c >> 18); - buffer[i++] = 0x80 + ((c >> 12) & 0x3f); - buffer[i++] = 0x80 + ((c >> 6) & 0x3f); - buffer[i++] = 0x80 + ((c) & 0x3f); - str += 2; - } - else if (*str >= 0xdc00 && *str < 0xe000) { - return NULL; - } - else { - if (i + 3 > n) return NULL; - buffer[i++] = 0xe0 + (*str >> 12); - buffer[i++] = 0x80 + ((*str >> 6) & 0x3f); - buffer[i++] = 0x80 + ((*str) & 0x3f); - str += 1; - } - } - buffer[i] = 0; - return buffer; -} - -stb__wchar *stb__from_utf8(char *str) -{ - static stb__wchar buffer[4096]; - return stb_from_utf8(buffer, str, 4096); -} - -stb__wchar *stb__from_utf8_alt(char *str) -{ - static stb__wchar buffer[4096]; - return stb_from_utf8(buffer, str, 4096); -} - -char *stb__to_utf8(stb__wchar *str) -{ - static char buffer[4096]; - return stb_to_utf8(buffer, str, 4096); -} - -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Miscellany -// - -STB_EXTERN void stb_fatal(char *fmt, ...); -STB_EXTERN void stb_(char *fmt, ...); -STB_EXTERN void stb_append_to_file(char *file, char *fmt, ...); -STB_EXTERN void stb_log(int active); -STB_EXTERN void stb_log_fileline(int active); -STB_EXTERN void stb_log_name(char *filename); - -STB_EXTERN void stb_swap(void *p, void *q, size_t sz); -STB_EXTERN void *stb_copy(void *p, size_t sz); -STB_EXTERN void stb_pointer_array_free(void *p, int len); -STB_EXTERN void **stb_array_block_alloc(int count, int blocksize); - -#define stb_arrcount(x) (sizeof(x)/sizeof((x)[0])) - - -STB_EXTERN int stb__record_fileline(char *f, int n); - -#ifdef STB_DEFINE - -static char *stb__file; -static int stb__line; - -int stb__record_fileline(char *f, int n) -{ - stb__file = f; - stb__line = n; - return 0; -} - -void stb_fatal(char *s, ...) -{ - va_list a; - if (stb__file) - fprintf(stderr, "[%s:%d] ", stb__file, stb__line); - va_start(a, s); - fputs("Fatal error: ", stderr); - vfprintf(stderr, s, a); - va_end(a); - fputs("\n", stderr); -#ifdef STB_DEBUG -#ifdef _MSC_VER -#ifndef STB_PTR64 - __asm int 3; // trap to debugger! -#else - __debugbreak(); -#endif -#else - __builtin_trap(); -#endif -#endif - exit(1); -} - -static int stb__log_active = 1, stb__log_fileline = 1; - -void stb_log(int active) -{ - stb__log_active = active; -} - -void stb_log_fileline(int active) -{ - stb__log_fileline = active; -} - -#ifdef STB_NO_STB_STRINGS -char *stb__log_filename = "temp.log"; -#else -char *stb__log_filename = "stb.log"; -#endif - -void stb_log_name(char *s) -{ - stb__log_filename = s; -} - -void stb_(char *s, ...) -{ - if (stb__log_active) { - FILE *f = fopen(stb__log_filename, "a"); - if (f) { - va_list a; - if (stb__log_fileline && stb__file) - fprintf(f, "[%s:%4d] ", stb__file, stb__line); - va_start(a, s); - vfprintf(f, s, a); - va_end(a); - fputs("\n", f); - fclose(f); - } - } -} - -void stb_append_to_file(char *filename, char *s, ...) -{ - FILE *f = fopen(filename, "a"); - if (f) { - va_list a; - va_start(a, s); - vfprintf(f, s, a); - va_end(a); - fputs("\n", f); - fclose(f); - } -} - - -typedef struct { char d[4]; } stb__4; -typedef struct { char d[8]; } stb__8; - -// optimize the small cases, though you shouldn't be calling this for those! -void stb_swap(void *p, void *q, size_t sz) -{ - char buffer[256]; - if (p == q) return; - if (sz == 4) { - stb__4 temp = *(stb__4 *)p; - *(stb__4 *)p = *(stb__4 *)q; - *(stb__4 *)q = temp; - return; - } - else if (sz == 8) { - stb__8 temp = *(stb__8 *)p; - *(stb__8 *)p = *(stb__8 *)q; - *(stb__8 *)q = temp; - return; - } - - while (sz > sizeof(buffer)) { - stb_swap(p, q, sizeof(buffer)); - p = (char *)p + sizeof(buffer); - q = (char *)q + sizeof(buffer); - sz -= sizeof(buffer); - } - - memcpy(buffer, p, sz); - memcpy(p, q, sz); - memcpy(q, buffer, sz); -} - -void *stb_copy(void *p, size_t sz) -{ - void *q = malloc(sz); - memcpy(q, p, sz); - return q; -} - -void stb_pointer_array_free(void *q, int len) -{ - void **p = (void **)q; - int i; - for (i = 0; i < len; ++i) - free(p[i]); -} - -void **stb_array_block_alloc(int count, int blocksize) -{ - int i; - char *p = (char *)malloc(sizeof(void *) * count + count * blocksize); - void **q; - if (p == NULL) return NULL; - q = (void **)p; - p += sizeof(void *) * count; - for (i = 0; i < count; ++i) - q[i] = p + i * blocksize; - return q; -} -#endif - -#ifdef STB_DEBUG -// tricky hack to allow recording FILE,LINE even in varargs functions -#define STB__RECORD_FILE(x) (stb__record_fileline(__FILE__, __LINE__),(x)) -#define stb_log STB__RECORD_FILE(stb_log) -#define stb_ STB__RECORD_FILE(stb_) -#ifndef STB_FATAL_CLEAN -#define stb_fatal STB__RECORD_FILE(stb_fatal) -#endif -#define STB__DEBUG(x) x -#else -#define STB__DEBUG(x) -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// stb_temp -// - -#define stb_temp(block, sz) stb__temp(block, sizeof(block), (sz)) - -STB_EXTERN void * stb__temp(void *b, int b_sz, int want_sz); -STB_EXTERN void stb_tempfree(void *block, void *ptr); - -#ifdef STB_DEFINE - -void * stb__temp(void *b, int b_sz, int want_sz) -{ - if (b_sz >= want_sz) - return b; - else - return malloc(want_sz); -} - -void stb_tempfree(void *b, void *p) -{ - if (p != b) - free(p); -} -#endif - - -////////////////////////////////////////////////////////////////////////////// -// -// math/sampling operations -// - - -#define stb_lerp(t,a,b) ( (a) + (t) * (float) ((b)-(a)) ) -#define stb_unlerp(t,a,b) ( ((t) - (a)) / (float) ((b) - (a)) ) - -#define stb_clamp(x,xmin,xmax) ((x) < (xmin) ? (xmin) : (x) > (xmax) ? (xmax) : (x)) - -STB_EXTERN void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize); -STB_EXTERN int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis); -STB_EXTERN void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt); - -STB_EXTERN int stb_float_eq(float x, float y, float delta, int max_ulps); -STB_EXTERN int stb_is_prime(unsigned int m); -STB_EXTERN unsigned int stb_power_of_two_nearest_prime(int n); - -STB_EXTERN float stb_smoothstep(float t); -STB_EXTERN float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3); - -STB_EXTERN double stb_linear_remap(double x, double a, double b, - double c, double d); - -#ifdef STB_DEFINE -float stb_smoothstep(float t) -{ - return (3 - 2 * t)*(t*t); -} - -float stb_cubic_bezier_1d(float t, float p0, float p1, float p2, float p3) -{ - float it = 1 - t; - return it*it*it*p0 + 3 * it*it*t*p1 + 3 * it*t*t*p2 + t*t*t*p3; -} - -void stb_newell_normal(float *normal, int num_vert, float **vert, int normalize) -{ - int i, j; - float p; - normal[0] = normal[1] = normal[2] = 0; - for (i = num_vert - 1, j = 0; j < num_vert; i = j++) { - float *u = vert[i]; - float *v = vert[j]; - normal[0] += (u[1] - v[1]) * (u[2] + v[2]); - normal[1] += (u[2] - v[2]) * (u[0] + v[0]); - normal[2] += (u[0] - v[0]) * (u[1] + v[1]); - } - if (normalize) { - p = normal[0] * normal[0] + normal[1] * normal[1] + normal[2] * normal[2]; - p = (float)(1.0 / sqrt(p)); - normal[0] *= p; - normal[1] *= p; - normal[2] *= p; - } -} - -int stb_box_face_vertex_axis_side(int face_number, int vertex_number, int axis) -{ - static int box_vertices[6][4][3] = - { - { { 1,1,1 },{ 1,0,1 },{ 1,0,0 },{ 1,1,0 } }, - { { 0,0,0 },{ 0,0,1 },{ 0,1,1 },{ 0,1,0 } }, - { { 0,0,0 },{ 0,1,0 },{ 1,1,0 },{ 1,0,0 } }, - { { 0,0,0 },{ 1,0,0 },{ 1,0,1 },{ 0,0,1 } }, - { { 1,1,1 },{ 0,1,1 },{ 0,0,1 },{ 1,0,1 } }, - { { 1,1,1 },{ 1,1,0 },{ 0,1,0 },{ 0,1,1 } }, - }; - assert(face_number >= 0 && face_number < 6); - assert(vertex_number >= 0 && vertex_number < 4); - assert(axis >= 0 && axis < 3); - return box_vertices[face_number][vertex_number][axis]; -} - -void stb_linear_controller(float *curpos, float target_pos, float acc, float deacc, float dt) -{ - float sign = 1, p, cp = *curpos; - if (cp == target_pos) return; - if (target_pos < cp) { - target_pos = -target_pos; - cp = -cp; - sign = -1; - } - // first decelerate - if (cp < 0) { - p = cp + deacc * dt; - if (p > 0) { - p = 0; - dt = dt - cp / deacc; - if (dt < 0) dt = 0; - } - else { - dt = 0; - } - cp = p; - } - // now accelerate - p = cp + acc*dt; - if (p > target_pos) p = target_pos; - *curpos = p * sign; - // @TODO: testing -} - -float stb_quadratic_controller(float target_pos, float curpos, float maxvel, float maxacc, float dt, float *curvel) -{ - return 0; // @TODO -} - -int stb_float_eq(float x, float y, float delta, int max_ulps) -{ - if (fabs(x - y) <= delta) return 1; - if (abs(*(int *)&x - *(int *)&y) <= max_ulps) return 1; - return 0; -} - -int stb_is_prime(unsigned int m) -{ - unsigned int i, j; - if (m < 2) return 0; - if (m == 2) return 1; - if (!(m & 1)) return 0; - if (m % 3 == 0) return (m == 3); - for (i = 5; (j = i*i), j <= m && j > i; i += 6) { - if (m % i == 0) return 0; - if (m % (i + 2) == 0) return 0; - } - return 1; -} - -unsigned int stb_power_of_two_nearest_prime(int n) -{ - static signed char tab[32] = { 0,0,0,0,1,0,-1,0,1,-1,-1,3,-1,0,-1,2,1, - 0,2,0,-1,-4,-1,5,-1,18,-2,15,2,-1,2,0 }; - if (!tab[0]) { - int i; - for (i = 0; i < 32; ++i) - tab[i] = (1 << i) + 2 * tab[i] - 1; - tab[1] = 2; - tab[0] = 1; - } - if (n >= 32) return 0xfffffffb; - return tab[n]; -} - -double stb_linear_remap(double x, double x_min, double x_max, - double out_min, double out_max) -{ - return stb_lerp(stb_unlerp(x, x_min, x_max), out_min, out_max); -} -#endif - -// create a macro so it's faster, but you can get at the function pointer -#define stb_linear_remap(t,a,b,c,d) stb_lerp(stb_unlerp(t,a,b),c,d) - - -////////////////////////////////////////////////////////////////////////////// -// -// bit operations -// - -#define stb_big32(c) (((c)[0]<<24) + (c)[1]*65536 + (c)[2]*256 + (c)[3]) -#define stb_little32(c) (((c)[3]<<24) + (c)[2]*65536 + (c)[1]*256 + (c)[0]) -#define stb_big16(c) ((c)[0]*256 + (c)[1]) -#define stb_little16(c) ((c)[1]*256 + (c)[0]) - -STB_EXTERN int stb_bitcount(unsigned int a); -STB_EXTERN unsigned int stb_bitreverse8(unsigned char n); -STB_EXTERN unsigned int stb_bitreverse(unsigned int n); - -STB_EXTERN int stb_is_pow2(unsigned int n); -STB_EXTERN int stb_log2_ceil(unsigned int n); -STB_EXTERN int stb_log2_floor(unsigned int n); - -STB_EXTERN int stb_lowbit8(unsigned int n); -STB_EXTERN int stb_highbit8(unsigned int n); - -#ifdef STB_DEFINE -int stb_bitcount(unsigned int a) -{ - a = (a & 0x55555555) + ((a >> 1) & 0x55555555); // max 2 - a = (a & 0x33333333) + ((a >> 2) & 0x33333333); // max 4 - a = (a + (a >> 4)) & 0x0f0f0f0f; // max 8 per 4, now 8 bits - a = (a + (a >> 8)); // max 16 per 8 bits - a = (a + (a >> 16)); // max 32 per 8 bits - return a & 0xff; -} - -unsigned int stb_bitreverse8(unsigned char n) -{ - n = ((n & 0xAA) >> 1) + ((n & 0x55) << 1); - n = ((n & 0xCC) >> 2) + ((n & 0x33) << 2); - return (unsigned char)((n >> 4) + (n << 4)); -} - -unsigned int stb_bitreverse(unsigned int n) -{ - n = ((n & 0xAAAAAAAA) >> 1) | ((n & 0x55555555) << 1); - n = ((n & 0xCCCCCCCC) >> 2) | ((n & 0x33333333) << 2); - n = ((n & 0xF0F0F0F0) >> 4) | ((n & 0x0F0F0F0F) << 4); - n = ((n & 0xFF00FF00) >> 8) | ((n & 0x00FF00FF) << 8); - return (n >> 16) | (n << 16); -} - -int stb_is_pow2(unsigned int n) -{ - return (n & (n - 1)) == 0; -} - -// tricky use of 4-bit table to identify 5 bit positions (note the '-1') -// 3-bit table would require another tree level; 5-bit table wouldn't save one -#if defined(_WIN32) && !defined(__MINGW32__) -#pragma warning(push) -#pragma warning(disable: 4035) // disable warning about no return value -int stb_log2_floor(unsigned int n) -{ -#if _MSC_VER > 1700 - unsigned long i; - _BitScanReverse(&i, n); - return i != 0 ? i : -1; -#else - __asm { - bsr eax, n - jnz done - mov eax, -1 - } -done:; -#endif -} -#pragma warning(pop) -#else -int stb_log2_floor(unsigned int n) -{ - static signed char log2_4[16] = { -1,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3 }; - - // 2 compares if n < 16, 3 compares otherwise - if (n < (1U << 14)) - if (n < (1U << 4)) return 0 + log2_4[n]; - else if (n < (1U << 9)) return 5 + log2_4[n >> 5]; - else return 10 + log2_4[n >> 10]; - else if (n < (1U << 24)) - if (n < (1U << 19)) return 15 + log2_4[n >> 15]; - else return 20 + log2_4[n >> 20]; - else if (n < (1U << 29)) return 25 + log2_4[n >> 25]; - else return 30 + log2_4[n >> 30]; -} -#endif - -// define ceil from floor -int stb_log2_ceil(unsigned int n) -{ - if (stb_is_pow2(n)) return stb_log2_floor(n); - else return 1 + stb_log2_floor(n); -} - -int stb_highbit8(unsigned int n) -{ - return stb_log2_ceil(n & 255); -} - -int stb_lowbit8(unsigned int n) -{ - static signed char lowbit4[16] = { -1,0,1,0, 2,0,1,0, 3,0,1,0, 2,0,1,0 }; - int k = lowbit4[n & 15]; - if (k >= 0) return k; - k = lowbit4[(n >> 4) & 15]; - if (k >= 0) return k + 4; - return k; -} -#endif - - - -////////////////////////////////////////////////////////////////////////////// -// -// qsort Compare Routines -// - -#ifdef _WIN32 -#define stb_stricmp(a,b) stricmp(a,b) -#define stb_strnicmp(a,b,n) strnicmp(a,b,n) -#else -#define stb_stricmp(a,b) strcasecmp(a,b) -#define stb_strnicmp(a,b,n) strncasecmp(a,b,n) -#endif - - -STB_EXTERN int(*stb_intcmp(int offset))(const void *a, const void *b); -STB_EXTERN int(*stb_qsort_strcmp(int offset))(const void *a, const void *b); -STB_EXTERN int(*stb_qsort_stricmp(int offset))(const void *a, const void *b); -STB_EXTERN int(*stb_floatcmp(int offset))(const void *a, const void *b); -STB_EXTERN int(*stb_doublecmp(int offset))(const void *a, const void *b); -STB_EXTERN int(*stb_charcmp(int offset))(const void *a, const void *b); - -#ifdef STB_DEFINE -static int stb__intcmpoffset, stb__ucharcmpoffset, stb__strcmpoffset; -static int stb__floatcmpoffset, stb__doublecmpoffset; - -int stb__intcmp(const void *a, const void *b) -{ - const int p = *(const int *)((const char *)a + stb__intcmpoffset); - const int q = *(const int *)((const char *)b + stb__intcmpoffset); - return p < q ? -1 : p > q; -} - -int stb__ucharcmp(const void *a, const void *b) -{ - const int p = *(const unsigned char *)((const char *)a + stb__ucharcmpoffset); - const int q = *(const unsigned char *)((const char *)b + stb__ucharcmpoffset); - return p < q ? -1 : p > q; -} - -int stb__floatcmp(const void *a, const void *b) -{ - const float p = *(const float *)((const char *)a + stb__floatcmpoffset); - const float q = *(const float *)((const char *)b + stb__floatcmpoffset); - return p < q ? -1 : p > q; -} - -int stb__doublecmp(const void *a, const void *b) -{ - const double p = *(const double *)((const char *)a + stb__doublecmpoffset); - const double q = *(const double *)((const char *)b + stb__doublecmpoffset); - return p < q ? -1 : p > q; -} - -int stb__qsort_strcmp(const void *a, const void *b) -{ - const char *p = *(const char **)((const char *)a + stb__strcmpoffset); - const char *q = *(const char **)((const char *)b + stb__strcmpoffset); - return strcmp(p, q); -} - -int stb__qsort_stricmp(const void *a, const void *b) -{ - const char *p = *(const char **)((const char *)a + stb__strcmpoffset); - const char *q = *(const char **)((const char *)b + stb__strcmpoffset); - return stb_stricmp(p, q); -} - -int(*stb_intcmp(int offset))(const void *, const void *) -{ - stb__intcmpoffset = offset; - return &stb__intcmp; -} - -int(*stb_ucharcmp(int offset))(const void *, const void *) -{ - stb__ucharcmpoffset = offset; - return &stb__ucharcmp; -} - -int(*stb_qsort_strcmp(int offset))(const void *, const void *) -{ - stb__strcmpoffset = offset; - return &stb__qsort_strcmp; -} - -int(*stb_qsort_stricmp(int offset))(const void *, const void *) -{ - stb__strcmpoffset = offset; - return &stb__qsort_stricmp; -} - -int(*stb_floatcmp(int offset))(const void *, const void *) -{ - stb__floatcmpoffset = offset; - return &stb__floatcmp; -} - -int(*stb_doublecmp(int offset))(const void *, const void *) -{ - stb__doublecmpoffset = offset; - return &stb__doublecmp; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Binary Search Toolkit -// - -typedef struct -{ - int minval, maxval, guess; - int mode, step; -} stb_search; - -STB_EXTERN int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest); -STB_EXTERN int stb_search_open(stb_search *s, int minv, int find_smallest); -STB_EXTERN int stb_probe(stb_search *s, int compare, int *result); // return 0 when done - -#ifdef STB_DEFINE -enum -{ - STB_probe_binary_smallest, - STB_probe_binary_largest, - STB_probe_open_smallest, - STB_probe_open_largest, -}; - -static int stb_probe_guess(stb_search *s, int *result) -{ - switch (s->mode) { - case STB_probe_binary_largest: - if (s->minval == s->maxval) { - *result = s->minval; - return 0; - } - assert(s->minval < s->maxval); - // if a < b, then a < p <= b - s->guess = s->minval + (((unsigned)s->maxval - s->minval + 1) >> 1); - break; - - case STB_probe_binary_smallest: - if (s->minval == s->maxval) { - *result = s->minval; - return 0; - } - assert(s->minval < s->maxval); - // if a < b, then a <= p < b - s->guess = s->minval + (((unsigned)s->maxval - s->minval) >> 1); - break; - case STB_probe_open_smallest: - case STB_probe_open_largest: - s->guess = s->maxval; // guess the current maxval - break; - } - *result = s->guess; - return 1; -} - -int stb_probe(stb_search *s, int compare, int *result) -{ - switch (s->mode) { - case STB_probe_open_smallest: - case STB_probe_open_largest: { - if (compare <= 0) { - // then it lies within minval & maxval - if (s->mode == STB_probe_open_smallest) - s->mode = STB_probe_binary_smallest; - else - s->mode = STB_probe_binary_largest; - } - else { - // otherwise, we need to probe larger - s->minval = s->maxval + 1; - s->maxval = s->minval + s->step; - s->step += s->step; - } - break; - } - case STB_probe_binary_smallest: { - // if compare < 0, then s->minval <= a < p - // if compare = 0, then s->minval <= a <= p - // if compare > 0, then p < a <= s->maxval - if (compare <= 0) - s->maxval = s->guess; - else - s->minval = s->guess + 1; - break; - } - case STB_probe_binary_largest: { - // if compare < 0, then s->minval <= a < p - // if compare = 0, then p <= a <= s->maxval - // if compare > 0, then p < a <= s->maxval - if (compare < 0) - s->maxval = s->guess - 1; - else - s->minval = s->guess; - break; - } - } - return stb_probe_guess(s, result); -} - -int stb_search_binary(stb_search *s, int minv, int maxv, int find_smallest) -{ - int r; - if (maxv < minv) return minv - 1; - s->minval = minv; - s->maxval = maxv; - s->mode = find_smallest ? STB_probe_binary_smallest : STB_probe_binary_largest; - stb_probe_guess(s, &r); - return r; -} - -int stb_search_open(stb_search *s, int minv, int find_smallest) -{ - int r; - s->step = 4; - s->minval = minv; - s->maxval = minv + s->step; - s->mode = find_smallest ? STB_probe_open_smallest : STB_probe_open_largest; - stb_probe_guess(s, &r); - return r; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// String Processing -// - -#define stb_prefixi(s,t) (0==stb_strnicmp((s),(t),strlen(t))) - -enum stb_splitpath_flag -{ - STB_PATH = 1, - STB_FILE = 2, - STB_EXT = 4, - STB_PATH_FILE = STB_PATH + STB_FILE, - STB_FILE_EXT = STB_FILE + STB_EXT, - STB_EXT_NO_PERIOD = 8, -}; - -STB_EXTERN char * stb_skipwhite(char *s); -STB_EXTERN char * stb_trimwhite(char *s); -STB_EXTERN char * stb_skipnewline(char *s); -STB_EXTERN char * stb_strncpy(char *s, char *t, int n); -STB_EXTERN char * stb_substr(char *t, int n); -STB_EXTERN char * stb_duplower(char *s); -STB_EXTERN void stb_tolower(char *s); -STB_EXTERN char * stb_strchr2(char *s, char p1, char p2); -STB_EXTERN char * stb_strrchr2(char *s, char p1, char p2); -STB_EXTERN char * stb_strtok(char *output, char *src, char *delimit); -STB_EXTERN char * stb_strtok_keep(char *output, char *src, char *delimit); -STB_EXTERN char * stb_strtok_invert(char *output, char *src, char *allowed); -STB_EXTERN char * stb_dupreplace(char *s, char *find, char *replace); -STB_EXTERN void stb_replaceinplace(char *s, char *find, char *replace); -STB_EXTERN char * stb_splitpath(char *output, char *src, int flag); -STB_EXTERN char * stb_splitpathdup(char *src, int flag); -STB_EXTERN char * stb_replacedir(char *output, char *src, char *dir); -STB_EXTERN char * stb_replaceext(char *output, char *src, char *ext); -STB_EXTERN void stb_fixpath(char *path); -STB_EXTERN char * stb_shorten_path_readable(char *path, int max_len); -STB_EXTERN int stb_suffix(char *s, char *t); -STB_EXTERN int stb_suffixi(char *s, char *t); -STB_EXTERN int stb_prefix(char *s, char *t); -STB_EXTERN char * stb_strichr(char *s, char t); -STB_EXTERN char * stb_stristr(char *s, char *t); -STB_EXTERN int stb_prefix_count(char *s, char *t); -STB_EXTERN const char * stb_plural(int n); // "s" or "" -STB_EXTERN size_t stb_strscpy(char *d, const char *s, size_t n); - -STB_EXTERN char **stb_tokens(char *src, char *delimit, int *count); -STB_EXTERN char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out); -STB_EXTERN char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out); -STB_EXTERN char **stb_tokens_allowempty(char *src, char *delimit, int *count); -STB_EXTERN char **stb_tokens_stripwhite(char *src, char *delimit, int *count); -STB_EXTERN char **stb_tokens_withdelim(char *src, char *delimit, int *count); -STB_EXTERN char **stb_tokens_quoted(char *src, char *delimit, int *count); -// with 'quoted', allow delimiters to appear inside quotation marks, and don't -// strip whitespace inside them (and we delete the quotation marks unless they -// appear back to back, in which case they're considered escaped) - -#ifdef STB_DEFINE - -size_t stb_strscpy(char *d, const char *s, size_t n) -{ - size_t len = strlen(s); - if (len >= n) { - if (n) d[0] = 0; - return 0; - } - strcpy(d, s); - return len + 1; -} - -const char *stb_plural(int n) -{ - return n == 1 ? "" : "s"; -} - -int stb_prefix(char *s, char *t) -{ - while (*t) - if (*s++ != *t++) - return STB_FALSE; - return STB_TRUE; -} - -int stb_prefix_count(char *s, char *t) -{ - int c = 0; - while (*t) { - if (*s++ != *t++) - break; - ++c; - } - return c; -} - -int stb_suffix(char *s, char *t) -{ - size_t n = strlen(s); - size_t m = strlen(t); - if (m <= n) - return 0 == strcmp(s + n - m, t); - else - return 0; -} - -int stb_suffixi(char *s, char *t) -{ - size_t n = strlen(s); - size_t m = strlen(t); - if (m <= n) - return 0 == stb_stricmp(s + n - m, t); - else - return 0; -} - -// originally I was using this table so that I could create known sentinel -// values--e.g. change whitetable[0] to be true if I was scanning for whitespace, -// and false if I was scanning for nonwhite. I don't appear to be using that -// functionality anymore (I do for tokentable, though), so just replace it -// with isspace() -char *stb_skipwhite(char *s) -{ - while (isspace((unsigned char)*s)) ++s; - return s; -} - -char *stb_skipnewline(char *s) -{ - if (s[0] == '\r' || s[0] == '\n') { - if (s[0] + s[1] == '\r' + '\n') ++s; - ++s; - } - return s; -} - -char *stb_trimwhite(char *s) -{ - int i, n; - s = stb_skipwhite(s); - n = (int)strlen(s); - for (i = n - 1; i >= 0; --i) - if (!isspace(s[i])) - break; - s[i + 1] = 0; - return s; -} - -char *stb_strncpy(char *s, char *t, int n) -{ - strncpy(s, t, n); - s[n - 1] = 0; - return s; -} - -char *stb_substr(char *t, int n) -{ - char *a; - int z = (int)strlen(t); - if (z < n) n = z; - a = (char *)malloc(n + 1); - strncpy(a, t, n); - a[n] = 0; - return a; -} - -char *stb_duplower(char *s) -{ - char *p = strdup(s), *q = p; - while (*q) { - *q = tolower(*q); - ++q; - } - return p; -} - -void stb_tolower(char *s) -{ - while (*s) { - *s = tolower(*s); - ++s; - } -} - -char *stb_strchr2(char *s, char x, char y) -{ - for (; *s; ++s) - if (*s == x || *s == y) - return s; - return NULL; -} - -char *stb_strrchr2(char *s, char x, char y) -{ - char *r = NULL; - for (; *s; ++s) - if (*s == x || *s == y) - r = s; - return r; -} - -char *stb_strichr(char *s, char t) -{ - if (tolower(t) == toupper(t)) - return strchr(s, t); - return stb_strchr2(s, (char)tolower(t), (char)toupper(t)); -} - -char *stb_stristr(char *s, char *t) -{ - size_t n = strlen(t); - char *z; - if (n == 0) return s; - while ((z = stb_strichr(s, *t)) != NULL) { - if (0 == stb_strnicmp(z, t, n)) - return z; - s = z + 1; - } - return NULL; -} - -static char *stb_strtok_raw(char *output, char *src, char *delimit, int keep, int invert) -{ - if (invert) { - while (*src && strchr(delimit, *src) != NULL) { - *output++ = *src++; - } - } - else { - while (*src && strchr(delimit, *src) == NULL) { - *output++ = *src++; - } - } - *output = 0; - if (keep) - return src; - else - return *src ? src + 1 : src; -} - -char *stb_strtok(char *output, char *src, char *delimit) -{ - return stb_strtok_raw(output, src, delimit, 0, 0); -} - -char *stb_strtok_keep(char *output, char *src, char *delimit) -{ - return stb_strtok_raw(output, src, delimit, 1, 0); -} - -char *stb_strtok_invert(char *output, char *src, char *delimit) -{ - return stb_strtok_raw(output, src, delimit, 1, 1); -} - -static char **stb_tokens_raw(char *src_, char *delimit, int *count, - int stripwhite, int allow_empty, char *start, char *end) -{ - int nested = 0; - unsigned char *src = (unsigned char *)src_; - static char stb_tokentable[256]; // rely on static initializion to 0 - static char stable[256], etable[256]; - char *out; - char **result; - int num = 0; - unsigned char *s; - - s = (unsigned char *)delimit; while (*s) stb_tokentable[*s++] = 1; - if (start) { - s = (unsigned char *)start; while (*s) stable[*s++] = 1; - s = (unsigned char *)end; if (s) while (*s) stable[*s++] = 1; - s = (unsigned char *)end; if (s) while (*s) etable[*s++] = 1; - } - stable[0] = 1; - - // two passes through: the first time, counting how many - s = (unsigned char *)src; - while (*s) { - // state: just found delimiter - // skip further delimiters - if (!allow_empty) { - stb_tokentable[0] = 0; - while (stb_tokentable[*s]) - ++s; - if (!*s) break; - } - ++num; - // skip further non-delimiters - stb_tokentable[0] = 1; - if (stripwhite == 2) { // quoted strings - while (!stb_tokentable[*s]) { - if (*s != '"') - ++s; - else { - ++s; - if (*s == '"') - ++s; // "" -> ", not start a string - else { - // begin a string - while (*s) { - if (s[0] == '"') { - if (s[1] == '"') s += 2; // "" -> " - else { ++s; break; } // terminating " - } - else - ++s; - } - } - } - } - } - else - while (nested || !stb_tokentable[*s]) { - if (stable[*s]) { - if (!*s) break; - if (end ? etable[*s] : nested) - --nested; - else - ++nested; - } - ++s; - } - if (allow_empty) { - if (*s) ++s; - } - } - // now num has the actual count... malloc our output structure - // need space for all the strings: strings won't be any longer than - // original input, since for every '\0' there's at least one delimiter - result = (char **)malloc(sizeof(*result) * (num + 1) + (s - src + 1)); - if (result == NULL) return result; - out = (char *)(result + (num + 1)); - // second pass: copy out the data - s = (unsigned char *)src; - num = 0; - nested = 0; - while (*s) { - char *last_nonwhite; - // state: just found delimiter - // skip further delimiters - if (!allow_empty) { - stb_tokentable[0] = 0; - if (stripwhite) - while (stb_tokentable[*s] || isspace(*s)) - ++s; - else - while (stb_tokentable[*s]) - ++s; - } - else if (stripwhite) { - while (isspace(*s)) ++s; - } - if (!*s) break; - // we're past any leading delimiters and whitespace - result[num] = out; - ++num; - // copy non-delimiters - stb_tokentable[0] = 1; - last_nonwhite = out - 1; - if (stripwhite == 2) { - while (!stb_tokentable[*s]) { - if (*s != '"') { - if (!isspace(*s)) last_nonwhite = out; - *out++ = *s++; - } - else { - ++s; - if (*s == '"') { - if (!isspace(*s)) last_nonwhite = out; - *out++ = *s++; // "" -> ", not start string - } - else { - // begin a quoted string - while (*s) { - if (s[0] == '"') { - if (s[1] == '"') { *out++ = *s; s += 2; } - else { ++s; break; } // terminating " - } - else - *out++ = *s++; - } - last_nonwhite = out - 1; // all in quotes counts as non-white - } - } - } - } - else { - while (nested || !stb_tokentable[*s]) { - if (!isspace(*s)) last_nonwhite = out; - if (stable[*s]) { - if (!*s) break; - if (end ? etable[*s] : nested) - --nested; - else - ++nested; - } - *out++ = *s++; - } - } - - if (stripwhite) // rewind to last non-whitespace char - out = last_nonwhite + 1; - *out++ = '\0'; - - if (*s) ++s; // skip delimiter - } - s = (unsigned char *)delimit; while (*s) stb_tokentable[*s++] = 0; - if (start) { - s = (unsigned char *)start; while (*s) stable[*s++] = 1; - s = (unsigned char *)end; if (s) while (*s) stable[*s++] = 1; - s = (unsigned char *)end; if (s) while (*s) etable[*s++] = 1; - } - if (count != NULL) *count = num; - result[num] = 0; - return result; -} - -char **stb_tokens(char *src, char *delimit, int *count) -{ - return stb_tokens_raw(src, delimit, count, 0, 0, 0, 0); -} - -char **stb_tokens_nested(char *src, char *delimit, int *count, char *nest_in, char *nest_out) -{ - return stb_tokens_raw(src, delimit, count, 0, 0, nest_in, nest_out); -} - -char **stb_tokens_nested_empty(char *src, char *delimit, int *count, char *nest_in, char *nest_out) -{ - return stb_tokens_raw(src, delimit, count, 0, 1, nest_in, nest_out); -} - -char **stb_tokens_allowempty(char *src, char *delimit, int *count) -{ - return stb_tokens_raw(src, delimit, count, 0, 1, 0, 0); -} - -char **stb_tokens_stripwhite(char *src, char *delimit, int *count) -{ - return stb_tokens_raw(src, delimit, count, 1, 1, 0, 0); -} - -char **stb_tokens_quoted(char *src, char *delimit, int *count) -{ - return stb_tokens_raw(src, delimit, count, 2, 1, 0, 0); -} - -char *stb_dupreplace(char *src, char *find, char *replace) -{ - size_t len_find = strlen(find); - size_t len_replace = strlen(replace); - int count = 0; - - char *s, *p, *q; - - s = strstr(src, find); - if (s == NULL) return strdup(src); - do { - ++count; - s = strstr(s + len_find, find); - } while (s != NULL); - - p = (char *)malloc(strlen(src) + count * (len_replace - len_find) + 1); - if (p == NULL) return p; - q = p; - s = src; - for (;;) { - char *t = strstr(s, find); - if (t == NULL) { - strcpy(q, s); - assert(strlen(p) == strlen(src) + count*(len_replace - len_find)); - return p; - } - memcpy(q, s, t - s); - q += t - s; - memcpy(q, replace, len_replace); - q += len_replace; - s = t + len_find; - } -} - -void stb_replaceinplace(char *src, char *find, char *replace) -{ - size_t len_find = strlen(find); - size_t len_replace = strlen(replace); - int delta; - - char *s, *p, *q; - - delta = len_replace - len_find; - assert(delta <= 0); - if (delta > 0) return; - - p = strstr(src, find); - if (p == NULL) return; - - s = q = p; - while (*s) { - memcpy(q, replace, len_replace); - p += len_find; - q += len_replace; - s = strstr(p, find); - if (s == NULL) s = p + strlen(p); - memmove(q, p, s - p); - q += s - p; - p = s; - } - *q = 0; -} - -void stb_fixpath(char *path) -{ - for (; *path; ++path) - if (*path == '\\') - *path = '/'; -} - -void stb__add_section(char *buffer, char *data, int curlen, int newlen) -{ - if (newlen < curlen) { - int z1 = newlen >> 1, z2 = newlen - z1; - memcpy(buffer, data, z1 - 1); - buffer[z1 - 1] = '.'; - buffer[z1 - 0] = '.'; - memcpy(buffer + z1 + 1, data + curlen - z2 + 1, z2 - 1); - } - else - memcpy(buffer, data, curlen); -} - -char * stb_shorten_path_readable(char *path, int len) -{ - static char buffer[1024]; - int n = strlen(path), n1, n2, r1, r2; - char *s; - if (n <= len) return path; - if (len > 1024) return path; - s = stb_strrchr2(path, '/', '\\'); - if (s) { - n1 = s - path + 1; - n2 = n - n1; - ++s; - } - else { - n1 = 0; - n2 = n; - s = path; - } - // now we need to reduce r1 and r2 so that they fit in len - if (n1 < len >> 1) { - r1 = n1; - r2 = len - r1; - } - else if (n2 < len >> 1) { - r2 = n2; - r1 = len - r2; - } - else { - r1 = n1 * len / n; - r2 = n2 * len / n; - if (r1 < len >> 2) r1 = len >> 2, r2 = len - r1; - if (r2 < len >> 2) r2 = len >> 2, r1 = len - r2; - } - assert(r1 <= n1 && r2 <= n2); - if (n1) - stb__add_section(buffer, path, n1, r1); - stb__add_section(buffer + r1, s, n2, r2); - buffer[len] = 0; - return buffer; -} - -static char *stb__splitpath_raw(char *buffer, char *path, int flag) -{ - int len = 0, x, y, n = (int)strlen(path), f1, f2; - char *s = stb_strrchr2(path, '/', '\\'); - char *t = strrchr(path, '.'); - if (s && t && t < s) t = NULL; - if (s) ++s; - - if (flag == STB_EXT_NO_PERIOD) - flag |= STB_EXT; - - if (!(flag & (STB_PATH | STB_FILE | STB_EXT))) return NULL; - - f1 = s == NULL ? 0 : s - path; // start of filename - f2 = t == NULL ? n : t - path; // just past end of filename - - if (flag & STB_PATH) { - x = 0; if (f1 == 0 && flag == STB_PATH) len = 2; - } - else if (flag & STB_FILE) { - x = f1; - } - else { - x = f2; - if (flag & STB_EXT_NO_PERIOD) - if (buffer[x] == '.') - ++x; - } - - if (flag & STB_EXT) - y = n; - else if (flag & STB_FILE) - y = f2; - else - y = f1; - - if (buffer == NULL) { - buffer = (char *)malloc(y - x + len + 1); - if (!buffer) return NULL; - } - - if (len) { strcpy(buffer, "./"); return buffer; } - strncpy(buffer, path + x, y - x); - buffer[y - x] = 0; - return buffer; -} - -char *stb_splitpath(char *output, char *src, int flag) -{ - return stb__splitpath_raw(output, src, flag); -} - -char *stb_splitpathdup(char *src, int flag) -{ - return stb__splitpath_raw(NULL, src, flag); -} - -char *stb_replacedir(char *output, char *src, char *dir) -{ - char buffer[4096]; - stb_splitpath(buffer, src, STB_FILE | STB_EXT); - if (dir) - sprintf(output, "%s/%s", dir, buffer); - else - strcpy(output, buffer); - return output; -} - -char *stb_replaceext(char *output, char *src, char *ext) -{ - char buffer[4096]; - stb_splitpath(buffer, src, STB_PATH | STB_FILE); - if (ext) - sprintf(output, "%s.%s", buffer, ext[0] == '.' ? ext + 1 : ext); - else - strcpy(output, buffer); - return output; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// stb_alloc - hierarchical allocator -// -// inspired by http://swapped.cc/halloc -// -// -// When you alloc a given block through stb_alloc, you have these choices: -// -// 1. does it have a parent? -// 2. can it have children? -// 3. can it be freed directly? -// 4. is it transferrable? -// 5. what is its alignment? -// -// Here are interesting combinations of those: -// -// children free transfer alignment -// arena Y Y N n/a -// no-overhead, chunked N N N normal -// string pool alloc N N N 1 -// parent-ptr, chunked Y N N normal -// low-overhead, unchunked N Y Y normal -// general purpose alloc Y Y Y normal -// -// Unchunked allocations will probably return 16-aligned pointers. If -// we 16-align the results, we have room for 4 pointers. For smaller -// allocations that allow finer alignment, we can reduce the pointers. -// -// The strategy is that given a pointer, assuming it has a header (only -// the no-overhead allocations have no header), we can determine the -// type of the header fields, and the number of them, by stepping backwards -// through memory and looking at the tags in the bottom bits. -// -// Implementation strategy: -// chunked allocations come from the middle of chunks, and can't -// be freed. thefore they do not need to be on a sibling chain. -// they may need child pointers if they have children. -// -// chunked, with-children -// void *parent; -// -// unchunked, no-children -- reduced storage -// void *next_sibling; -// void *prev_sibling_nextp; -// -// unchunked, general -// void *first_child; -// void *next_sibling; -// void *prev_sibling_nextp; -// void *chunks; -// -// so, if we code each of these fields with different bit patterns -// (actually same one for next/prev/child), then we can identify which -// each one is from the last field. - -STB_EXTERN void stb_free(void *p); -STB_EXTERN void *stb_malloc_global(size_t size); -STB_EXTERN void *stb_malloc(void *context, size_t size); -STB_EXTERN void *stb_malloc_nofree(void *context, size_t size); -STB_EXTERN void *stb_malloc_leaf(void *context, size_t size); -STB_EXTERN void *stb_malloc_raw(void *context, size_t size); -STB_EXTERN void *stb_realloc(void *ptr, size_t newsize); - -STB_EXTERN void stb_reassign(void *new_context, void *ptr); -STB_EXTERN void stb_malloc_validate(void *p, void *parent); - -extern int stb_alloc_chunk_size; -extern int stb_alloc_count_free; -extern int stb_alloc_count_alloc; -extern int stb_alloc_alignment; - -#ifdef STB_DEFINE - -int stb_alloc_chunk_size = 65536; -int stb_alloc_count_free = 0; -int stb_alloc_count_alloc = 0; -int stb_alloc_alignment = -16; - -typedef struct stb__chunk -{ - struct stb__chunk *next; - int data_left; - int alloc; -} stb__chunk; - -typedef struct -{ - void * next; - void ** prevn; -} stb__nochildren; - -typedef struct -{ - void ** prevn; - void * child; - void * next; - stb__chunk *chunks; -} stb__alloc; - -typedef struct -{ - stb__alloc *parent; -} stb__chunked; - -#define STB__PARENT 1 -#define STB__CHUNKS 2 - -typedef enum -{ - STB__nochildren = 0, - STB__chunked = STB__PARENT, - STB__alloc = STB__CHUNKS, - - STB__chunk_raw = 4, -} stb__alloc_type; - -// these functions set the bottom bits of a pointer efficiently -#define STB__DECODE(x,v) ((void *) ((char *) (x) - (v))) -#define STB__ENCODE(x,v) ((void *) ((char *) (x) + (v))) - -#define stb__parent(z) (stb__alloc *) STB__DECODE((z)->parent, STB__PARENT) -#define stb__chunks(z) (stb__chunk *) STB__DECODE((z)->chunks, STB__CHUNKS) - -#define stb__setparent(z,p) (z)->parent = (stb__alloc *) STB__ENCODE((p), STB__PARENT) -#define stb__setchunks(z,c) (z)->chunks = (stb__chunk *) STB__ENCODE((c), STB__CHUNKS) - -static stb__alloc stb__alloc_global = -{ - NULL, - NULL, - NULL, - (stb__chunk *)STB__ENCODE(NULL, STB__CHUNKS) -}; - -static stb__alloc_type stb__identify(void *p) -{ - void **q = (void **)p; - return (stb__alloc_type)((stb_uinta)q[-1] & 3); -} - -static void *** stb__prevn(void *p) -{ - if (stb__identify(p) == STB__alloc) { - stb__alloc *s = (stb__alloc *)p - 1; - return &s->prevn; - } - else { - stb__nochildren *s = (stb__nochildren *)p - 1; - return &s->prevn; - } -} - -void stb_free(void *p) -{ - if (p == NULL) return; - - // count frees so that unit tests can see what's happening - ++stb_alloc_count_free; - - switch (stb__identify(p)) { - case STB__chunked: - // freeing a chunked-block with children does nothing; - // they only get freed when the parent does - // surely this is wrong, and it should free them immediately? - // otherwise how are they getting put on the right chain? - return; - case STB__nochildren: { - stb__nochildren *s = (stb__nochildren *)p - 1; - // unlink from sibling chain - *(s->prevn) = s->next; - if (s->next) - *stb__prevn(s->next) = s->prevn; - free(s); - return; - } - case STB__alloc: { - stb__alloc *s = (stb__alloc *)p - 1; - stb__chunk *c, *n; - void *q; - - // unlink from sibling chain, if any - *(s->prevn) = s->next; - if (s->next) - *stb__prevn(s->next) = s->prevn; - - // first free chunks - c = (stb__chunk *)stb__chunks(s); - while (c != NULL) { - n = c->next; - stb_alloc_count_free += c->alloc; - free(c); - c = n; - } - - // validating - stb__setchunks(s, NULL); - s->prevn = NULL; - s->next = NULL; - - // now free children - while ((q = s->child) != NULL) { - stb_free(q); - } - - // now free self - free(s); - return; - } - default: - assert(0); /* NOTREACHED */ - } -} - -void stb_malloc_validate(void *p, void *parent) -{ - if (p == NULL) return; - - switch (stb__identify(p)) { - case STB__chunked: - return; - case STB__nochildren: { - stb__nochildren *n = (stb__nochildren *)p - 1; - if (n->prevn) - assert(*n->prevn == p); - if (n->next) { - assert(*stb__prevn(n->next) == &n->next); - stb_malloc_validate(n, parent); - } - return; - } - case STB__alloc: { - stb__alloc *s = (stb__alloc *)p - 1; - - if (s->prevn) - assert(*s->prevn == p); - - if (s->child) { - assert(*stb__prevn(s->child) == &s->child); - stb_malloc_validate(s->child, p); - } - - if (s->next) { - assert(*stb__prevn(s->next) == &s->next); - stb_malloc_validate(s->next, parent); - } - return; - } - default: - assert(0); /* NOTREACHED */ - } -} - -static void * stb__try_chunk(stb__chunk *c, int size, int align, int pre_align) -{ - char *memblock = (char *)(c + 1), *q; - stb_inta iq; - int start_offset; - - // we going to allocate at the end of the chunk, not the start. confusing, - // but it means we don't need both a 'limit' and a 'cur', just a 'cur'. - // the block ends at: p + c->data_left - // then we move back by size - start_offset = c->data_left - size; - - // now we need to check the alignment of that - q = memblock + start_offset; - iq = (stb_inta)q; - assert(sizeof(q) == sizeof(iq)); - - // suppose align = 2 - // then we need to retreat iq far enough that (iq & (2-1)) == 0 - // to get (iq & (align-1)) = 0 requires subtracting (iq & (align-1)) - - start_offset -= iq & (align - 1); - assert(((stb_uinta)(memblock + start_offset) & (align - 1)) == 0); - - // now, if that + pre_align works, go for it! - start_offset -= pre_align; - - if (start_offset >= 0) { - c->data_left = start_offset; - return memblock + start_offset; - } - - return NULL; -} - -static void stb__sort_chunks(stb__alloc *src) -{ - // of the first two chunks, put the chunk with more data left in it first - stb__chunk *c = stb__chunks(src), *d; - if (c == NULL) return; - d = c->next; - if (d == NULL) return; - if (c->data_left > d->data_left) return; - - c->next = d->next; - d->next = c; - stb__setchunks(src, d); -} - -static void * stb__alloc_chunk(stb__alloc *src, int size, int align, int pre_align) -{ - void *p; - stb__chunk *c = stb__chunks(src); - - if (c && size <= stb_alloc_chunk_size) { - - p = stb__try_chunk(c, size, align, pre_align); - if (p) { ++c->alloc; return p; } - - // try a second chunk to reduce wastage - if (c->next) { - p = stb__try_chunk(c->next, size, align, pre_align); - if (p) { ++c->alloc; return p; } - - // put the bigger chunk first, since the second will get buried - // the upshot of this is that, until it gets allocated from, chunk #2 - // is always the largest remaining chunk. (could formalize - // this with a heap!) - stb__sort_chunks(src); - c = stb__chunks(src); - } - } - - // allocate a new chunk - { - stb__chunk *n; - - int chunk_size = stb_alloc_chunk_size; - // we're going to allocate a new chunk to put this in - if (size > chunk_size) - chunk_size = size; - - assert(sizeof(*n) + pre_align <= 16); - - // loop trying to allocate a large enough chunk - // the loop is because the alignment may cause problems if it's big... - // and we don't know what our chunk alignment is going to be - while (1) { - n = (stb__chunk *)malloc(16 + chunk_size); - if (n == NULL) return NULL; - - n->data_left = chunk_size - sizeof(*n); - - p = stb__try_chunk(n, size, align, pre_align); - if (p != NULL) { - n->next = c; - stb__setchunks(src, n); - - // if we just used up the whole block immediately, - // move the following chunk up - n->alloc = 1; - if (size == chunk_size) - stb__sort_chunks(src); - - return p; - } - - free(n); - chunk_size += 16 + align; - } - } -} - -static stb__alloc * stb__get_context(void *context) -{ - if (context == NULL) { - return &stb__alloc_global; - } - else { - int u = stb__identify(context); - // if context is chunked, grab parent - if (u == STB__chunked) { - stb__chunked *s = (stb__chunked *)context - 1; - return stb__parent(s); - } - else { - return (stb__alloc *)context - 1; - } - } -} - -static void stb__insert_alloc(stb__alloc *src, stb__alloc *s) -{ - s->prevn = &src->child; - s->next = src->child; - src->child = s + 1; - if (s->next) - *stb__prevn(s->next) = &s->next; -} - -static void stb__insert_nochild(stb__alloc *src, stb__nochildren *s) -{ - s->prevn = &src->child; - s->next = src->child; - src->child = s + 1; - if (s->next) - *stb__prevn(s->next) = &s->next; -} - -static void * malloc_base(void *context, size_t size, stb__alloc_type t, int align) -{ - void *p; - - stb__alloc *src = stb__get_context(context); - - if (align <= 0) { - // compute worst-case C packed alignment - // e.g. a 24-byte struct is 8-aligned - int align_proposed = 1 << stb_lowbit8(size); - - if (align_proposed < 0) - align_proposed = 4; - - if (align_proposed == 0) { - if (size == 0) - align_proposed = 1; - else - align_proposed = 256; - } - - // a negative alignment means 'don't align any larger - // than this'; so -16 means we align 1,2,4,8, or 16 - - if (align < 0) { - if (align_proposed > -align) - align_proposed = -align; - } - - align = align_proposed; - } - - assert(stb_is_pow2(align)); - - // don't cause misalignment when allocating nochildren - if (t == STB__nochildren && align > 8) - t = STB__alloc; - - switch (t) { - case STB__alloc: { - stb__alloc *s = (stb__alloc *)malloc(size + sizeof(*s)); - if (s == NULL) return NULL; - p = s + 1; - s->child = NULL; - stb__insert_alloc(src, s); - - stb__setchunks(s, NULL); - break; - } - - case STB__nochildren: { - stb__nochildren *s = (stb__nochildren *)malloc(size + sizeof(*s)); - if (s == NULL) return NULL; - p = s + 1; - stb__insert_nochild(src, s); - break; - } - - case STB__chunk_raw: { - p = stb__alloc_chunk(src, size, align, 0); - if (p == NULL) return NULL; - break; - } - - case STB__chunked: { - stb__chunked *s; - if (align < sizeof(stb_uintptr)) align = sizeof(stb_uintptr); - s = (stb__chunked *)stb__alloc_chunk(src, size, align, sizeof(*s)); - if (s == NULL) return NULL; - stb__setparent(s, src); - p = s + 1; - break; - } - - default: p = NULL; assert(0); /* NOTREACHED */ - } - - ++stb_alloc_count_alloc; - return p; -} - -void *stb_malloc_global(size_t size) -{ - return malloc_base(NULL, size, STB__alloc, stb_alloc_alignment); -} - -void *stb_malloc(void *context, size_t size) -{ - return malloc_base(context, size, STB__alloc, stb_alloc_alignment); -} - -void *stb_malloc_nofree(void *context, size_t size) -{ - return malloc_base(context, size, STB__chunked, stb_alloc_alignment); -} - -void *stb_malloc_leaf(void *context, size_t size) -{ - return malloc_base(context, size, STB__nochildren, stb_alloc_alignment); -} - -void *stb_malloc_raw(void *context, size_t size) -{ - return malloc_base(context, size, STB__chunk_raw, stb_alloc_alignment); -} - -char *stb_malloc_string(void *context, size_t size) -{ - return (char *)malloc_base(context, size, STB__chunk_raw, 1); -} - -void *stb_realloc(void *ptr, size_t newsize) -{ - stb__alloc_type t; - - if (ptr == NULL) return stb_malloc(NULL, newsize); - if (newsize == 0) { stb_free(ptr); return NULL; } - - t = stb__identify(ptr); - assert(t == STB__alloc || t == STB__nochildren); - - if (t == STB__alloc) { - stb__alloc *s = (stb__alloc *)ptr - 1; - - s = (stb__alloc *)realloc(s, newsize + sizeof(*s)); - if (s == NULL) return NULL; - - ptr = s + 1; - - // update pointers - (*s->prevn) = ptr; - if (s->next) - *stb__prevn(s->next) = &s->next; - - if (s->child) - *stb__prevn(s->child) = &s->child; - - return ptr; - } - else { - stb__nochildren *s = (stb__nochildren *)ptr - 1; - - s = (stb__nochildren *)realloc(ptr, newsize + sizeof(s)); - if (s == NULL) return NULL; - - // update pointers - (*s->prevn) = s + 1; - if (s->next) - *stb__prevn(s->next) = &s->next; - - return s + 1; - } -} - -void *stb_realloc_c(void *context, void *ptr, size_t newsize) -{ - if (ptr == NULL) return stb_malloc(context, newsize); - if (newsize == 0) { stb_free(ptr); return NULL; } - // @TODO: verify you haven't changed contexts - return stb_realloc(ptr, newsize); -} - -void stb_reassign(void *new_context, void *ptr) -{ - stb__alloc *src = stb__get_context(new_context); - - stb__alloc_type t = stb__identify(ptr); - assert(t == STB__alloc || t == STB__nochildren); - - if (t == STB__alloc) { - stb__alloc *s = (stb__alloc *)ptr - 1; - - // unlink from old - *(s->prevn) = s->next; - if (s->next) - *stb__prevn(s->next) = s->prevn; - - stb__insert_alloc(src, s); - } - else { - stb__nochildren *s = (stb__nochildren *)ptr - 1; - - // unlink from old - *(s->prevn) = s->next; - if (s->next) - *stb__prevn(s->next) = s->prevn; - - stb__insert_nochild(src, s); - } -} - -#endif - - -////////////////////////////////////////////////////////////////////////////// -// -// stb_arr -// -// An stb_arr is directly useable as a pointer (use the actual type in your -// definition), but when it resizes, it returns a new pointer and you can't -// use the old one, so you have to be careful to copy-in-out as necessary. -// -// Use a NULL pointer as a 0-length array. -// -// float *my_array = NULL, *temp; -// -// // add elements on the end one at a time -// stb_arr_push(my_array, 0.0f); -// stb_arr_push(my_array, 1.0f); -// stb_arr_push(my_array, 2.0f); -// -// assert(my_array[1] == 2.0f); -// -// // add an uninitialized element at the end, then assign it -// *stb_arr_add(my_array) = 3.0f; -// -// // add three uninitialized elements at the end -// temp = stb_arr_addn(my_array,3); -// temp[0] = 4.0f; -// temp[1] = 5.0f; -// temp[2] = 6.0f; -// -// assert(my_array[5] == 5.0f); -// -// // remove the last one -// stb_arr_pop(my_array); -// -// assert(stb_arr_len(my_array) == 6); - - -#ifdef STB_MALLOC_WRAPPER -#define STB__PARAMS , char *file, int line -#define STB__ARGS , file, line -#else -#define STB__PARAMS -#define STB__ARGS -#endif - -// calling this function allocates an empty stb_arr attached to p -// (whereas NULL isn't attached to anything) -STB_EXTERN void stb_arr_malloc(void **target, void *context); - -// call this function with a non-NULL value to have all successive -// stbs that are created be attached to the associated parent. Note -// that once a given stb_arr is non-empty, it stays attached to its -// current parent, even if you call this function again. -// it turns the previous value, so you can restore it -STB_EXTERN void* stb_arr_malloc_parent(void *p); - -// simple functions written on top of other functions -#define stb_arr_empty(a) ( stb_arr_len(a) == 0 ) -#define stb_arr_add(a) ( stb_arr_addn((a),1) ) -#define stb_arr_push(a,v) ( *stb_arr_add(a)=(v) ) - -typedef struct -{ - int len, limit; - int stb_malloc; - unsigned int signature; -} stb__arr; - -#define stb_arr_signature 0x51bada7b // ends with 0123 in decimal - -// access the header block stored before the data -#define stb_arrhead(a) /*lint --e(826)*/ (((stb__arr *) (a)) - 1) -#define stb_arrhead2(a) /*lint --e(826)*/ (((stb__arr *) (a)) - 1) - -#ifdef STB_DEBUG -#define stb_arr_check(a) assert(!a || stb_arrhead(a)->signature == stb_arr_signature) -#define stb_arr_check2(a) assert(!a || stb_arrhead2(a)->signature == stb_arr_signature) -#else -#define stb_arr_check(a) ((void) 0) -#define stb_arr_check2(a) ((void) 0) -#endif - -// ARRAY LENGTH - -// get the array length; special case if pointer is NULL -#define stb_arr_len(a) (a ? stb_arrhead(a)->len : 0) -#define stb_arr_len2(a) ((stb__arr *) (a) ? stb_arrhead2(a)->len : 0) -#define stb_arr_lastn(a) (stb_arr_len(a)-1) - -// check whether a given index is valid -- tests 0 <= i < stb_arr_len(a) -#define stb_arr_valid(a,i) (a ? (int) (i) < stb_arrhead(a)->len : 0) - -// change the array length so is is exactly N entries long, creating -// uninitialized entries as needed -#define stb_arr_setlen(a,n) \ - (stb__arr_setlen((void **) &(a), sizeof(a[0]), (n))) - -// change the array length so that N is a valid index (that is, so -// it is at least N entries long), creating uninitialized entries as needed -#define stb_arr_makevalid(a,n) \ - (stb_arr_len(a) < (n)+1 ? stb_arr_setlen(a,(n)+1),(a) : (a)) - -// remove the last element of the array, returning it -#define stb_arr_pop(a) ((stb_arr_check(a), (a))[--stb_arrhead(a)->len]) - -// access the last element in the array -#define stb_arr_last(a) ((stb_arr_check(a), (a))[stb_arr_len(a)-1]) - -// is iterator at end of list? -#define stb_arr_end(a,i) ((i) >= &(a)[stb_arr_len(a)]) - -// (internal) change the allocated length of the array -#define stb_arr__grow(a,n) (stb_arr_check(a), stb_arrhead(a)->len += (n)) - -// add N new unitialized elements to the end of the array -#define stb_arr__addn(a,n) /*lint --e(826)*/ \ - ((stb_arr_len(a)+(n) > stb_arrcurmax(a)) \ - ? (stb__arr_addlen((void **) &(a),sizeof(*a),(n)),0) \ - : ((stb_arr__grow(a,n), 0))) - -// add N new unitialized elements to the end of the array, and return -// a pointer to the first new one -#define stb_arr_addn(a,n) (stb_arr__addn((a),n),(a)+stb_arr_len(a)-(n)) - -// add N new uninitialized elements starting at index 'i' -#define stb_arr_insertn(a,i,n) (stb__arr_insertn((void **) &(a), sizeof(*a), i, n)) - -// insert an element at i -#define stb_arr_insert(a,i,v) (stb__arr_insertn((void **) &(a), sizeof(*a), i, 1), ((a)[i] = v)) - -// delete N elements from the middle starting at index 'i' -#define stb_arr_deleten(a,i,n) (stb__arr_deleten((void **) &(a), sizeof(*a), i, n)) - -// delete the i'th element -#define stb_arr_delete(a,i) stb_arr_deleten(a,i,1) - -// delete the i'th element, swapping down from the end -#define stb_arr_fastdelete(a,i) \ - (stb_swap(&a[i], &a[stb_arrhead(a)->len-1], sizeof(*a)), stb_arr_pop(a)) - - -// ARRAY STORAGE - -// get the array maximum storage; special case if NULL -#define stb_arrcurmax(a) (a ? stb_arrhead(a)->limit : 0) -#define stb_arrcurmax2(a) (a ? stb_arrhead2(a)->limit : 0) - -// set the maxlength of the array to n in anticipation of further growth -#define stb_arr_setsize(a,n) (stb_arr_check(a), stb__arr_setsize((void **) &(a),sizeof((a)[0]),n)) - -// make sure maxlength is large enough for at least N new allocations -#define stb_arr_atleast(a,n) (stb_arr_len(a)+(n) > stb_arrcurmax(a) \ - ? stb_arr_setsize((a), (n)) : 0) - -// make a copy of a given array (copies contents via 'memcpy'!) -#define stb_arr_copy(a) stb__arr_copy(a, sizeof((a)[0])) - -// compute the storage needed to store all the elements of the array -#define stb_arr_storage(a) (stb_arr_len(a) * sizeof((a)[0])) - -#define stb_arr_for(v,arr) for((v)=(arr); (v) < (arr)+stb_arr_len(arr); ++(v)) - -// IMPLEMENTATION - -STB_EXTERN void stb_arr_free_(void **p); -STB_EXTERN void *stb__arr_copy_(void *p, int elem_size); -STB_EXTERN void stb__arr_setsize_(void **p, int size, int limit STB__PARAMS); -STB_EXTERN void stb__arr_setlen_(void **p, int size, int newlen STB__PARAMS); -STB_EXTERN void stb__arr_addlen_(void **p, int size, int addlen STB__PARAMS); -STB_EXTERN void stb__arr_deleten_(void **p, int size, int loc, int n STB__PARAMS); -STB_EXTERN void stb__arr_insertn_(void **p, int size, int loc, int n STB__PARAMS); - -#define stb_arr_free(p) stb_arr_free_((void **) &(p)) -#define stb__arr_copy stb__arr_copy_ - -#ifndef STB_MALLOC_WRAPPER -#define stb__arr_setsize stb__arr_setsize_ -#define stb__arr_setlen stb__arr_setlen_ -#define stb__arr_addlen stb__arr_addlen_ -#define stb__arr_deleten stb__arr_deleten_ -#define stb__arr_insertn stb__arr_insertn_ -#else -#define stb__arr_addlen(p,s,n) stb__arr_addlen_(p,s,n,__FILE__,__LINE__) -#define stb__arr_setlen(p,s,n) stb__arr_setlen_(p,s,n,__FILE__,__LINE__) -#define stb__arr_setsize(p,s,n) stb__arr_setsize_(p,s,n,__FILE__,__LINE__) -#define stb__arr_deleten(p,s,i,n) stb__arr_deleten_(p,s,i,n,__FILE__,__LINE__) -#define stb__arr_insertn(p,s,i,n) stb__arr_insertn_(p,s,i,n,__FILE__,__LINE__) -#endif - -#ifdef STB_DEFINE -static void *stb__arr_context; - -void *stb_arr_malloc_parent(void *p) -{ - void *q = stb__arr_context; - stb__arr_context = p; - return q; -} - -void stb_arr_malloc(void **target, void *context) -{ - stb__arr *q = (stb__arr *)stb_malloc(context, sizeof(*q)); - q->len = q->limit = 0; - q->stb_malloc = 1; - q->signature = stb_arr_signature; - *target = (void *)(q + 1); -} - -static void * stb__arr_malloc(int size) -{ - if (stb__arr_context) - return stb_malloc(stb__arr_context, size); - return malloc(size); -} - -void * stb__arr_copy_(void *p, int elem_size) -{ - stb__arr *q; - if (p == NULL) return p; - q = (stb__arr *)stb__arr_malloc(sizeof(*q) + elem_size * stb_arrhead2(p)->limit); - stb_arr_check2(p); - memcpy(q, stb_arrhead2(p), sizeof(*q) + elem_size * stb_arrhead2(p)->len); - q->stb_malloc = !!stb__arr_context; - return q + 1; -} - -void stb_arr_free_(void **pp) -{ - void *p = *pp; - stb_arr_check2(p); - if (p) { - stb__arr *q = stb_arrhead2(p); - if (q->stb_malloc) - stb_free(q); - else - free(q); - } - *pp = NULL; -} - -static void stb__arrsize_(void **pp, int size, int limit, int len STB__PARAMS) -{ - void *p = *pp; - stb__arr *a; - stb_arr_check2(p); - if (p == NULL) { - if (len == 0 && size == 0) return; - a = (stb__arr *)stb__arr_malloc(sizeof(*a) + size*limit); - a->limit = limit; - a->len = len; - a->stb_malloc = !!stb__arr_context; - a->signature = stb_arr_signature; - } - else { - a = stb_arrhead2(p); - a->len = len; - if (a->limit < limit) { - void *p; - if (a->limit >= 4 && limit < a->limit * 2) - limit = a->limit * 2; - if (a->stb_malloc) - p = stb_realloc(a, sizeof(*a) + limit*size); - else -#ifdef STB_MALLOC_WRAPPER - p = stb__realloc(a, sizeof(*a) + limit*size, file, line); -#else - p = realloc(a, sizeof(*a) + limit*size); -#endif - if (p) { - a = (stb__arr *)p; - a->limit = limit; - } - else { - // throw an error! - } - } - } - a->len = stb_min(a->len, a->limit); - *pp = a + 1; -} - -void stb__arr_setsize_(void **pp, int size, int limit STB__PARAMS) -{ - void *p = *pp; - stb_arr_check2(p); - stb__arrsize_(pp, size, limit, stb_arr_len2(p) STB__ARGS); -} - -void stb__arr_setlen_(void **pp, int size, int newlen STB__PARAMS) -{ - void *p = *pp; - stb_arr_check2(p); - if (stb_arrcurmax2(p) < newlen || p == NULL) { - stb__arrsize_(pp, size, newlen, newlen STB__ARGS); - } - else { - stb_arrhead2(p)->len = newlen; - } -} - -void stb__arr_addlen_(void **p, int size, int addlen STB__PARAMS) -{ - stb__arr_setlen_(p, size, stb_arr_len2(*p) + addlen STB__ARGS); -} - -void stb__arr_insertn_(void **pp, int size, int i, int n STB__PARAMS) -{ - void *p = *pp; - if (n) { - int z; - - if (p == NULL) { - stb__arr_addlen_(pp, size, n STB__ARGS); - return; - } - - z = stb_arr_len2(p); - stb__arr_addlen_(&p, size, n STB__ARGS); - memmove((char *)p + (i + n)*size, (char *)p + i*size, size * (z - i)); - } - *pp = p; -} - -void stb__arr_deleten_(void **pp, int size, int i, int n STB__PARAMS) -{ - void *p = *pp; - if (n) { - memmove((char *)p + i*size, (char *)p + (i + n)*size, size * (stb_arr_len2(p) - (i + n))); - stb_arrhead2(p)->len -= n; - } - *pp = p; -} - -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Hashing -// -// typical use for this is to make a power-of-two hash table. -// -// let N = size of table (2^n) -// let H = stb_hash(str) -// let S = stb_rehash(H) | 1 -// -// then hash probe sequence P(i) for i=0..N-1 -// P(i) = (H + S*i) & (N-1) -// -// the idea is that H has 32 bits of hash information, but the -// table has only, say, 2^20 entries so only uses 20 of the bits. -// then by rehashing the original H we get 2^12 different probe -// sequences for a given initial probe location. (So it's optimal -// for 64K tables and its optimality decreases past that.) -// -// ok, so I've added something that generates _two separate_ -// 32-bit hashes simultaneously which should scale better to -// very large tables. - - -STB_EXTERN unsigned int stb_hash(char *str); -STB_EXTERN unsigned int stb_hashptr(void *p); -STB_EXTERN unsigned int stb_hashlen(char *str, int len); -STB_EXTERN unsigned int stb_rehash_improved(unsigned int v); -STB_EXTERN unsigned int stb_hash_fast(void *p, int len); -STB_EXTERN unsigned int stb_hash2(char *str, unsigned int *hash2_ptr); -STB_EXTERN unsigned int stb_hash_number(unsigned int hash); - -#define stb_rehash(x) ((x) + ((x) >> 6) + ((x) >> 19)) - -#ifdef STB_DEFINE -unsigned int stb_hash(char *str) -{ - unsigned int hash = 0; - while (*str) - hash = (hash << 7) + (hash >> 25) + *str++; - return hash + (hash >> 16); -} - -unsigned int stb_hashlen(char *str, int len) -{ - unsigned int hash = 0; - while (len-- > 0 && *str) - hash = (hash << 7) + (hash >> 25) + *str++; - return hash + (hash >> 16); -} - -unsigned int stb_hashptr(void *p) -{ - unsigned int x = (unsigned int)(size_t)p; - - // typically lacking in low bits and high bits - x = stb_rehash(x); - x += x << 16; - - // pearson's shuffle - x ^= x << 3; - x += x >> 5; - x ^= x << 2; - x += x >> 15; - x ^= x << 10; - return stb_rehash(x); -} - -unsigned int stb_rehash_improved(unsigned int v) -{ - return stb_hashptr((void *)(size_t)v); -} - -unsigned int stb_hash2(char *str, unsigned int *hash2_ptr) -{ - unsigned int hash1 = 0x3141592c; - unsigned int hash2 = 0x77f044ed; - while (*str) { - hash1 = (hash1 << 7) + (hash1 >> 25) + *str; - hash2 = (hash2 << 11) + (hash2 >> 21) + *str; - ++str; - } - *hash2_ptr = hash2 + (hash1 >> 16); - return hash1 + (hash2 >> 16); -} - -// Paul Hsieh hash -#define stb__get16_slow(p) ((p)[0] + ((p)[1] << 8)) -#if defined(_MSC_VER) -#define stb__get16(p) (*((unsigned short *) (p))) -#else -#define stb__get16(p) stb__get16_slow(p) -#endif - -unsigned int stb_hash_fast(void *p, int len) -{ - unsigned char *q = (unsigned char *)p; - unsigned int hash = len; - - if (len <= 0 || q == NULL) return 0; - - /* Main loop */ - if (((int)(size_t)q & 1) == 0) { - for (; len > 3; len -= 4) { - unsigned int val; - hash += stb__get16(q); - val = (stb__get16(q + 2) << 11); - hash = (hash << 16) ^ hash ^ val; - q += 4; - hash += hash >> 11; - } - } - else { - for (; len > 3; len -= 4) { - unsigned int val; - hash += stb__get16_slow(q); - val = (stb__get16_slow(q + 2) << 11); - hash = (hash << 16) ^ hash ^ val; - q += 4; - hash += hash >> 11; - } - } - - /* Handle end cases */ - switch (len) { - case 3: hash += stb__get16_slow(q); - hash ^= hash << 16; - hash ^= q[2] << 18; - hash += hash >> 11; - break; - case 2: hash += stb__get16_slow(q); - hash ^= hash << 11; - hash += hash >> 17; - break; - case 1: hash += q[0]; - hash ^= hash << 10; - hash += hash >> 1; - break; - case 0: break; - } - - /* Force "avalanching" of final 127 bits */ - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - - return hash; -} - -unsigned int stb_hash_number(unsigned int hash) -{ - hash ^= hash << 3; - hash += hash >> 5; - hash ^= hash << 4; - hash += hash >> 17; - hash ^= hash << 25; - hash += hash >> 6; - return hash; -} - -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Perfect hashing for ints/pointers -// -// This is mainly useful for making faster pointer-indexed tables -// that don't change frequently. E.g. for stb_ischar(). -// - -typedef struct -{ - stb_uint32 addend; - stb_uint multiplicand; - stb_uint b_mask; - stb_uint8 small_bmap[16]; - stb_uint16 *large_bmap; - - stb_uint table_mask; - stb_uint32 *table; -} stb_perfect; - -STB_EXTERN int stb_perfect_create(stb_perfect *, unsigned int*, int n); -STB_EXTERN void stb_perfect_destroy(stb_perfect *); -STB_EXTERN int stb_perfect_hash(stb_perfect *, unsigned int x); -extern int stb_perfect_hash_max_failures; - -#ifdef STB_DEFINE - -int stb_perfect_hash_max_failures; - -int stb_perfect_hash(stb_perfect *p, unsigned int x) -{ - stb_uint m = x * p->multiplicand; - stb_uint y = x >> 16; - stb_uint bv = (m >> 24) + y; - stb_uint av = (m + y) >> 12; - if (p->table == NULL) return -1; // uninitialized table fails - bv &= p->b_mask; - av &= p->table_mask; - if (p->large_bmap) - av ^= p->large_bmap[bv]; - else - av ^= p->small_bmap[bv]; - return p->table[av] == x ? av : -1; -} - -static void stb__perfect_prehash(stb_perfect *p, stb_uint x, stb_uint16 *a, stb_uint16 *b) -{ - stb_uint m = x * p->multiplicand; - stb_uint y = x >> 16; - stb_uint bv = (m >> 24) + y; - stb_uint av = (m + y) >> 12; - bv &= p->b_mask; - av &= p->table_mask; - *b = bv; - *a = av; -} - -static unsigned long stb__perfect_rand(void) -{ - static unsigned long stb__rand; - stb__rand = stb__rand * 2147001325 + 715136305; - return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16)); -} - -typedef struct { - unsigned short count; - unsigned short b; - unsigned short map; - unsigned short *entries; -} stb__slot; - -static int stb__slot_compare(const void *p, const void *q) -{ - stb__slot *a = (stb__slot *)p; - stb__slot *b = (stb__slot *)q; - return a->count > b->count ? -1 : a->count < b->count; // sort large to small -} - -int stb_perfect_create(stb_perfect *p, unsigned int *v, int n) -{ - unsigned int buffer1[64], buffer2[64], buffer3[64], buffer4[64], buffer5[32]; - unsigned short *as = (unsigned short *)stb_temp(buffer1, sizeof(*v)*n); - unsigned short *bs = (unsigned short *)stb_temp(buffer2, sizeof(*v)*n); - unsigned short *entries = (unsigned short *)stb_temp(buffer4, sizeof(*entries) * n); - int size = 1 << stb_log2_ceil(n), bsize = 8; - int failure = 0, i, j, k; - - assert(n <= 32768); - p->large_bmap = NULL; - - for (;;) { - stb__slot *bcount = (stb__slot *)stb_temp(buffer3, sizeof(*bcount) * bsize); - unsigned short *bloc = (unsigned short *)stb_temp(buffer5, sizeof(*bloc) * bsize); - unsigned short *e; - int bad = 0; - - p->addend = stb__perfect_rand(); - p->multiplicand = stb__perfect_rand() | 1; - p->table_mask = size - 1; - p->b_mask = bsize - 1; - p->table = (stb_uint32 *)malloc(size * sizeof(*p->table)); - - for (i = 0; i < bsize; ++i) { - bcount[i].b = i; - bcount[i].count = 0; - bcount[i].map = 0; - } - for (i = 0; i < n; ++i) { - stb__perfect_prehash(p, v[i], as + i, bs + i); - ++bcount[bs[i]].count; - } - qsort(bcount, bsize, sizeof(*bcount), stb__slot_compare); - e = entries; // now setup up their entries index - for (i = 0; i < bsize; ++i) { - bcount[i].entries = e; - e += bcount[i].count; - bcount[i].count = 0; - bloc[bcount[i].b] = i; - } - // now fill them out - for (i = 0; i < n; ++i) { - int b = bs[i]; - int w = bloc[b]; - bcount[w].entries[bcount[w].count++] = i; - } - stb_tempfree(buffer5, bloc); - // verify - for (i = 0; i < bsize; ++i) - for (j = 0; j < bcount[i].count; ++j) - assert(bs[bcount[i].entries[j]] == bcount[i].b); - memset(p->table, 0, size * sizeof(*p->table)); - - // check if any b has duplicate a - for (i = 0; i < bsize; ++i) { - if (bcount[i].count > 1) { - for (j = 0; j < bcount[i].count; ++j) { - if (p->table[as[bcount[i].entries[j]]]) - bad = 1; - p->table[as[bcount[i].entries[j]]] = 1; - } - for (j = 0; j < bcount[i].count; ++j) { - p->table[as[bcount[i].entries[j]]] = 0; - } - if (bad) break; - } - } - - if (!bad) { - // go through the bs and populate the table, first fit - for (i = 0; i < bsize; ++i) { - if (bcount[i].count) { - // go through the candidate table[b] values - for (j = 0; j < size; ++j) { - // go through the a values and see if they fit - for (k = 0; k < bcount[i].count; ++k) { - int a = as[bcount[i].entries[k]]; - if (p->table[(a^j)&p->table_mask]) { - break; // fails - } - } - // if succeeded, accept - if (k == bcount[i].count) { - bcount[i].map = j; - for (k = 0; k < bcount[i].count; ++k) { - int a = as[bcount[i].entries[k]]; - p->table[(a^j)&p->table_mask] = 1; - } - break; - } - } - if (j == size) - break; // no match for i'th entry, so break out in failure - } - } - if (i == bsize) { - // success... fill out map - if (bsize <= 16 && size <= 256) { - p->large_bmap = NULL; - for (i = 0; i < bsize; ++i) - p->small_bmap[bcount[i].b] = (stb_uint8)bcount[i].map; - } - else { - p->large_bmap = (unsigned short *)malloc(sizeof(*p->large_bmap) * bsize); - for (i = 0; i < bsize; ++i) - p->large_bmap[bcount[i].b] = bcount[i].map; - } - - // initialize table to v[0], so empty slots will fail - for (i = 0; i < size; ++i) - p->table[i] = v[0]; - - for (i = 0; i < n; ++i) - if (p->large_bmap) - p->table[as[i] ^ p->large_bmap[bs[i]]] = v[i]; - else - p->table[as[i] ^ p->small_bmap[bs[i]]] = v[i]; - - // and now validate that none of them collided - for (i = 0; i < n; ++i) - assert(stb_perfect_hash(p, v[i]) >= 0); - - stb_tempfree(buffer3, bcount); - break; - } - } - free(p->table); - p->table = NULL; - stb_tempfree(buffer3, bcount); - - ++failure; - if (failure >= 4 && bsize < size) bsize *= 2; - if (failure >= 8 && (failure & 3) == 0 && size < 4 * n) { - size *= 2; - bsize *= 2; - } - if (failure == 6) { - // make sure the input data is unique, so we don't infinite loop - unsigned int *data = (unsigned int *)stb_temp(buffer3, n * sizeof(*data)); - memcpy(data, v, sizeof(*data) * n); - qsort(data, n, sizeof(*data), stb_intcmp(0)); - for (i = 1; i < n; ++i) { - if (data[i] == data[i - 1]) - size = 0; // size is return value, so 0 it - } - stb_tempfree(buffer3, data); - if (!size) break; - } - } - - if (failure > stb_perfect_hash_max_failures) - stb_perfect_hash_max_failures = failure; - - stb_tempfree(buffer1, as); - stb_tempfree(buffer2, bs); - stb_tempfree(buffer4, entries); - - return size; -} - -void stb_perfect_destroy(stb_perfect *p) -{ - if (p->large_bmap) free(p->large_bmap); - if (p->table) free(p->table); - p->large_bmap = NULL; - p->table = NULL; - p->b_mask = 0; - p->table_mask = 0; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Perfect hash clients - -STB_EXTERN int stb_ischar(char s, char *set); - -#ifdef STB_DEFINE - -int stb_ischar(char c, char *set) -{ - static unsigned char bit[8] = { 1,2,4,8,16,32,64,128 }; - static stb_perfect p; - static unsigned char(*tables)[256]; - static char ** sets = NULL; - - int z = stb_perfect_hash(&p, (int)(size_t)set); - if (z < 0) { - int i, k, n, j, f; - // special code that means free all existing data - if (set == NULL) { - stb_arr_free(sets); - free(tables); - tables = NULL; - stb_perfect_destroy(&p); - return 0; - } - stb_arr_push(sets, set); - stb_perfect_destroy(&p); - n = stb_perfect_create(&p, (unsigned int *)(char **)sets, stb_arr_len(sets)); - assert(n != 0); - k = (n + 7) >> 3; - tables = (unsigned char(*)[256]) realloc(tables, sizeof(*tables) * k); - memset(tables, 0, sizeof(*tables) * k); - for (i = 0; i < stb_arr_len(sets); ++i) { - k = stb_perfect_hash(&p, (int)(size_t)sets[i]); - assert(k >= 0); - n = k >> 3; - f = bit[k & 7]; - for (j = 0; !j || sets[i][j]; ++j) { - tables[n][(unsigned char)sets[i][j]] |= f; - } - } - z = stb_perfect_hash(&p, (int)(size_t)set); - } - return tables[z >> 3][(unsigned char)c] & bit[z & 7]; -} - -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Instantiated data structures -// -// This is an attempt to implement a templated data structure. -// -// Hash table: call stb_define_hash(TYPE,N,KEY,K1,K2,HASH,VALUE) -// TYPE -- will define a structure type containing the hash table -// N -- the name, will prefix functions named: -// N create -// N destroy -// N get -// N set, N add, N update, -// N remove -// KEY -- the type of the key. 'x == y' must be valid -// K1,K2 -- keys never used by the app, used as flags in the hashtable -// HASH -- a piece of code ending with 'return' that hashes key 'k' -// VALUE -- the type of the value. 'x = y' must be valid -// -// Note that stb_define_hash_base can be used to define more sophisticated -// hash tables, e.g. those that make copies of the key or use special -// comparisons (e.g. strcmp). - -#define STB_(prefix,name) stb__##prefix##name -#define STB__(prefix,name) prefix##name -#define STB__use(x) x -#define STB__skip(x) - -#define stb_declare_hash(PREFIX,TYPE,N,KEY,VALUE) \ - typedef struct stb__st_##TYPE TYPE;\ - PREFIX int STB__(N, init)(TYPE *h, int count);\ - PREFIX int STB__(N, memory_usage)(TYPE *h);\ - PREFIX TYPE * STB__(N, create)(void);\ - PREFIX TYPE * STB__(N, copy)(TYPE *h);\ - PREFIX void STB__(N, destroy)(TYPE *h);\ - PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v);\ - PREFIX VALUE STB__(N,get)(TYPE *a, KEY k);\ - PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v);\ - PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v);\ - PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v);\ - PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v); - -#define STB_nocopy(x) (x) -#define STB_nodelete(x) 0 -#define STB_nofields -#define STB_nonullvalue(x) -#define STB_nullvalue(x) x -#define STB_safecompare(x) x -#define STB_nosafe(x) -#define STB_noprefix - -#ifdef __GNUC__ -#define STB__nogcc(x) -#else -#define STB__nogcc(x) x -#endif - -#define stb_define_hash_base(PREFIX,TYPE,FIELDS,N,NC,LOAD_FACTOR, \ - KEY,EMPTY,DEL,COPY,DISPOSE,SAFE, \ - VCOMPARE,CCOMPARE,HASH, \ - VALUE,HASVNULL,VNULL) \ - \ -typedef struct \ -{ \ - KEY k; \ - VALUE v; \ -} STB_(N,_hashpair); \ - \ -STB__nogcc( typedef struct stb__st_##TYPE TYPE; ) \ -struct stb__st_##TYPE { \ - FIELDS \ - STB_(N,_hashpair) *table; \ - unsigned int mask; \ - int count, limit; \ - int deleted; \ - \ - int delete_threshhold; \ - int grow_threshhold; \ - int shrink_threshhold; \ - unsigned char alloced, has_empty, has_del; \ - VALUE ev; VALUE dv; \ -}; \ - \ -static unsigned int STB_(N, hash)(KEY k) \ -{ \ - HASH \ -} \ - \ -PREFIX int STB__(N, init)(TYPE *h, int count) \ -{ \ - int i; \ - if (count < 4) count = 4; \ - h->limit = count; \ - h->count = 0; \ - h->mask = count-1; \ - h->deleted = 0; \ - h->grow_threshhold = (int) (count * LOAD_FACTOR); \ - h->has_empty = h->has_del = 0; \ - h->alloced = 0; \ - if (count <= 64) \ - h->shrink_threshhold = 0; \ - else \ - h->shrink_threshhold = (int) (count * (LOAD_FACTOR/2.25)); \ - h->delete_threshhold = (int) (count * (1-LOAD_FACTOR)/2); \ - h->table = (STB_(N,_hashpair)*) malloc(sizeof(h->table[0]) * count); \ - if (h->table == NULL) return 0; \ - /* ideally this gets turned into a memset32 automatically */ \ - for (i=0; i < count; ++i) \ - h->table[i].k = EMPTY; \ - return 1; \ -} \ - \ -PREFIX int STB__(N, memory_usage)(TYPE *h) \ -{ \ - return sizeof(*h) + h->limit * sizeof(h->table[0]); \ -} \ - \ -PREFIX TYPE * STB__(N, create)(void) \ -{ \ - TYPE *h = (TYPE *) malloc(sizeof(*h)); \ - if (h) { \ - if (STB__(N, init)(h, 16)) \ - h->alloced = 1; \ - else { free(h); h=NULL; } \ - } \ - return h; \ -} \ - \ -PREFIX void STB__(N, destroy)(TYPE *a) \ -{ \ - int i; \ - for (i=0; i < a->limit; ++i) \ - if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k, DEL)) \ - DISPOSE(a->table[i].k); \ - free(a->table); \ - if (a->alloced) \ - free(a); \ -} \ - \ -static void STB_(N, rehash)(TYPE *a, int count); \ - \ -PREFIX int STB__(N,get_flag)(TYPE *a, KEY k, VALUE *v) \ -{ \ - unsigned int h = STB_(N, hash)(k); \ - unsigned int n = h & a->mask, s; \ - if (CCOMPARE(k,EMPTY)){ if (a->has_empty) *v = a->ev; return a->has_empty;}\ - if (CCOMPARE(k,DEL)) { if (a->has_del ) *v = a->dv; return a->has_del; }\ - if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \ - SAFE(if (!CCOMPARE(a->table[n].k,DEL))) \ - if (VCOMPARE(a->table[n].k,k)) { *v = a->table[n].v; return 1; } \ - s = stb_rehash(h) | 1; \ - for(;;) { \ - n = (n + s) & a->mask; \ - if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \ - SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;) \ - if (VCOMPARE(a->table[n].k,k)) \ - { *v = a->table[n].v; return 1; } \ - } \ -} \ - \ -HASVNULL( \ - PREFIX VALUE STB__(N,get)(TYPE *a, KEY k) \ - { \ - VALUE v; \ - if (STB__(N,get_flag)(a,k,&v)) return v; \ - else return VNULL; \ - } \ -) \ - \ -PREFIX int STB__(N,getkey)(TYPE *a, KEY k, KEY *kout) \ -{ \ - unsigned int h = STB_(N, hash)(k); \ - unsigned int n = h & a->mask, s; \ - if (CCOMPARE(k,EMPTY)||CCOMPARE(k,DEL)) return 0; \ - if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \ - SAFE(if (!CCOMPARE(a->table[n].k,DEL))) \ - if (VCOMPARE(a->table[n].k,k)) { *kout = a->table[n].k; return 1; } \ - s = stb_rehash(h) | 1; \ - for(;;) { \ - n = (n + s) & a->mask; \ - if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \ - SAFE(if (CCOMPARE(a->table[n].k,DEL)) continue;) \ - if (VCOMPARE(a->table[n].k,k)) \ - { *kout = a->table[n].k; return 1; } \ - } \ -} \ - \ -static int STB_(N,addset)(TYPE *a, KEY k, VALUE v, \ - int allow_new, int allow_old, int copy) \ -{ \ - unsigned int h = STB_(N, hash)(k); \ - unsigned int n = h & a->mask; \ - int b = -1; \ - if (CCOMPARE(k,EMPTY)) { \ - if (a->has_empty ? allow_old : allow_new) { \ - n=a->has_empty; a->ev = v; a->has_empty = 1; return !n; \ - } else return 0; \ - } \ - if (CCOMPARE(k,DEL)) { \ - if (a->has_del ? allow_old : allow_new) { \ - n=a->has_del; a->dv = v; a->has_del = 1; return !n; \ - } else return 0; \ - } \ - if (!CCOMPARE(a->table[n].k, EMPTY)) { \ - unsigned int s; \ - if (CCOMPARE(a->table[n].k, DEL)) \ - b = n; \ - else if (VCOMPARE(a->table[n].k,k)) { \ - if (allow_old) \ - a->table[n].v = v; \ - return !allow_new; \ - } \ - s = stb_rehash(h) | 1; \ - for(;;) { \ - n = (n + s) & a->mask; \ - if (CCOMPARE(a->table[n].k, EMPTY)) break; \ - if (CCOMPARE(a->table[n].k, DEL)) { \ - if (b < 0) b = n; \ - } else if (VCOMPARE(a->table[n].k,k)) { \ - if (allow_old) \ - a->table[n].v = v; \ - return !allow_new; \ - } \ - } \ - } \ - if (!allow_new) return 0; \ - if (b < 0) b = n; else --a->deleted; \ - a->table[b].k = copy ? COPY(k) : k; \ - a->table[b].v = v; \ - ++a->count; \ - if (a->count > a->grow_threshhold) \ - STB_(N,rehash)(a, a->limit*2); \ - return 1; \ -} \ - \ -PREFIX int STB__(N, set)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,1,1);}\ -PREFIX int STB__(N, add)(TYPE *a, KEY k, VALUE v){return STB_(N,addset)(a,k,v,1,0,1);}\ -PREFIX int STB__(N, update)(TYPE*a,KEY k,VALUE v){return STB_(N,addset)(a,k,v,0,1,1);}\ - \ -PREFIX int STB__(N, remove)(TYPE *a, KEY k, VALUE *v) \ -{ \ - unsigned int h = STB_(N, hash)(k); \ - unsigned int n = h & a->mask, s; \ - if (CCOMPARE(k,EMPTY)) { if (a->has_empty) { if(v)*v = a->ev; a->has_empty=0; return 1; } return 0; } \ - if (CCOMPARE(k,DEL)) { if (a->has_del ) { if(v)*v = a->dv; a->has_del =0; return 1; } return 0; } \ - if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \ - if (SAFE(CCOMPARE(a->table[n].k,DEL) || ) !VCOMPARE(a->table[n].k,k)) { \ - s = stb_rehash(h) | 1; \ - for(;;) { \ - n = (n + s) & a->mask; \ - if (CCOMPARE(a->table[n].k,EMPTY)) return 0; \ - SAFE(if (CCOMPARE(a->table[n].k, DEL)) continue;) \ - if (VCOMPARE(a->table[n].k,k)) break; \ - } \ - } \ - DISPOSE(a->table[n].k); \ - a->table[n].k = DEL; \ - --a->count; \ - ++a->deleted; \ - if (v != NULL) \ - *v = a->table[n].v; \ - if (a->count < a->shrink_threshhold) \ - STB_(N, rehash)(a, a->limit >> 1); \ - else if (a->deleted > a->delete_threshhold) \ - STB_(N, rehash)(a, a->limit); \ - return 1; \ -} \ - \ -PREFIX TYPE * STB__(NC, copy)(TYPE *a) \ -{ \ - int i; \ - TYPE *h = (TYPE *) malloc(sizeof(*h)); \ - if (!h) return NULL; \ - if (!STB__(N, init)(h, a->limit)) { free(h); return NULL; } \ - h->count = a->count; \ - h->deleted = a->deleted; \ - h->alloced = 1; \ - h->ev = a->ev; h->dv = a->dv; \ - h->has_empty = a->has_empty; h->has_del = a->has_del; \ - memcpy(h->table, a->table, h->limit * sizeof(h->table[0])); \ - for (i=0; i < a->limit; ++i) \ - if (!CCOMPARE(h->table[i].k,EMPTY) && !CCOMPARE(h->table[i].k,DEL)) \ - h->table[i].k = COPY(h->table[i].k); \ - return h; \ -} \ - \ -static void STB_(N, rehash)(TYPE *a, int count) \ -{ \ - int i; \ - TYPE b; \ - STB__(N, init)(&b, count); \ - for (i=0; i < a->limit; ++i) \ - if (!CCOMPARE(a->table[i].k,EMPTY) && !CCOMPARE(a->table[i].k,DEL)) \ - STB_(N,addset)(&b, a->table[i].k, a->table[i].v,1,1,0); \ - free(a->table); \ - a->table = b.table; \ - a->mask = b.mask; \ - a->count = b.count; \ - a->limit = b.limit; \ - a->deleted = b.deleted; \ - a->delete_threshhold = b.delete_threshhold; \ - a->grow_threshhold = b.grow_threshhold; \ - a->shrink_threshhold = b.shrink_threshhold; \ -} - -#define STB_equal(a,b) ((a) == (b)) - -#define stb_define_hash(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE) \ - stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f, \ - KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe, \ - STB_equal,STB_equal,HASH, \ - VALUE,STB_nonullvalue,0) - -#define stb_define_hash_vnull(TYPE,N,KEY,EMPTY,DEL,HASH,VALUE,VNULL) \ - stb_define_hash_base(STB_noprefix, TYPE,STB_nofields,N,NC,0.85f, \ - KEY,EMPTY,DEL,STB_nocopy,STB_nodelete,STB_nosafe, \ - STB_equal,STB_equal,HASH, \ - VALUE,STB_nullvalue,VNULL) - -////////////////////////////////////////////////////////////////////////////// -// -// stb_ptrmap -// -// An stb_ptrmap data structure is an O(1) hash table between pointers. One -// application is to let you store "extra" data associated with pointers, -// which is why it was originally called stb_extra. - -stb_declare_hash(STB_EXTERN, stb_ptrmap, stb_ptrmap_, void *, void *) -stb_declare_hash(STB_EXTERN, stb_idict, stb_idict_, stb_int32, stb_int32) - -STB_EXTERN void stb_ptrmap_delete(stb_ptrmap *e, void(*free_func)(void *)); -STB_EXTERN stb_ptrmap *stb_ptrmap_new(void); - -STB_EXTERN stb_idict * stb_idict_new_size(int size); -STB_EXTERN void stb_idict_remove_all(stb_idict *e); - -#ifdef STB_DEFINE - -#define STB_EMPTY ((void *) 2) -#define STB_EDEL ((void *) 6) - -stb_define_hash_base(STB_noprefix, stb_ptrmap, STB_nofields, stb_ptrmap_, stb_ptrmap_, 0.85f, - void *, STB_EMPTY, STB_EDEL, STB_nocopy, STB_nodelete, STB_nosafe, - STB_equal, STB_equal, return stb_hashptr(k); , - void *, STB_nullvalue, NULL) - - stb_ptrmap *stb_ptrmap_new(void) -{ - return stb_ptrmap_create(); -} - -void stb_ptrmap_delete(stb_ptrmap *e, void(*free_func)(void *)) -{ - int i; - if (free_func) - for (i = 0; i < e->limit; ++i) - if (e->table[i].k != STB_EMPTY && e->table[i].k != STB_EDEL) { - if (free_func == free) - free(e->table[i].v); // allow STB_MALLOC_WRAPPER to operate - else - free_func(e->table[i].v); - } - stb_ptrmap_destroy(e); -} - -// extra fields needed for stua_dict -#define STB_IEMPTY ((int) 1) -#define STB_IDEL ((int) 3) -stb_define_hash_base(STB_noprefix, stb_idict, short type; short gc; STB_nofields, stb_idict_, stb_idict_, 0.85f, - stb_int32, STB_IEMPTY, STB_IDEL, STB_nocopy, STB_nodelete, STB_nosafe, - STB_equal, STB_equal, - return stb_rehash_improved(k); , stb_int32, STB_nonullvalue, 0) - - stb_idict * stb_idict_new_size(int size) -{ - stb_idict *e = (stb_idict *)malloc(sizeof(*e)); - if (e) { - if (!stb_is_pow2(size)) - size = 1 << stb_log2_ceil(size); - stb_idict_init(e, size); - e->alloced = 1; - } - return e; -} - -void stb_idict_remove_all(stb_idict *e) -{ - int n; - for (n = 0; n < e->limit; ++n) - e->table[n].k = STB_IEMPTY; - e->has_empty = e->has_del = 0; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// stb_sparse_ptr_matrix -// -// An stb_ptrmap data structure is an O(1) hash table storing an arbitrary -// block of data for a given pair of pointers. -// -// If create=0, returns - -typedef struct stb__st_stb_spmatrix stb_spmatrix; - -STB_EXTERN stb_spmatrix * stb_sparse_ptr_matrix_new(int val_size); -STB_EXTERN void stb_sparse_ptr_matrix_free(stb_spmatrix *z); -STB_EXTERN void * stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create); - -#ifdef STB_DEFINE -typedef struct -{ - void *a; - void *b; -} stb__ptrpair; - -static stb__ptrpair stb__ptrpair_empty = { (void *)1, (void *)1 }; -static stb__ptrpair stb__ptrpair_del = { (void *)2, (void *)2 }; - -#define STB__equal_ptrpair(x,y) ((x).a == (y).a && (x).b == (y).b) - -stb_define_hash_base(static, stb_spmatrix, int val_size; void *arena; , stb__spmatrix_, stb__spmatrix_, 0.85, - stb__ptrpair, stb__ptrpair_empty, stb__ptrpair_del, - STB_nocopy, STB_nodelete, STB_nosafe, - STB__equal_ptrpair, STB__equal_ptrpair, return stb_rehash(stb_hashptr(k.a)) + stb_hashptr(k.b); , - void *, STB_nullvalue, 0) - - stb_spmatrix *stb_sparse_ptr_matrix_new(int val_size) -{ - stb_spmatrix *m = stb__spmatrix_create(); - if (m) m->val_size = val_size; - if (m) m->arena = stb_malloc_global(1); - return m; -} - -void stb_sparse_ptr_matrix_free(stb_spmatrix *z) -{ - if (z->arena) stb_free(z->arena); - stb__spmatrix_destroy(z); -} - -void *stb_sparse_ptr_matrix_get(stb_spmatrix *z, void *a, void *b, int create) -{ - stb__ptrpair t = { a,b }; - void *data = stb__spmatrix_get(z, t); - if (!data && create) { - data = stb_malloc_raw(z->arena, z->val_size); - if (!data) return NULL; - memset(data, 0, z->val_size); - stb__spmatrix_add(z, t, data); - } - return data; -} -#endif - - - -////////////////////////////////////////////////////////////////////////////// -// -// SDICT: Hash Table for Strings (symbol table) -// -// if "use_arena=1", then strings will be copied -// into blocks and never freed until the sdict is freed; -// otherwise they're malloc()ed and free()d on the fly. -// (specify use_arena=1 if you never stb_sdict_remove) - -stb_declare_hash(STB_EXTERN, stb_sdict, stb_sdict_, char *, void *) - -STB_EXTERN stb_sdict * stb_sdict_new(int use_arena); -STB_EXTERN stb_sdict * stb_sdict_copy(stb_sdict*); -STB_EXTERN void stb_sdict_delete(stb_sdict *); -STB_EXTERN void * stb_sdict_change(stb_sdict *, char *str, void *p); -STB_EXTERN int stb_sdict_count(stb_sdict *d); - -STB_EXTERN int stb_sdict_internal_limit(stb_sdict *d); -STB_EXTERN char * stb_sdict_internal_key(stb_sdict *d, int n); -STB_EXTERN void * stb_sdict_internal_value(stb_sdict *d, int n); - -#define stb_sdict_for(d,i,q,z) \ - for(i=0; i < stb_sdict_internal_limit(d) ? (q=stb_sdict_internal_key(d,i),z=stb_sdict_internal_value(d,i),1) : 0; ++i) \ - if (q==NULL||q==(void *) 1);else // reversed makes macro friendly - -#ifdef STB_DEFINE - -// if in same translation unit, for speed, don't call accessors -#undef stb_sdict_for -#define stb_sdict_for(d,i,q,z) \ - for(i=0; i < (d)->limit ? (q=(d)->table[i].k,z=(d)->table[i].v,1) : 0; ++i) \ - if (q==NULL||q==(void *) 1);else // reversed makes macro friendly - -#define STB_DEL ((void *) 1) -#define STB_SDEL ((char *) 1) - -#define stb_sdict__copy(x) \ - strcpy(a->arena ? stb_malloc_string(a->arena, strlen(x)+1) \ - : (char *) malloc(strlen(x)+1), x) - -#define stb_sdict__dispose(x) if (!a->arena) free(x) - -stb_define_hash_base(STB_noprefix, stb_sdict, void*arena; , stb_sdict_, stb_sdictinternal_, 0.85f, - char *, NULL, STB_SDEL, stb_sdict__copy, stb_sdict__dispose, - STB_safecompare, !strcmp, STB_equal, return stb_hash(k); , - void *, STB_nullvalue, NULL) - - int stb_sdict_count(stb_sdict *a) -{ - return a->count; -} - -int stb_sdict_internal_limit(stb_sdict *a) -{ - return a->limit; -} -char* stb_sdict_internal_key(stb_sdict *a, int n) -{ - return a->table[n].k; -} -void* stb_sdict_internal_value(stb_sdict *a, int n) -{ - return a->table[n].v; -} - -stb_sdict * stb_sdict_new(int use_arena) -{ - stb_sdict *d = stb_sdict_create(); - if (d == NULL) return NULL; - d->arena = use_arena ? stb_malloc_global(1) : NULL; - return d; -} - -stb_sdict* stb_sdict_copy(stb_sdict *old) -{ - stb_sdict *n; - void *old_arena = old->arena; - void *new_arena = old_arena ? stb_malloc_global(1) : NULL; - old->arena = new_arena; - n = stb_sdictinternal_copy(old); - old->arena = old_arena; - if (n) - n->arena = new_arena; - else if (new_arena) - stb_free(new_arena); - return n; -} - - -void stb_sdict_delete(stb_sdict *d) -{ - if (d->arena) - stb_free(d->arena); - stb_sdict_destroy(d); -} - -void * stb_sdict_change(stb_sdict *d, char *str, void *p) -{ - void *q = stb_sdict_get(d, str); - stb_sdict_set(d, str, p); - return q; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Instantiated data structures -// -// This is an attempt to implement a templated data structure. -// What you do is define a struct foo, and then include several -// pointer fields to struct foo in your struct. Then you call -// the instantiator, which creates the functions that implement -// the data structure. This requires massive undebuggable #defines, -// so we limit the cases where we do this. -// -// AA tree is an encoding of a 2-3 tree whereas RB trees encode a 2-3-4 tree; -// much simpler code due to fewer cases. - -#define stb__bst_parent(x) x -#define stb__bst_noparent(x) - -#define stb_bst_fields(N) \ - *STB_(N,left), *STB_(N,right); \ - unsigned char STB_(N,level) - -#define stb_bst_fields_parent(N) \ - *STB_(N,left), *STB_(N,right), *STB_(N,parent); \ - unsigned char STB_(N,level) - -#define STB__level(N,x) ((x) ? (x)->STB_(N,level) : 0) - -#define stb_bst_base(TYPE, N, TREE, M, compare, PAR) \ - \ -static int STB_(N,_compare)(TYPE *p, TYPE *q) \ -{ \ - compare \ -} \ - \ -static void STB_(N,setleft)(TYPE *q, TYPE *v) \ -{ \ - q->STB_(N,left) = v; \ - PAR(if (v) v->STB_(N,parent) = q;) \ -} \ - \ -static void STB_(N,setright)(TYPE *q, TYPE *v) \ -{ \ - q->STB_(N,right) = v; \ - PAR(if (v) v->STB_(N,parent) = q;) \ -} \ - \ -static TYPE *STB_(N,skew)(TYPE *q) \ -{ \ - if (q == NULL) return q; \ - if (q->STB_(N,left) \ - && q->STB_(N,left)->STB_(N,level) == q->STB_(N,level)) { \ - TYPE *p = q->STB_(N,left); \ - STB_(N,setleft)(q, p->STB_(N,right)); \ - STB_(N,setright)(p, q); \ - return p; \ - } \ - return q; \ -} \ - \ -static TYPE *STB_(N,split)(TYPE *p) \ -{ \ - TYPE *q = p->STB_(N,right); \ - if (q && q->STB_(N,right) \ - && q->STB_(N,right)->STB_(N,level) == p->STB_(N,level)) { \ - STB_(N,setright)(p, q->STB_(N,left)); \ - STB_(N,setleft)(q,p); \ - ++q->STB_(N,level); \ - return q; \ - } \ - return p; \ -} \ - \ -TYPE *STB__(N,insert)(TYPE *tree, TYPE *item) \ -{ \ - int c; \ - if (tree == NULL) { \ - item->STB_(N,left) = NULL; \ - item->STB_(N,right) = NULL; \ - item->STB_(N,level) = 1; \ - PAR(item->STB_(N,parent) = NULL;) \ - return item; \ - } \ - c = STB_(N,_compare)(item,tree); \ - if (c == 0) { \ - if (item != tree) { \ - STB_(N,setleft)(item, tree->STB_(N,left)); \ - STB_(N,setright)(item, tree->STB_(N,right)); \ - item->STB_(N,level) = tree->STB_(N,level); \ - PAR(item->STB_(N,parent) = NULL;) \ - } \ - return item; \ - } \ - if (c < 0) \ - STB_(N,setleft )(tree, STB__(N,insert)(tree->STB_(N,left), item)); \ - else \ - STB_(N,setright)(tree, STB__(N,insert)(tree->STB_(N,right), item)); \ - tree = STB_(N,skew)(tree); \ - tree = STB_(N,split)(tree); \ - PAR(tree->STB_(N,parent) = NULL;) \ - return tree; \ -} \ - \ -TYPE *STB__(N,remove)(TYPE *tree, TYPE *item) \ -{ \ - static TYPE *delnode, *leaf, *restore; \ - if (tree == NULL) return NULL; \ - leaf = tree; \ - if (STB_(N,_compare)(item, tree) < 0) { \ - STB_(N,setleft)(tree, STB__(N,remove)(tree->STB_(N,left), item)); \ - } else { \ - TYPE *r; \ - delnode = tree; \ - r = STB__(N,remove)(tree->STB_(N,right), item); \ - /* maybe move 'leaf' up to this location */ \ - if (restore == tree) { tree = leaf; leaf = restore = NULL; } \ - STB_(N,setright)(tree,r); \ - assert(tree->STB_(N,right) != tree); \ - } \ - if (tree == leaf) { \ - if (delnode == item) { \ - tree = tree->STB_(N,right); \ - assert(leaf->STB_(N,left) == NULL); \ - /* move leaf (the right sibling) up to delnode */ \ - STB_(N,setleft )(leaf, item->STB_(N,left )); \ - STB_(N,setright)(leaf, item->STB_(N,right)); \ - leaf->STB_(N,level) = item->STB_(N,level); \ - if (leaf != item) \ - restore = delnode; \ - } \ - delnode = NULL; \ - } else { \ - if (STB__level(N,tree->STB_(N,left) ) < tree->STB_(N,level)-1 || \ - STB__level(N,tree->STB_(N,right)) < tree->STB_(N,level)-1) { \ - --tree->STB_(N,level); \ - if (STB__level(N,tree->STB_(N,right)) > tree->STB_(N,level)) \ - tree->STB_(N,right)->STB_(N,level) = tree->STB_(N,level); \ - tree = STB_(N,skew)(tree); \ - STB_(N,setright)(tree, STB_(N,skew)(tree->STB_(N,right))); \ - if (tree->STB_(N,right)) \ - STB_(N,setright)(tree->STB_(N,right), \ - STB_(N,skew)(tree->STB_(N,right)->STB_(N,right))); \ - tree = STB_(N,split)(tree); \ - if (tree->STB_(N,right)) \ - STB_(N,setright)(tree, STB_(N,split)(tree->STB_(N,right))); \ - } \ - } \ - PAR(if (tree) tree->STB_(N,parent) = NULL;) \ - return tree; \ -} \ - \ -TYPE *STB__(N,last)(TYPE *tree) \ -{ \ - if (tree) \ - while (tree->STB_(N,right)) tree = tree->STB_(N,right); \ - return tree; \ -} \ - \ -TYPE *STB__(N,first)(TYPE *tree) \ -{ \ - if (tree) \ - while (tree->STB_(N,left)) tree = tree->STB_(N,left); \ - return tree; \ -} \ - \ -TYPE *STB__(N,next)(TYPE *tree, TYPE *item) \ -{ \ - TYPE *next = NULL; \ - if (item->STB_(N,right)) \ - return STB__(N,first)(item->STB_(N,right)); \ - PAR( \ - while(item->STB_(N,parent)) { \ - TYPE *up = item->STB_(N,parent); \ - if (up->STB_(N,left) == item) return up; \ - item = up; \ - } \ - return NULL; \ - ) \ - while (tree != item) { \ - if (STB_(N,_compare)(item, tree) < 0) { \ - next = tree; \ - tree = tree->STB_(N,left); \ - } else { \ - tree = tree->STB_(N,right); \ - } \ - } \ - return next; \ -} \ - \ -TYPE *STB__(N,prev)(TYPE *tree, TYPE *item) \ -{ \ - TYPE *next = NULL; \ - if (item->STB_(N,left)) \ - return STB__(N,last)(item->STB_(N,left)); \ - PAR( \ - while(item->STB_(N,parent)) { \ - TYPE *up = item->STB_(N,parent); \ - if (up->STB_(N,right) == item) return up; \ - item = up; \ - } \ - return NULL; \ - ) \ - while (tree != item) { \ - if (STB_(N,_compare)(item, tree) < 0) { \ - tree = tree->STB_(N,left); \ - } else { \ - next = tree; \ - tree = tree->STB_(N,right); \ - } \ - } \ - return next; \ -} \ - \ -STB__DEBUG( \ - void STB__(N,_validate)(TYPE *tree, int root) \ - { \ - if (tree == NULL) return; \ - PAR(if(root) assert(tree->STB_(N,parent) == NULL);) \ - assert(STB__level(N,tree->STB_(N,left) ) == tree->STB_(N,level)-1); \ - assert(STB__level(N,tree->STB_(N,right)) <= tree->STB_(N,level)); \ - assert(STB__level(N,tree->STB_(N,right)) >= tree->STB_(N,level)-1); \ - if (tree->STB_(N,right)) { \ - assert(STB__level(N,tree->STB_(N,right)->STB_(N,right)) \ - != tree->STB_(N,level)); \ - PAR(assert(tree->STB_(N,right)->STB_(N,parent) == tree);) \ - } \ - PAR(if(tree->STB_(N,left)) assert(tree->STB_(N,left)->STB_(N,parent) == tree);) \ - STB__(N,_validate)(tree->STB_(N,left) ,0); \ - STB__(N,_validate)(tree->STB_(N,right),0); \ - } \ -) \ - \ -typedef struct \ -{ \ - TYPE *root; \ -} TREE; \ - \ -void STB__(M,Insert)(TREE *tree, TYPE *item) \ -{ tree->root = STB__(N,insert)(tree->root, item); } \ -void STB__(M,Remove)(TREE *tree, TYPE *item) \ -{ tree->root = STB__(N,remove)(tree->root, item); } \ -TYPE *STB__(M,Next)(TREE *tree, TYPE *item) \ -{ return STB__(N,next)(tree->root, item); } \ -TYPE *STB__(M,Prev)(TREE *tree, TYPE *item) \ -{ return STB__(N,prev)(tree->root, item); } \ -TYPE *STB__(M,First)(TREE *tree) { return STB__(N,first)(tree->root); } \ -TYPE *STB__(M,Last) (TREE *tree) { return STB__(N,last) (tree->root); } \ -void STB__(M,Init)(TREE *tree) { tree->root = NULL; } - - -#define stb_bst_find(N,tree,fcompare) \ -{ \ - int c; \ - while (tree != NULL) { \ - fcompare \ - if (c == 0) return tree; \ - if (c < 0) tree = tree->STB_(N,left); \ - else tree = tree->STB_(N,right); \ - } \ - return NULL; \ -} - -#define stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,PAR) \ - stb_bst_base(TYPE,N,TREE,M, \ - VTYPE a = p->vfield; VTYPE b = q->vfield; return (compare);, PAR ) \ - \ -TYPE *STB__(N,find)(TYPE *tree, VTYPE a) \ - stb_bst_find(N,tree,VTYPE b = tree->vfield; c = (compare);) \ -TYPE *STB__(M,Find)(TREE *tree, VTYPE a) \ -{ return STB__(N,find)(tree->root, a); } - -#define stb_bst(TYPE,N,TREE,M,vfield,VTYPE,compare) \ - stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_noparent) -#define stb_bst_parent(TYPE,N,TREE,M,vfield,VTYPE,compare) \ - stb_bst_raw(TYPE,N,TREE,M,vfield,VTYPE,compare,stb__bst_parent) - - - -////////////////////////////////////////////////////////////////////////////// -// -// Pointer Nulling -// -// This lets you automatically NULL dangling pointers to "registered" -// objects. Note that you have to make sure you call the appropriate -// functions when you free or realloc blocks of memory that contain -// pointers or pointer targets. stb.h can automatically do this for -// stb_arr, or for all frees/reallocs if it's wrapping them. -// - -#ifdef STB_NPTR - -STB_EXTERN void stb_nptr_set(void *address_of_pointer, void *value_to_write); -STB_EXTERN void stb_nptr_didset(void *address_of_pointer); - -STB_EXTERN void stb_nptr_didfree(void *address_being_freed, int len); -STB_EXTERN void stb_nptr_free(void *address_being_freed, int len); - -STB_EXTERN void stb_nptr_didrealloc(void *new_address, void *old_address, int len); -STB_EXTERN void stb_nptr_recache(void); // recache all known pointers - // do this after pointer sets outside your control, slow - -#ifdef STB_DEFINE - // for fast updating on free/realloc, we need to be able to find - // all the objects (pointers and targets) within a given block; - // this precludes hashing - - // we use a three-level hierarchy of memory to minimize storage: - // level 1: 65536 pointers to stb__memory_node (always uses 256 KB) - // level 2: each stb__memory_node represents a 64K block of memory - // with 256 stb__memory_leafs (worst case 64MB) - // level 3: each stb__memory_leaf represents 256 bytes of memory - // using a list of target locations and a list of pointers - // (which are hopefully fairly short normally!) - - // this approach won't work in 64-bit, which has a much larger address - // space. need to redesign - -#define STB__NPTR_ROOT_LOG2 16 -#define STB__NPTR_ROOT_NUM (1 << STB__NPTR_ROOT_LOG2) -#define STB__NPTR_ROOT_SHIFT (32 - STB__NPTR_ROOT_LOG2) - -#define STB__NPTR_NODE_LOG2 5 -#define STB__NPTR_NODE_NUM (1 << STB__NPTR_NODE_LOG2) -#define STB__NPTR_NODE_MASK (STB__NPTR_NODE_NUM-1) -#define STB__NPTR_NODE_SHIFT (STB__NPTR_ROOT_SHIFT - STB__NPTR_NODE_LOG2) -#define STB__NPTR_NODE_OFFSET(x) (((x) >> STB__NPTR_NODE_SHIFT) & STB__NPTR_NODE_MASK) - -typedef struct stb__st_nptr -{ - void *ptr; // address of actual pointer - struct stb__st_nptr *next; // next pointer with same target - struct stb__st_nptr **prev; // prev pointer with same target, address of 'next' field (or first) - struct stb__st_nptr *next_in_block; -} stb__nptr; - -typedef struct stb__st_nptr_target -{ - void *ptr; // address of target - stb__nptr *first; // address of first nptr pointing to this - struct stb__st_nptr_target *next_in_block; -} stb__nptr_target; - -typedef struct -{ - stb__nptr *pointers; - stb__nptr_target *targets; -} stb__memory_leaf; - -typedef struct -{ - stb__memory_leaf *children[STB__NPTR_NODE_NUM]; -} stb__memory_node; - -stb__memory_node *stb__memtab_root[STB__NPTR_ROOT_NUM]; - -static stb__memory_leaf *stb__nptr_find_leaf(void *mem) -{ - stb_uint32 address = (stb_uint32)mem; - stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT]; - if (z) - return z->children[STB__NPTR_NODE_OFFSET(address)]; - else - return NULL; -} - -static void * stb__nptr_alloc(int size) -{ - return stb__realloc_raw(0, size); -} - -static void stb__nptr_free(void *p) -{ - stb__realloc_raw(p, 0); -} - -static stb__memory_leaf *stb__nptr_make_leaf(void *mem) -{ - stb_uint32 address = (stb_uint32)mem; - stb__memory_node *z = stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT]; - stb__memory_leaf *f; - if (!z) { - int i; - z = (stb__memory_node *)stb__nptr_alloc(sizeof(*stb__memtab_root[0])); - stb__memtab_root[address >> STB__NPTR_ROOT_SHIFT] = z; - for (i = 0; i < 256; ++i) - z->children[i] = 0; - } - f = (stb__memory_leaf *)stb__nptr_alloc(sizeof(*f)); - z->children[STB__NPTR_NODE_OFFSET(address)] = f; - f->pointers = NULL; - f->targets = NULL; - return f; -} - -static stb__nptr_target *stb__nptr_find_target(void *target, int force) -{ - stb__memory_leaf *p = stb__nptr_find_leaf(target); - if (p) { - stb__nptr_target *t = p->targets; - while (t) { - if (t->ptr == target) - return t; - t = t->next_in_block; - } - } - if (force) { - stb__nptr_target *t = (stb__nptr_target*)stb__nptr_alloc(sizeof(*t)); - if (!p) p = stb__nptr_make_leaf(target); - t->ptr = target; - t->first = NULL; - t->next_in_block = p->targets; - p->targets = t; - return t; - } - else - return NULL; -} - -static stb__nptr *stb__nptr_find_pointer(void *ptr, int force) -{ - stb__memory_leaf *p = stb__nptr_find_leaf(ptr); - if (p) { - stb__nptr *t = p->pointers; - while (t) { - if (t->ptr == ptr) - return t; - t = t->next_in_block; - } - } - if (force) { - stb__nptr *t = (stb__nptr *)stb__nptr_alloc(sizeof(*t)); - if (!p) p = stb__nptr_make_leaf(ptr); - t->ptr = ptr; - t->next = NULL; - t->prev = NULL; - t->next_in_block = p->pointers; - p->pointers = t; - return t; - } - else - return NULL; -} - -void stb_nptr_set(void *address_of_pointer, void *value_to_write) -{ - if (*(void **)address_of_pointer != value_to_write) { - *(void **)address_of_pointer = value_to_write; - stb_nptr_didset(address_of_pointer); - } -} - -void stb_nptr_didset(void *address_of_pointer) -{ - // first unlink from old chain - void *new_address; - stb__nptr *p = stb__nptr_find_pointer(address_of_pointer, 1); // force building if doesn't exist - if (p->prev) { // if p->prev is NULL, we just built it, or it was NULL - *(p->prev) = p->next; - if (p->next) p->next->prev = p->prev; - } - // now add to new chain - new_address = *(void **)address_of_pointer; - if (new_address != NULL) { - stb__nptr_target *t = stb__nptr_find_target(new_address, 1); - p->next = t->first; - if (p->next) p->next->prev = &p->next; - p->prev = &t->first; - t->first = p; - } - else { - p->prev = NULL; - p->next = NULL; - } -} - -void stb__nptr_block(void *address, int len, void(*function)(stb__memory_leaf *f, int datum, void *start, void *end), int datum) -{ - void *end_address = (void *)((char *)address + len - 1); - stb__memory_node *n; - stb_uint32 start = (stb_uint32)address; - stb_uint32 end = start + len - 1; - - int b0 = start >> STB__NPTR_ROOT_SHIFT; - int b1 = end >> STB__NPTR_ROOT_SHIFT; - int b = b0, i, e0, e1; - - e0 = STB__NPTR_NODE_OFFSET(start); - - if (datum <= 0) { - // first block - n = stb__memtab_root[b0]; - if (n) { - if (b0 != b1) - e1 = STB__NPTR_NODE_NUM - 1; - else - e1 = STB__NPTR_NODE_OFFSET(end); - for (i = e0; i <= e1; ++i) - if (n->children[i]) - function(n->children[i], datum, address, end_address); - } - if (b1 > b0) { - // blocks other than the first and last block - for (b = b0 + 1; b < b1; ++b) { - n = stb__memtab_root[b]; - if (n) - for (i = 0; i <= STB__NPTR_NODE_NUM - 1; ++i) - if (n->children[i]) - function(n->children[i], datum, address, end_address); - } - // last block - n = stb__memtab_root[b1]; - if (n) { - e1 = STB__NPTR_NODE_OFFSET(end); - for (i = 0; i <= e1; ++i) - if (n->children[i]) - function(n->children[i], datum, address, end_address); - } - } - } - else { - if (b1 > b0) { - // last block - n = stb__memtab_root[b1]; - if (n) { - e1 = STB__NPTR_NODE_OFFSET(end); - for (i = e1; i >= 0; --i) - if (n->children[i]) - function(n->children[i], datum, address, end_address); - } - // blocks other than the first and last block - for (b = b1 - 1; b > b0; --b) { - n = stb__memtab_root[b]; - if (n) - for (i = STB__NPTR_NODE_NUM - 1; i >= 0; --i) - if (n->children[i]) - function(n->children[i], datum, address, end_address); - } - } - // first block - n = stb__memtab_root[b0]; - if (n) { - if (b0 != b1) - e1 = STB__NPTR_NODE_NUM - 1; - else - e1 = STB__NPTR_NODE_OFFSET(end); - for (i = e1; i >= e0; --i) - if (n->children[i]) - function(n->children[i], datum, address, end_address); - } - } -} - -static void stb__nptr_delete_pointers(stb__memory_leaf *f, int offset, void *start, void *end) -{ - stb__nptr **p = &f->pointers; - while (*p) { - stb__nptr *n = *p; - if (n->ptr >= start && n->ptr <= end) { - // unlink - if (n->prev) { - *(n->prev) = n->next; - if (n->next) n->next->prev = n->prev; - } - *p = n->next_in_block; - stb__nptr_free(n); - } - else - p = &(n->next_in_block); - } -} - -static void stb__nptr_delete_targets(stb__memory_leaf *f, int offset, void *start, void *end) -{ - stb__nptr_target **p = &f->targets; - while (*p) { - stb__nptr_target *n = *p; - if (n->ptr >= start && n->ptr <= end) { - // null pointers - stb__nptr *z = n->first; - while (z) { - stb__nptr *y = z->next; - z->prev = NULL; - z->next = NULL; - *(void **)z->ptr = NULL; - z = y; - } - // unlink this target - *p = n->next_in_block; - stb__nptr_free(n); - } - else - p = &(n->next_in_block); - } -} - -void stb_nptr_didfree(void *address_being_freed, int len) -{ - // step one: delete all pointers in this block - stb__nptr_block(address_being_freed, len, stb__nptr_delete_pointers, 0); - // step two: NULL all pointers to this block; do this second to avoid NULLing deleted pointers - stb__nptr_block(address_being_freed, len, stb__nptr_delete_targets, 0); -} - -void stb_nptr_free(void *address_being_freed, int len) -{ - free(address_being_freed); - stb_nptr_didfree(address_being_freed, len); -} - -static void stb__nptr_move_targets(stb__memory_leaf *f, int offset, void *start, void *end) -{ - stb__nptr_target **t = &f->targets; - while (*t) { - stb__nptr_target *n = *t; - if (n->ptr >= start && n->ptr <= end) { - stb__nptr *z; - stb__memory_leaf *f; - // unlink n - *t = n->next_in_block; - // update n to new address - n->ptr = (void *)((char *)n->ptr + offset); - f = stb__nptr_find_leaf(n->ptr); - if (!f) f = stb__nptr_make_leaf(n->ptr); - n->next_in_block = f->targets; - f->targets = n; - // now go through all pointers and make them point here - z = n->first; - while (z) { - *(void**)z->ptr = n->ptr; - z = z->next; - } - } - else - t = &(n->next_in_block); - } -} - -static void stb__nptr_move_pointers(stb__memory_leaf *f, int offset, void *start, void *end) -{ - stb__nptr **p = &f->pointers; - while (*p) { - stb__nptr *n = *p; - if (n->ptr >= start && n->ptr <= end) { - // unlink - *p = n->next_in_block; - n->ptr = (void *)((int)n->ptr + offset); - // move to new block - f = stb__nptr_find_leaf(n->ptr); - if (!f) f = stb__nptr_make_leaf(n->ptr); - n->next_in_block = f->pointers; - f->pointers = n; - } - else - p = &(n->next_in_block); - } -} - -void stb_nptr_realloc(void *new_address, void *old_address, int len) -{ - if (new_address == old_address) return; - - // have to move the pointers first, because moving the targets - // requires writing to the pointers-to-the-targets, and if some of those moved too, - // we need to make sure we don't write to the old memory - - // step one: move all pointers within the block - stb__nptr_block(old_address, len, stb__nptr_move_pointers, (char *)new_address - (char *)old_address); - // step two: move all targets within the block - stb__nptr_block(old_address, len, stb__nptr_move_targets, (char *)new_address - (char *)old_address); -} - -void stb_nptr_move(void *new_address, void *old_address) -{ - stb_nptr_realloc(new_address, old_address, 1); -} - -void stb_nptr_recache(void) -{ - int i, j; - for (i = 0; i < STB__NPTR_ROOT_NUM; ++i) - if (stb__memtab_root[i]) - for (j = 0; j < STB__NPTR_NODE_NUM; ++j) - if (stb__memtab_root[i]->children[j]) { - stb__nptr *p = stb__memtab_root[i]->children[j]->pointers; - while (p) { - stb_nptr_didset(p->ptr); - p = p->next_in_block; - } - } -} - -#endif // STB_DEFINE -#endif // STB_NPTR - - -////////////////////////////////////////////////////////////////////////////// -// -// File Processing -// - - -#ifdef _MSC_VER -#define stb_rename(x,y) _wrename((const wchar_t *)stb__from_utf8(x), (const wchar_t *)stb__from_utf8_alt(y)) -#define stb_mktemp _mktemp -#else -#define stb_mktemp mktemp -#define stb_rename rename -#endif - -STB_EXTERN void stb_fput_varlen64(FILE *f, stb_uint64 v); -STB_EXTERN stb_uint64 stb_fget_varlen64(FILE *f); -STB_EXTERN int stb_size_varlen64(stb_uint64 v); - - -#define stb_filec (char *) stb_file -#define stb_fileu (unsigned char *) stb_file -STB_EXTERN void * stb_file(char *filename, size_t *length); -STB_EXTERN void * stb_file_max(char *filename, size_t *length); -STB_EXTERN size_t stb_filelen(FILE *f); -STB_EXTERN int stb_filewrite(char *filename, void *data, size_t length); -STB_EXTERN int stb_filewritestr(char *filename, char *data); -STB_EXTERN char ** stb_stringfile(char *filename, int *len); -STB_EXTERN char ** stb_stringfile_trimmed(char *name, int *len, char comm); -STB_EXTERN char * stb_fgets(char *buffer, int buflen, FILE *f); -STB_EXTERN char * stb_fgets_malloc(FILE *f); -STB_EXTERN int stb_fexists(char *filename); -STB_EXTERN int stb_fcmp(char *s1, char *s2); -STB_EXTERN int stb_feq(char *s1, char *s2); -STB_EXTERN time_t stb_ftimestamp(char *filename); - -STB_EXTERN int stb_fullpath(char *abs, int abs_size, char *rel); -STB_EXTERN FILE * stb_fopen(char *filename, char *mode); -STB_EXTERN int stb_fclose(FILE *f, int keep); - -enum -{ - stb_keep_no = 0, - stb_keep_yes = 1, - stb_keep_if_different = 2, -}; - -STB_EXTERN int stb_copyfile(char *src, char *dest); - -STB_EXTERN void stb_fput_varlen64(FILE *f, stb_uint64 v); -STB_EXTERN stb_uint64 stb_fget_varlen64(FILE *f); -STB_EXTERN int stb_size_varlen64(stb_uint64 v); - -STB_EXTERN void stb_fwrite32(FILE *f, stb_uint32 datum); -STB_EXTERN void stb_fput_varlen(FILE *f, int v); -STB_EXTERN void stb_fput_varlenu(FILE *f, unsigned int v); -STB_EXTERN int stb_fget_varlen(FILE *f); -STB_EXTERN stb_uint stb_fget_varlenu(FILE *f); -STB_EXTERN void stb_fput_ranged(FILE *f, int v, int b, stb_uint n); -STB_EXTERN int stb_fget_ranged(FILE *f, int b, stb_uint n); -STB_EXTERN int stb_size_varlen(int v); -STB_EXTERN int stb_size_varlenu(unsigned int v); -STB_EXTERN int stb_size_ranged(int b, stb_uint n); - -STB_EXTERN int stb_fread(void *data, size_t len, size_t count, void *f); -STB_EXTERN int stb_fwrite(void *data, size_t len, size_t count, void *f); - -#if 0 -typedef struct -{ - FILE *base_file; - char *buffer; - int buffer_size; - int buffer_off; - int buffer_left; -} STBF; - -STB_EXTERN STBF *stb_tfopen(char *filename, char *mode); -STB_EXTERN int stb_tfread(void *data, size_t len, size_t count, STBF *f); -STB_EXTERN int stb_tfwrite(void *data, size_t len, size_t count, STBF *f); -#endif - -#ifdef STB_DEFINE - -#if 0 -STBF *stb_tfopen(char *filename, char *mode) -{ - STBF *z; - FILE *f = fopen(filename, mode); - if (!f) return NULL; - z = (STBF *)malloc(sizeof(*z)); - if (!z) { fclose(f); return NULL; } - z->base_file = f; - if (!strcmp(mode, "rb") || !strcmp(mode, "wb")) { - z->buffer_size = 4096; - z->buffer_off = z->buffer_size; - z->buffer_left = 0; - z->buffer = malloc(z->buffer_size); - if (!z->buffer) { free(z); fclose(f); return NULL; } - } - else { - z->buffer = 0; - z->buffer_size = 0; - z->buffer_left = 0; - } - return z; -} - -int stb_tfread(void *data, size_t len, size_t count, STBF *f) -{ - int total = len*count, done = 0; - if (!total) return 0; - if (total <= z->buffer_left) { - memcpy(data, z->buffer + z->buffer_off, total); - z->buffer_off += total; - z->buffer_left -= total; - return count; - } - else { - char *out = (char *)data; - - // consume all buffered data - memcpy(data, z->buffer + z->buffer_off, z->buffer_left); - done = z->buffer_left; - out += z->buffer_left; - z->buffer_left = 0; - - if (total - done > (z->buffer_size >> 1)) { - done += fread(out - } - } -} -#endif - -void stb_fwrite32(FILE *f, stb_uint32 x) -{ - fwrite(&x, 4, 1, f); -} - -#if defined(_MSC_VER) || defined(__MINGW32__) -#define stb__stat _stat -#else -#define stb__stat stat -#endif - -int stb_fexists(char *filename) -{ - struct stb__stat buf; - return stb__windows( - _wstat((const wchar_t *)stb__from_utf8(filename), &buf), - stat(filename, &buf) - ) == 0; -} - -time_t stb_ftimestamp(char *filename) -{ - struct stb__stat buf; - if (stb__windows( - _wstat((const wchar_t *)stb__from_utf8(filename), &buf), - stat(filename, &buf) - ) == 0) - { - return buf.st_mtime; - } - else { - return 0; - } -} - -size_t stb_filelen(FILE *f) -{ - size_t len, pos; - pos = ftell(f); - fseek(f, 0, SEEK_END); - len = ftell(f); - fseek(f, pos, SEEK_SET); - return len; -} - -void *stb_file(char *filename, size_t *length) -{ - FILE *f = stb__fopen(filename, "rb"); - char *buffer; - size_t len, len2; - if (!f) return NULL; - len = stb_filelen(f); - buffer = (char *)malloc(len + 2); // nul + extra - len2 = fread(buffer, 1, len, f); - if (len2 == len) { - if (length) *length = len; - buffer[len] = 0; - } - else { - free(buffer); - buffer = NULL; - } - fclose(f); - return buffer; -} - -int stb_filewrite(char *filename, void *data, size_t length) -{ - FILE *f = stb_fopen(filename, "wb"); - if (f) { - unsigned char *data_ptr = (unsigned char *)data; - size_t remaining = length; - while (remaining > 0) { - size_t len2 = remaining > 65536 ? 65536 : remaining; - size_t len3 = fwrite(data_ptr, 1, len2, f); - if (len2 != len3) { - fprintf(stderr, "Failed while writing %s\n", filename); - break; - } - remaining -= len2; - data_ptr += len2; - } - stb_fclose(f, stb_keep_if_different); - } - return f != NULL; -} - -int stb_filewritestr(char *filename, char *data) -{ - return stb_filewrite(filename, data, strlen(data)); -} - -void * stb_file_max(char *filename, size_t *length) -{ - FILE *f = stb__fopen(filename, "rb"); - char *buffer; - size_t len, maxlen; - if (!f) return NULL; - maxlen = *length; - buffer = (char *)malloc(maxlen + 1); - len = fread(buffer, 1, maxlen, f); - buffer[len] = 0; - fclose(f); - *length = len; - return buffer; -} - -char ** stb_stringfile(char *filename, int *plen) -{ - FILE *f = stb__fopen(filename, "rb"); - char *buffer, **list = NULL, *s; - size_t len, count, i; - - if (!f) return NULL; - len = stb_filelen(f); - buffer = (char *)malloc(len + 1); - len = fread(buffer, 1, len, f); - buffer[len] = 0; - fclose(f); - - // two passes through: first time count lines, second time set them - for (i = 0; i < 2; ++i) { - s = buffer; - if (i == 1) - list[0] = s; - count = 1; - while (*s) { - if (*s == '\n' || *s == '\r') { - // detect if both cr & lf are together - int crlf = (s[0] + s[1]) == ('\n' + '\r'); - if (i == 1) *s = 0; - if (crlf) ++s; - if (s[1]) { // it's not over yet - if (i == 1) list[count] = s + 1; - ++count; - } - } - ++s; - } - if (i == 0) { - list = (char **)malloc(sizeof(*list) * (count + 1) + len + 1); - if (!list) return NULL; - list[count] = 0; - // recopy the file so there's just a single allocation to free - memcpy(&list[count + 1], buffer, len + 1); - free(buffer); - buffer = (char *)&list[count + 1]; - if (plen) *plen = count; - } - } - return list; -} - -char ** stb_stringfile_trimmed(char *name, int *len, char comment) -{ - int i, n, o = 0; - char **s = stb_stringfile(name, &n); - if (s == NULL) return NULL; - for (i = 0; i < n; ++i) { - char *p = stb_skipwhite(s[i]); - if (*p && *p != comment) - s[o++] = p; - } - s[o] = NULL; - if (len) *len = o; - return s; -} - -char * stb_fgets(char *buffer, int buflen, FILE *f) -{ - char *p; - buffer[0] = 0; - p = fgets(buffer, buflen, f); - if (p) { - int n = strlen(p) - 1; - if (n >= 0) - if (p[n] == '\n') - p[n] = 0; - } - return p; -} - -char * stb_fgets_malloc(FILE *f) -{ - // avoid reallocing for small strings - char quick_buffer[800]; - quick_buffer[sizeof(quick_buffer) - 2] = 0; - if (!fgets(quick_buffer, sizeof(quick_buffer), f)) - return NULL; - - if (quick_buffer[sizeof(quick_buffer) - 2] == 0) { - int n = strlen(quick_buffer); - if (n > 0 && quick_buffer[n - 1] == '\n') - quick_buffer[n - 1] = 0; - return strdup(quick_buffer); - } - else { - char *p; - char *a = strdup(quick_buffer); - int len = sizeof(quick_buffer) - 1; - - while (!feof(f)) { - if (a[len - 1] == '\n') break; - a = (char *)realloc(a, len * 2); - p = &a[len]; - p[len - 2] = 0; - if (!fgets(p, len, f)) - break; - if (p[len - 2] == 0) { - len += strlen(p); - break; - } - len = len + (len - 1); - } - if (a[len - 1] == '\n') - a[len - 1] = 0; - return a; - } -} - -int stb_fullpath(char *abs, int abs_size, char *rel) -{ -#ifdef _MSC_VER - return _fullpath(abs, rel, abs_size) != NULL; -#else - if (rel[0] == '/' || rel[0] == '~') { - if ((int)strlen(rel) >= abs_size) - return 0; - strcpy(abs, rel); - return STB_TRUE; - } - else { - int n; - getcwd(abs, abs_size); - n = strlen(abs); - if (n + (int)strlen(rel) + 2 <= abs_size) { - abs[n] = '/'; - strcpy(abs + n + 1, rel); - return STB_TRUE; - } - else { - return STB_FALSE; - } - } -#endif -} - -static int stb_fcmp_core(FILE *f, FILE *g) -{ - char buf1[1024], buf2[1024]; - int n1, n2, res = 0; - - while (1) { - n1 = fread(buf1, 1, sizeof(buf1), f); - n2 = fread(buf2, 1, sizeof(buf2), g); - res = memcmp(buf1, buf2, stb_min(n1, n2)); - if (res) - break; - if (n1 != n2) { - res = n1 < n2 ? -1 : 1; - break; - } - if (n1 == 0) - break; - } - - fclose(f); - fclose(g); - return res; -} - -int stb_fcmp(char *s1, char *s2) -{ - FILE *f = stb__fopen(s1, "rb"); - FILE *g = stb__fopen(s2, "rb"); - - if (f == NULL || g == NULL) { - if (f) fclose(f); - if (g) { - fclose(g); - return STB_TRUE; - } - return f != NULL; - } - - return stb_fcmp_core(f, g); -} - -int stb_feq(char *s1, char *s2) -{ - FILE *f = stb__fopen(s1, "rb"); - FILE *g = stb__fopen(s2, "rb"); - - if (f == NULL || g == NULL) { - if (f) fclose(f); - if (g) fclose(g); - return f == g; - } - - // feq is faster because it shortcuts if they're different length - if (stb_filelen(f) != stb_filelen(g)) { - fclose(f); - fclose(g); - return 0; - } - - return !stb_fcmp_core(f, g); -} - -static stb_ptrmap *stb__files; - -typedef struct -{ - char *temp_name; - char *name; - int errors; -} stb__file_data; - -static FILE *stb__open_temp_file(char *temp_name, char *src_name, char *mode) -{ - int p; -#ifdef _MSC_VER - int j; -#endif - FILE *f; - // try to generate a temporary file in the same directory - p = strlen(src_name) - 1; - while (p > 0 && src_name[p] != '/' && src_name[p] != '\\' - && src_name[p] != ':' && src_name[p] != '~') - --p; - ++p; - - memcpy(temp_name, src_name, p); - -#ifdef _MSC_VER - // try multiple times to make a temp file... just in - // case some other process makes the name first - for (j = 0; j < 32; ++j) { - strcpy(temp_name + p, "stmpXXXXXX"); - if (stb_mktemp(temp_name) == NULL) - return 0; - - f = fopen(temp_name, mode); - if (f != NULL) - break; - } -#else - { - strcpy(temp_name + p, "stmpXXXXXX"); -#ifdef __MINGW32__ - int fd = open(mktemp(temp_name), O_RDWR); -#else - int fd = mkstemp(temp_name); -#endif - if (fd == -1) return NULL; - f = fdopen(fd, mode); - if (f == NULL) { - unlink(temp_name); - close(fd); - return NULL; - } - } -#endif - return f; -} - - -FILE * stb_fopen(char *filename, char *mode) -{ - FILE *f; - char name_full[4096]; - char temp_full[sizeof(name_full) + 12]; - - // @TODO: if the file doesn't exist, we can also use the fastpath here - if (mode[0] != 'w' && !strchr(mode, '+')) - return stb__fopen(filename, mode); - - // save away the full path to the file so if the program - // changes the cwd everything still works right! unix has - // better ways to do this, but we have to work in windows - name_full[0] = '\0'; // stb_fullpath reads name_full[0] - if (stb_fullpath(name_full, sizeof(name_full), filename) == 0) - return 0; - - f = stb__open_temp_file(temp_full, name_full, mode); - if (f != NULL) { - stb__file_data *d = (stb__file_data *)malloc(sizeof(*d)); - if (!d) { assert(0); /* NOTREACHED */fclose(f); return NULL; } - if (stb__files == NULL) stb__files = stb_ptrmap_create(); - d->temp_name = strdup(temp_full); - d->name = strdup(name_full); - d->errors = 0; - stb_ptrmap_add(stb__files, f, d); - return f; - } - - return NULL; -} - -int stb_fclose(FILE *f, int keep) -{ - stb__file_data *d; - - int ok = STB_FALSE; - if (f == NULL) return 0; - - if (ferror(f)) - keep = stb_keep_no; - - fclose(f); - - if (stb__files && stb_ptrmap_remove(stb__files, f, (void **)&d)) { - if (stb__files->count == 0) { - stb_ptrmap_destroy(stb__files); - stb__files = NULL; - } - } - else - return STB_TRUE; // not special - - if (keep == stb_keep_if_different) { - // check if the files are identical - if (stb_feq(d->name, d->temp_name)) { - keep = stb_keep_no; - ok = STB_TRUE; // report success if no change - } - } - - if (keep == stb_keep_no) { - remove(d->temp_name); - } - else { - if (!stb_fexists(d->name)) { - // old file doesn't exist, so just move the new file over it - stb_rename(d->temp_name, d->name); - } - else { - // don't delete the old file yet in case there are troubles! First rename it! - char preserved_old_file[4096]; - - // generate a temp filename in the same directory (also creates it, which we don't need) - FILE *dummy = stb__open_temp_file(preserved_old_file, d->name, "wb"); - if (dummy != NULL) { - // we don't actually want the open file - fclose(dummy); - - // discard what we just created - remove(preserved_old_file); // if this fails, there's nothing we can do, and following logic handles it as best as possible anyway - - // move the existing file to the preserved name - if (0 != stb_rename(d->name, preserved_old_file)) { // 0 on success - // failed, state is: - // filename -> old file - // tempname -> new file - // keep tempname around so we don't lose data - } - else { - // state is: - // preserved -> old file - // tempname -> new file - // move the new file to the old name - if (0 == stb_rename(d->temp_name, d->name)) { - // state is: - // preserved -> old file - // filename -> new file - ok = STB_TRUE; - - // 'filename -> new file' has always been the goal, so clean up - remove(preserved_old_file); // nothing to be done if it fails - } - else { - // couldn't rename, so try renaming preserved file back - - // state is: - // preserved -> old file - // tempname -> new file - stb_rename(preserved_old_file, d->name); - // if the rename failed, there's nothing more we can do - } - } - } - else { - // we couldn't get a temp filename. do this the naive way; the worst case failure here - // leaves the filename pointing to nothing and the new file as a tempfile - remove(d->name); - stb_rename(d->temp_name, d->name); - } - } - } - - free(d->temp_name); - free(d->name); - free(d); - - return ok; -} - -int stb_copyfile(char *src, char *dest) -{ - char raw_buffer[1024]; - char *buffer; - int buf_size = 65536; - - FILE *f, *g; - - // if file already exists at destination, do nothing - if (stb_feq(src, dest)) return STB_TRUE; - - // open file - f = stb__fopen(src, "rb"); - if (f == NULL) return STB_FALSE; - - // open file for writing - g = stb__fopen(dest, "wb"); - if (g == NULL) { - fclose(f); - return STB_FALSE; - } - - buffer = (char *)malloc(buf_size); - if (buffer == NULL) { - buffer = raw_buffer; - buf_size = sizeof(raw_buffer); - } - - while (!feof(f)) { - int n = fread(buffer, 1, buf_size, f); - if (n != 0) - fwrite(buffer, 1, n, g); - } - - fclose(f); - if (buffer != raw_buffer) - free(buffer); - - fclose(g); - return STB_TRUE; -} - -// varlen: -// v' = (v >> 31) + (v < 0 ? ~v : v)<<1; // small abs(v) => small v' -// output v as big endian v'+k for v' <= k: -// 1 byte : v' <= 0x00000080 ( -64 <= v < 64) 7 bits -// 2 bytes: v' <= 0x00004000 (-8192 <= v < 8192) 14 bits -// 3 bytes: v' <= 0x00200000 21 bits -// 4 bytes: v' <= 0x10000000 28 bits -// the number of most significant 1-bits in the first byte -// equals the number of bytes after the first - -#define stb__varlen_xform(v) (v<0 ? (~v << 1)+1 : (v << 1)) - -int stb_size_varlen(int v) { return stb_size_varlenu(stb__varlen_xform(v)); } -int stb_size_varlenu(unsigned int v) -{ - if (v < 0x00000080) return 1; - if (v < 0x00004000) return 2; - if (v < 0x00200000) return 3; - if (v < 0x10000000) return 4; - return 5; -} - -void stb_fput_varlen(FILE *f, int v) { stb_fput_varlenu(f, stb__varlen_xform(v)); } - -void stb_fput_varlenu(FILE *f, unsigned int z) -{ - if (z >= 0x10000000) fputc(0xF0, f); - if (z >= 0x00200000) fputc((z < 0x10000000 ? 0xE0 : 0) + (z >> 24), f); - if (z >= 0x00004000) fputc((z < 0x00200000 ? 0xC0 : 0) + (z >> 16), f); - if (z >= 0x00000080) fputc((z < 0x00004000 ? 0x80 : 0) + (z >> 8), f); - fputc(z, f); -} - -#define stb_fgetc(f) ((unsigned char) fgetc(f)) - -int stb_fget_varlen(FILE *f) -{ - unsigned int z = stb_fget_varlenu(f); - return (z & 1) ? ~(z >> 1) : (z >> 1); -} - -unsigned int stb_fget_varlenu(FILE *f) -{ - unsigned int z; - unsigned char d; - d = stb_fgetc(f); - - if (d >= 0x80) { - if (d >= 0xc0) { - if (d >= 0xe0) { - if (d == 0xf0) z = stb_fgetc(f) << 24; - else z = (d - 0xe0) << 24; - z += stb_fgetc(f) << 16; - } - else - z = (d - 0xc0) << 16; - z += stb_fgetc(f) << 8; - } - else - z = (d - 0x80) << 8; - z += stb_fgetc(f); - } - else - z = d; - return z; -} - -stb_uint64 stb_fget_varlen64(FILE *f) -{ - stb_uint64 z; - unsigned char d; - d = stb_fgetc(f); - - if (d >= 0x80) { - if (d >= 0xc0) { - if (d >= 0xe0) { - if (d >= 0xf0) { - if (d >= 0xf8) { - if (d >= 0xfc) { - if (d >= 0xfe) { - if (d >= 0xff) - z = (stb_uint64)stb_fgetc(f) << 56; - else - z = (stb_uint64)(d - 0xfe) << 56; - z |= (stb_uint64)stb_fgetc(f) << 48; - } - else z = (stb_uint64)(d - 0xfc) << 48; - z |= (stb_uint64)stb_fgetc(f) << 40; - } - else z = (stb_uint64)(d - 0xf8) << 40; - z |= (stb_uint64)stb_fgetc(f) << 32; - } - else z = (stb_uint64)(d - 0xf0) << 32; - z |= (stb_uint)stb_fgetc(f) << 24; - } - else z = (stb_uint)(d - 0xe0) << 24; - z |= (stb_uint)stb_fgetc(f) << 16; - } - else z = (stb_uint)(d - 0xc0) << 16; - z |= (stb_uint)stb_fgetc(f) << 8; - } - else z = (stb_uint)(d - 0x80) << 8; - z |= stb_fgetc(f); - } - else - z = d; - - return (z & 1) ? ~(z >> 1) : (z >> 1); -} - -int stb_size_varlen64(stb_uint64 v) -{ - if (v < 0x00000080) return 1; - if (v < 0x00004000) return 2; - if (v < 0x00200000) return 3; - if (v < 0x10000000) return 4; - if (v < STB_IMM_UINT64(0x0000000800000000)) return 5; - if (v < STB_IMM_UINT64(0x0000040000000000)) return 6; - if (v < STB_IMM_UINT64(0x0002000000000000)) return 7; - if (v < STB_IMM_UINT64(0x0100000000000000)) return 8; - return 9; -} - -void stb_fput_varlen64(FILE *f, stb_uint64 v) -{ - stb_uint64 z = stb__varlen_xform(v); - int first = 1; - if (z >= STB_IMM_UINT64(0x100000000000000)) { - fputc(0xff, f); - first = 0; - } - if (z >= STB_IMM_UINT64(0x02000000000000)) fputc((first ? 0xFE : 0) + (char)(z >> 56), f), first = 0; - if (z >= STB_IMM_UINT64(0x00040000000000)) fputc((first ? 0xFC : 0) + (char)(z >> 48), f), first = 0; - if (z >= STB_IMM_UINT64(0x00000800000000)) fputc((first ? 0xF8 : 0) + (char)(z >> 40), f), first = 0; - if (z >= STB_IMM_UINT64(0x00000010000000)) fputc((first ? 0xF0 : 0) + (char)(z >> 32), f), first = 0; - if (z >= STB_IMM_UINT64(0x00000000200000)) fputc((first ? 0xE0 : 0) + (char)(z >> 24), f), first = 0; - if (z >= STB_IMM_UINT64(0x00000000004000)) fputc((first ? 0xC0 : 0) + (char)(z >> 16), f), first = 0; - if (z >= STB_IMM_UINT64(0x00000000000080)) fputc((first ? 0x80 : 0) + (char)(z >> 8), f), first = 0; - fputc((char)z, f); -} - -void stb_fput_ranged(FILE *f, int v, int b, stb_uint n) -{ - v -= b; - if (n <= (1 << 31)) - assert((stb_uint)v < n); - if (n >(1 << 24)) fputc(v >> 24, f); - if (n > (1 << 16)) fputc(v >> 16, f); - if (n > (1 << 8)) fputc(v >> 8, f); - fputc(v, f); -} - -int stb_fget_ranged(FILE *f, int b, stb_uint n) -{ - unsigned int v = 0; - if (n > (1 << 24)) v += stb_fgetc(f) << 24; - if (n > (1 << 16)) v += stb_fgetc(f) << 16; - if (n > (1 << 8)) v += stb_fgetc(f) << 8; - v += stb_fgetc(f); - return b + v; -} - -int stb_size_ranged(int b, stb_uint n) -{ - if (n > (1 << 24)) return 4; - if (n > (1 << 16)) return 3; - if (n > (1 << 8)) return 2; - return 1; -} - -void stb_fput_string(FILE *f, char *s) -{ - int len = strlen(s); - stb_fput_varlenu(f, len); - fwrite(s, 1, len, f); -} - -// inverse of the above algorithm -char *stb_fget_string(FILE *f, void *p) -{ - char *s; - int len = stb_fget_varlenu(f); - if (len > 4096) return NULL; - s = p ? stb_malloc_string(p, len + 1) : (char *)malloc(len + 1); - fread(s, 1, len, f); - s[len] = 0; - return s; -} - -char *stb_strdup(char *str, void *pool) -{ - int len = strlen(str); - char *p = stb_malloc_string(pool, len + 1); - strcpy(p, str); - return p; -} - -// strip the trailing '/' or '\\' from a directory so we can refer to it -// as a file for _stat() -char *stb_strip_final_slash(char *t) -{ - if (t[0]) { - char *z = t + strlen(t) - 1; - // *z is the last character - if (*z == '\\' || *z == '/') - if (z != t + 2 || t[1] != ':') // but don't strip it if it's e.g. "c:/" - *z = 0; - if (*z == '\\') - *z = '/'; // canonicalize to make sure it matches db - } - return t; -} - -char *stb_strip_final_slash_regardless(char *t) -{ - if (t[0]) { - char *z = t + strlen(t) - 1; - // *z is the last character - if (*z == '\\' || *z == '/') - *z = 0; - if (*z == '\\') - *z = '/'; // canonicalize to make sure it matches db - } - return t; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Options parsing -// - -STB_EXTERN char **stb_getopt_param(int *argc, char **argv, char *param); -STB_EXTERN char **stb_getopt(int *argc, char **argv); -STB_EXTERN void stb_getopt_free(char **opts); - -#ifdef STB_DEFINE - -void stb_getopt_free(char **opts) -{ - int i; - char ** o2 = opts; - for (i = 0; i < stb_arr_len(o2); ++i) - free(o2[i]); - stb_arr_free(o2); -} - -char **stb_getopt(int *argc, char **argv) -{ - return stb_getopt_param(argc, argv, ""); -} - -char **stb_getopt_param(int *argc, char **argv, char *param) -{ - char ** opts = NULL; - int i, j = 1; - for (i = 1; i < *argc; ++i) { - if (argv[i][0] != '-') { - argv[j++] = argv[i]; - } - else { - if (argv[i][1] == 0) { // plain - == don't parse further options - ++i; - while (i < *argc) - argv[j++] = argv[i++]; - break; - } - else { - int k; - char *q = argv[i]; // traverse options list - for (k = 1; q[k]; ++k) { - char *s; - if (strchr(param, q[k])) { // does it take a parameter? - char *t = &q[k + 1], z = q[k]; - int len = 0; - if (*t == 0) { - if (i == *argc - 1) { // takes a parameter, but none found - *argc = 0; - stb_getopt_free(opts); - return NULL; - } - t = argv[++i]; - } - else - k += strlen(t); - len = strlen(t); - s = (char *)malloc(len + 2); - if (!s) return NULL; - s[0] = z; - strcpy(s + 1, t); - } - else { - // no parameter - s = (char *)malloc(2); - if (!s) return NULL; - s[0] = q[k]; - s[1] = 0; - } - stb_arr_push(opts, s); - } - } - } - } - stb_arr_push(opts, NULL); - *argc = j; - return opts; -} -#endif - - -////////////////////////////////////////////////////////////////////////////// -// -// Portable directory reading -// - -STB_EXTERN char **stb_readdir_files(char *dir); -STB_EXTERN char **stb_readdir_files_mask(char *dir, char *wild); -STB_EXTERN char **stb_readdir_subdirs(char *dir); -STB_EXTERN char **stb_readdir_subdirs_mask(char *dir, char *wild); -STB_EXTERN void stb_readdir_free(char **files); -STB_EXTERN char **stb_readdir_recursive(char *dir, char *filespec); -STB_EXTERN void stb_delete_directory_recursive(char *dir); - -#ifdef STB_DEFINE - -#ifdef _MSC_VER -#include <io.h> -#else -#include <unistd.h> -#include <dirent.h> -#endif - -void stb_readdir_free(char **files) -{ - char **f2 = files; - int i; - for (i = 0; i < stb_arr_len(f2); ++i) - free(f2[i]); - stb_arr_free(f2); -} - -static int isdotdirname(char *name) -{ - if (name[0] == '.') - return (name[1] == '.') ? !name[2] : !name[1]; - return 0; -} - -STB_EXTERN int stb_wildmatchi(char *expr, char *candidate); -static char **readdir_raw(char *dir, int return_subdirs, char *mask) -{ - char **results = NULL; - char buffer[4096], with_slash[4096]; - size_t n; - -#ifdef _MSC_VER - stb__wchar *ws; - struct _wfinddata_t data; -#ifdef _WIN64 - const intptr_t none = -1; - intptr_t z; -#else - const long none = -1; - long z; -#endif -#else // !_MSC_VER - const DIR *none = NULL; - DIR *z; -#endif - - n = stb_strscpy(buffer, dir, sizeof(buffer)); - if (!n || n >= sizeof(buffer)) - return NULL; - stb_fixpath(buffer); - n--; - - if (n > 0 && (buffer[n - 1] != '/')) { - buffer[n++] = '/'; - } - buffer[n] = 0; - if (!stb_strscpy(with_slash, buffer, sizeof(with_slash))) - return NULL; - -#ifdef _MSC_VER - if (!stb_strscpy(buffer + n, "*.*", sizeof(buffer) - n)) - return NULL; - ws = stb__from_utf8(buffer); - z = _wfindfirst((const wchar_t *)ws, &data); -#else - z = opendir(dir); -#endif - - if (z != none) { - int nonempty = STB_TRUE; -#ifndef _MSC_VER - struct dirent *data = readdir(z); - nonempty = (data != NULL); -#endif - - if (nonempty) { - - do { - int is_subdir; -#ifdef _MSC_VER - char *name = stb__to_utf8((stb__wchar *)data.name); - if (name == NULL) { - fprintf(stderr, "%s to convert '%S' to %s!\n", "Unable", data.name, "utf8"); - continue; - } - is_subdir = !!(data.attrib & _A_SUBDIR); -#else - char *name = data->d_name; - if (!stb_strscpy(buffer + n, name, sizeof(buffer) - n)) - break; - // Could follow DT_LNK, but would need to check for recursive links. - is_subdir = !!(data->d_type & DT_DIR); -#endif - - if (is_subdir == return_subdirs) { - if (!is_subdir || !isdotdirname(name)) { - if (!mask || stb_wildmatchi(mask, name)) { - char buffer[4096], *p = buffer; - if (stb_snprintf(buffer, sizeof(buffer), "%s%s", with_slash, name) < 0) - break; - if (buffer[0] == '.' && buffer[1] == '/') - p = buffer + 2; - stb_arr_push(results, strdup(p)); - } - } - } - } -#ifdef _MSC_VER - while (0 == _wfindnext(z, &data)); -#else - while ((data = readdir(z)) != NULL); -#endif - } -#ifdef _MSC_VER - _findclose(z); -#else - closedir(z); -#endif - } - return results; -} - -char **stb_readdir_files(char *dir) { return readdir_raw(dir, 0, NULL); } -char **stb_readdir_subdirs(char *dir) { return readdir_raw(dir, 1, NULL); } -char **stb_readdir_files_mask(char *dir, char *wild) { return readdir_raw(dir, 0, wild); } -char **stb_readdir_subdirs_mask(char *dir, char *wild) { return readdir_raw(dir, 1, wild); } - -int stb__rec_max = 0x7fffffff; -static char **stb_readdir_rec(char **sofar, char *dir, char *filespec) -{ - char **files; - char ** dirs; - char **p; - - if (stb_arr_len(sofar) >= stb__rec_max) return sofar; - - files = stb_readdir_files_mask(dir, filespec); - stb_arr_for(p, files) { - stb_arr_push(sofar, strdup(*p)); - if (stb_arr_len(sofar) >= stb__rec_max) break; - } - stb_readdir_free(files); - if (stb_arr_len(sofar) >= stb__rec_max) return sofar; - - dirs = stb_readdir_subdirs(dir); - stb_arr_for(p, dirs) - sofar = stb_readdir_rec(sofar, *p, filespec); - stb_readdir_free(dirs); - return sofar; -} - -char **stb_readdir_recursive(char *dir, char *filespec) -{ - return stb_readdir_rec(NULL, dir, filespec); -} - -void stb_delete_directory_recursive(char *dir) -{ - char **list = stb_readdir_subdirs(dir); - int i; - for (i = 0; i < stb_arr_len(list); ++i) - stb_delete_directory_recursive(list[i]); - stb_arr_free(list); - list = stb_readdir_files(dir); - for (i = 0; i < stb_arr_len(list); ++i) - if (!remove(list[i])) { - // on windows, try again after making it writeable; don't ALWAYS - // do this first since that would be slow in the normal case -#ifdef _MSC_VER - _chmod(list[i], _S_IWRITE); - remove(list[i]); -#endif - } - stb_arr_free(list); - stb__windows(_rmdir, rmdir)(dir); -} - -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// construct trees from filenames; useful for cmirror summaries - -typedef struct stb_dirtree2 stb_dirtree2; - -struct stb_dirtree2 -{ - stb_dirtree2 **subdirs; - - // make convenient for stb_summarize_tree - int num_subdir; - float weight; - - // actual data - char *fullpath; - char *relpath; - char **files; -}; - -STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count); -STB_EXTERN stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count); -STB_EXTERN int stb_dir_is_prefix(char *dir, int dirlen, char *file); - -#ifdef STB_DEFINE - -int stb_dir_is_prefix(char *dir, int dirlen, char *file) -{ - if (dirlen == 0) return STB_TRUE; - if (stb_strnicmp(dir, file, dirlen)) return STB_FALSE; - if (file[dirlen] == '/' || file[dirlen] == '\\') return STB_TRUE; - return STB_FALSE; -} - -stb_dirtree2 *stb_dirtree2_from_files_relative(char *src, char **filelist, int count) -{ - char buffer1[1024]; - int i; - int dlen = strlen(src), elen; - stb_dirtree2 *d; - char ** descendents = NULL; - char ** files = NULL; - char *s; - if (!count) return NULL; - // first find all the ones that belong here... note this is will take O(NM) with N files and M subdirs - for (i = 0; i < count; ++i) { - if (stb_dir_is_prefix(src, dlen, filelist[i])) { - stb_arr_push(descendents, filelist[i]); - } - } - if (descendents == NULL) - return NULL; - elen = dlen; - // skip a leading slash - if (elen == 0 && (descendents[0][0] == '/' || descendents[0][0] == '\\')) - ++elen; - else if (elen) - ++elen; - // now extract all the ones that have their root here - for (i = 0; i < stb_arr_len(descendents);) { - if (!stb_strchr2(descendents[i] + elen, '/', '\\')) { - stb_arr_push(files, descendents[i]); - descendents[i] = descendents[stb_arr_len(descendents) - 1]; - stb_arr_pop(descendents); - } - else - ++i; - } - // now create a record - d = (stb_dirtree2 *)malloc(sizeof(*d)); - d->files = files; - d->subdirs = NULL; - d->fullpath = strdup(src); - s = stb_strrchr2(d->fullpath, '/', '\\'); - if (s) - ++s; - else - s = d->fullpath; - d->relpath = s; - // now create the children - qsort(descendents, stb_arr_len(descendents), sizeof(char *), stb_qsort_stricmp(0)); - buffer1[0] = 0; - for (i = 0; i < stb_arr_len(descendents); ++i) { - char buffer2[1024]; - char *s = descendents[i] + elen, *t; - t = stb_strchr2(s, '/', '\\'); - assert(t); - stb_strncpy(buffer2, descendents[i], t - descendents[i] + 1); - if (stb_stricmp(buffer1, buffer2)) { - stb_dirtree2 *t = stb_dirtree2_from_files_relative(buffer2, descendents, stb_arr_len(descendents)); - assert(t != NULL); - strcpy(buffer1, buffer2); - stb_arr_push(d->subdirs, t); - } - } - d->num_subdir = stb_arr_len(d->subdirs); - d->weight = 0; - return d; -} - -stb_dirtree2 *stb_dirtree2_from_files(char **filelist, int count) -{ - return stb_dirtree2_from_files_relative("", filelist, count); -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Checksums: CRC-32, ADLER32, SHA-1 -// -// CRC-32 and ADLER32 allow streaming blocks -// SHA-1 requires either a complete buffer, max size 2^32 - 73 -// or it can checksum directly from a file, max 2^61 - -#define STB_ADLER32_SEED 1 -#define STB_CRC32_SEED 0 // note that we logical NOT this in the code - -STB_EXTERN stb_uint -stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen); -STB_EXTERN stb_uint -stb_crc32_block(stb_uint crc32, stb_uchar *buffer, stb_uint len); -STB_EXTERN stb_uint stb_crc32(unsigned char *buffer, stb_uint len); - -STB_EXTERN void stb_sha1( - unsigned char output[20], unsigned char *buffer, unsigned int len); -STB_EXTERN int stb_sha1_file(unsigned char output[20], char *file); - -STB_EXTERN void stb_sha1_readable(char display[27], unsigned char sha[20]); - -#ifdef STB_DEFINE -stb_uint stb_crc32_block(stb_uint crc, unsigned char *buffer, stb_uint len) -{ - static stb_uint crc_table[256]; - stb_uint i, j, s; - crc = ~crc; - - if (crc_table[1] == 0) - for (i = 0; i < 256; i++) { - for (s = i, j = 0; j < 8; ++j) - s = (s >> 1) ^ (s & 1 ? 0xedb88320 : 0); - crc_table[i] = s; - } - for (i = 0; i < len; ++i) - crc = (crc >> 8) ^ crc_table[buffer[i] ^ (crc & 0xff)]; - return ~crc; -} - -stb_uint stb_crc32(unsigned char *buffer, stb_uint len) -{ - return stb_crc32_block(0, buffer, len); -} - -stb_uint stb_adler32(stb_uint adler32, stb_uchar *buffer, stb_uint buflen) -{ - const unsigned long ADLER_MOD = 65521; - unsigned long s1 = adler32 & 0xffff, s2 = adler32 >> 16; - unsigned long blocklen, i; - - blocklen = buflen % 5552; - while (buflen) { - for (i = 0; i + 7 < blocklen; i += 8) { - s1 += buffer[0], s2 += s1; - s1 += buffer[1], s2 += s1; - s1 += buffer[2], s2 += s1; - s1 += buffer[3], s2 += s1; - s1 += buffer[4], s2 += s1; - s1 += buffer[5], s2 += s1; - s1 += buffer[6], s2 += s1; - s1 += buffer[7], s2 += s1; - - buffer += 8; - } - - for (; i < blocklen; ++i) - s1 += *buffer++, s2 += s1; - - s1 %= ADLER_MOD, s2 %= ADLER_MOD; - buflen -= blocklen; - blocklen = 5552; - } - return (s2 << 16) + s1; -} - -static void stb__sha1(stb_uchar *chunk, stb_uint h[5]) -{ - int i; - stb_uint a, b, c, d, e; - stb_uint w[80]; - - for (i = 0; i < 16; ++i) - w[i] = stb_big32(&chunk[i * 4]); - for (i = 16; i < 80; ++i) { - stb_uint t; - t = w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]; - w[i] = (t + t) | (t >> 31); - } - - a = h[0]; - b = h[1]; - c = h[2]; - d = h[3]; - e = h[4]; - -#define STB__SHA1(k,f) \ - { \ - stb_uint temp = (a << 5) + (a >> 27) + (f) + e + (k) + w[i]; \ - e = d; \ - d = c; \ - c = (b << 30) + (b >> 2); \ - b = a; \ - a = temp; \ - } - - i = 0; - for (; i < 20; ++i) STB__SHA1(0x5a827999, d ^ (b & (c ^ d))); - for (; i < 40; ++i) STB__SHA1(0x6ed9eba1, b ^ c ^ d); - for (; i < 60; ++i) STB__SHA1(0x8f1bbcdc, (b & c) + (d & (b ^ c))); - for (; i < 80; ++i) STB__SHA1(0xca62c1d6, b ^ c ^ d); - -#undef STB__SHA1 - - h[0] += a; - h[1] += b; - h[2] += c; - h[3] += d; - h[4] += e; -} - -void stb_sha1(stb_uchar output[20], stb_uchar *buffer, stb_uint len) -{ - unsigned char final_block[128]; - stb_uint end_start, final_len, j; - int i; - - stb_uint h[5]; - - h[0] = 0x67452301; - h[1] = 0xefcdab89; - h[2] = 0x98badcfe; - h[3] = 0x10325476; - h[4] = 0xc3d2e1f0; - - // we need to write padding to the last one or two - // blocks, so build those first into 'final_block' - - // we have to write one special byte, plus the 8-byte length - - // compute the block where the data runs out - end_start = len & ~63; - - // compute the earliest we can encode the length - if (((len + 9) & ~63) == end_start) { - // it all fits in one block, so fill a second-to-last block - end_start -= 64; - } - - final_len = end_start + 128; - - // now we need to copy the data in - assert(end_start + 128 >= len + 9); - assert(end_start < len || len < 64 - 9); - - j = 0; - if (end_start > len) - j = (stb_uint)-(int)end_start; - - for (; end_start + j < len; ++j) - final_block[j] = buffer[end_start + j]; - final_block[j++] = 0x80; - while (j < 128 - 5) // 5 byte length, so write 4 extra padding bytes - final_block[j++] = 0; - // big-endian size - final_block[j++] = len >> 29; - final_block[j++] = len >> 21; - final_block[j++] = len >> 13; - final_block[j++] = len >> 5; - final_block[j++] = len << 3; - assert(j == 128 && end_start + j == final_len); - - for (j = 0; j < final_len; j += 64) { // 512-bit chunks - if (j + 64 >= end_start + 64) - stb__sha1(&final_block[j - end_start], h); - else - stb__sha1(&buffer[j], h); - } - - for (i = 0; i < 5; ++i) { - output[i * 4 + 0] = h[i] >> 24; - output[i * 4 + 1] = h[i] >> 16; - output[i * 4 + 2] = h[i] >> 8; - output[i * 4 + 3] = h[i] >> 0; - } -} - -#ifdef _MSC_VER -int stb_sha1_file(stb_uchar output[20], char *file) -{ - int i; - stb_uint64 length = 0; - unsigned char buffer[128]; - - FILE *f = stb__fopen(file, "rb"); - stb_uint h[5]; - - if (f == NULL) return 0; // file not found - - h[0] = 0x67452301; - h[1] = 0xefcdab89; - h[2] = 0x98badcfe; - h[3] = 0x10325476; - h[4] = 0xc3d2e1f0; - - for (;;) { - int n = fread(buffer, 1, 64, f); - if (n == 64) { - stb__sha1(buffer, h); - length += n; - } - else { - int block = 64; - - length += n; - - buffer[n++] = 0x80; - - // if there isn't enough room for the length, double the block - if (n + 8 > 64) - block = 128; - - // pad to end - memset(buffer + n, 0, block - 8 - n); - - i = block - 8; - buffer[i++] = (stb_uchar)(length >> 53); - buffer[i++] = (stb_uchar)(length >> 45); - buffer[i++] = (stb_uchar)(length >> 37); - buffer[i++] = (stb_uchar)(length >> 29); - buffer[i++] = (stb_uchar)(length >> 21); - buffer[i++] = (stb_uchar)(length >> 13); - buffer[i++] = (stb_uchar)(length >> 5); - buffer[i++] = (stb_uchar)(length << 3); - assert(i == block); - stb__sha1(buffer, h); - if (block == 128) - stb__sha1(buffer + 64, h); - else - assert(block == 64); - break; - } - } - fclose(f); - - for (i = 0; i < 5; ++i) { - output[i * 4 + 0] = h[i] >> 24; - output[i * 4 + 1] = h[i] >> 16; - output[i * 4 + 2] = h[i] >> 8; - output[i * 4 + 3] = h[i] >> 0; - } - - return 1; -} -#endif // _MSC_VER - -// client can truncate this wherever they like -void stb_sha1_readable(char display[27], unsigned char sha[20]) -{ - char encoding[65] = "0123456789abcdefghijklmnopqrstuv" - "wxyzABCDEFGHIJKLMNOPQRSTUVWXYZ%$"; - int num_bits = 0, acc = 0; - int i = 0, o = 0; - while (o < 26) { - int v; - // expand the accumulator - if (num_bits < 6) { - assert(i != 20); - acc += sha[i++] << num_bits; - num_bits += 8; - } - v = acc & ((1 << 6) - 1); - display[o++] = encoding[v]; - acc >>= 6; - num_bits -= 6; - } - assert(num_bits == 20 * 8 - 26 * 6); - display[o++] = encoding[acc]; -} - -#endif // STB_DEFINE - -/////////////////////////////////////////////////////////// -// -// simplified WINDOWS registry interface... hopefully -// we'll never actually use this? - -#if defined(_WIN32) - -STB_EXTERN void * stb_reg_open(char *mode, char *where); // mode: "rHKLM" or "rHKCU" or "w.." -STB_EXTERN void stb_reg_close(void *reg); -STB_EXTERN int stb_reg_read(void *zreg, char *str, void *data, unsigned long len); -STB_EXTERN int stb_reg_read_string(void *zreg, char *str, char *data, int len); -STB_EXTERN void stb_reg_write(void *zreg, char *str, void *data, unsigned long len); -STB_EXTERN void stb_reg_write_string(void *zreg, char *str, char *data); - -#if defined(STB_DEFINE) && !defined(STB_NO_REGISTRY) - -#define STB_HAS_REGISTRY - -#ifndef _WINDOWS_ - -#define HKEY void * - -STB_EXTERN __declspec(dllimport) long __stdcall RegCloseKey(HKEY hKey); -STB_EXTERN __declspec(dllimport) long __stdcall RegCreateKeyExA(HKEY hKey, const char * lpSubKey, - int Reserved, char * lpClass, int dwOptions, - int samDesired, void *lpSecurityAttributes, HKEY * phkResult, int * lpdwDisposition); -STB_EXTERN __declspec(dllimport) long __stdcall RegDeleteKeyA(HKEY hKey, const char * lpSubKey); -STB_EXTERN __declspec(dllimport) long __stdcall RegQueryValueExA(HKEY hKey, const char * lpValueName, - int * lpReserved, unsigned long * lpType, unsigned char * lpData, unsigned long * lpcbData); -STB_EXTERN __declspec(dllimport) long __stdcall RegSetValueExA(HKEY hKey, const char * lpValueName, - int Reserved, int dwType, const unsigned char* lpData, int cbData); -STB_EXTERN __declspec(dllimport) long __stdcall RegOpenKeyExA(HKEY hKey, const char * lpSubKey, - int ulOptions, int samDesired, HKEY * phkResult); - -#endif // _WINDOWS_ - -#define STB__REG_OPTION_NON_VOLATILE 0 -#define STB__REG_KEY_ALL_ACCESS 0x000f003f -#define STB__REG_KEY_READ 0x00020019 - -void *stb_reg_open(char *mode, char *where) -{ - long res; - HKEY base; - HKEY zreg; - if (!stb_stricmp(mode + 1, "cu") || !stb_stricmp(mode + 1, "hkcu")) - base = (HKEY)0x80000001; // HKCU - else if (!stb_stricmp(mode + 1, "lm") || !stb_stricmp(mode + 1, "hklm")) - base = (HKEY)0x80000002; // HKLM - else - return NULL; - - if (mode[0] == 'r') - res = RegOpenKeyExA(base, where, 0, STB__REG_KEY_READ, &zreg); - else if (mode[0] == 'w') - res = RegCreateKeyExA(base, where, 0, NULL, STB__REG_OPTION_NON_VOLATILE, STB__REG_KEY_ALL_ACCESS, NULL, &zreg, NULL); - else - return NULL; - - return res ? NULL : zreg; -} - -void stb_reg_close(void *reg) -{ - RegCloseKey((HKEY)reg); -} - -#define STB__REG_SZ 1 -#define STB__REG_BINARY 3 -#define STB__REG_DWORD 4 - -int stb_reg_read(void *zreg, char *str, void *data, unsigned long len) -{ - unsigned long type; - unsigned long alen = len; - if (0 == RegQueryValueExA((HKEY)zreg, str, 0, &type, (unsigned char *)data, &len)) - if (type == STB__REG_BINARY || type == STB__REG_SZ || type == STB__REG_DWORD) { - if (len < alen) - *((char *)data + len) = 0; - return 1; - } - return 0; -} - -void stb_reg_write(void *zreg, char *str, void *data, unsigned long len) -{ - if (zreg) - RegSetValueExA((HKEY)zreg, str, 0, STB__REG_BINARY, (const unsigned char *)data, len); -} - -int stb_reg_read_string(void *zreg, char *str, char *data, int len) -{ - if (!stb_reg_read(zreg, str, data, len)) return 0; - data[len - 1] = 0; // force a 0 at the end of the string no matter what - return 1; -} - -void stb_reg_write_string(void *zreg, char *str, char *data) -{ - if (zreg) - RegSetValueExA((HKEY)zreg, str, 0, STB__REG_SZ, (const unsigned char *)data, strlen(data) + 1); -} -#endif // STB_DEFINE -#endif // _WIN32 - - -////////////////////////////////////////////////////////////////////////////// -// -// stb_cfg - This is like the registry, but the config info -// is all stored in plain old files where we can -// backup and restore them easily. The LOCATION of -// the config files is gotten from... the registry! - -#ifndef STB_NO_STB_STRINGS -typedef struct stb_cfg_st stb_cfg; - -STB_EXTERN stb_cfg * stb_cfg_open(char *config, char *mode); // mode = "r", "w" -STB_EXTERN void stb_cfg_close(stb_cfg *cfg); -STB_EXTERN int stb_cfg_read(stb_cfg *cfg, char *key, void *value, int len); -STB_EXTERN void stb_cfg_write(stb_cfg *cfg, char *key, void *value, int len); -STB_EXTERN int stb_cfg_read_string(stb_cfg *cfg, char *key, char *value, int len); -STB_EXTERN void stb_cfg_write_string(stb_cfg *cfg, char *key, char *value); -STB_EXTERN int stb_cfg_delete(stb_cfg *cfg, char *key); -STB_EXTERN void stb_cfg_set_directory(char *dir); - -#ifdef STB_DEFINE - -typedef struct -{ - char *key; - void *value; - int value_len; -} stb__cfg_item; - -struct stb_cfg_st -{ - stb__cfg_item *data; - char *loaded_file; // this needs to be freed - FILE *f; // write the data to this file on close -}; - -static char *stb__cfg_sig = "sTbCoNfIg!\0\0"; -static char stb__cfg_dir[512]; -STB_EXTERN void stb_cfg_set_directory(char *dir) -{ - strcpy(stb__cfg_dir, dir); -} - -STB_EXTERN stb_cfg * stb_cfg_open(char *config, char *mode) -{ - size_t len; - stb_cfg *z; - char file[512]; - if (mode[0] != 'r' && mode[0] != 'w') return NULL; - - if (!stb__cfg_dir[0]) { -#ifdef _WIN32 - strcpy(stb__cfg_dir, "c:/stb"); -#else - strcpy(stb__cfg_dir, "~/.stbconfig"); -#endif - -#ifdef STB_HAS_REGISTRY - { - void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb"); - if (reg) { - stb_reg_read_string(reg, "config_dir", stb__cfg_dir, sizeof(stb__cfg_dir)); - stb_reg_close(reg); - } - } -#endif - } - - sprintf(file, "%s/%s.cfg", stb__cfg_dir, config); - - z = (stb_cfg *)stb_malloc(0, sizeof(*z)); - z->data = NULL; - - z->loaded_file = stb_filec(file, &len); - if (z->loaded_file) { - char *s = z->loaded_file; - if (!memcmp(s, stb__cfg_sig, 12)) { - char *s = z->loaded_file + 12; - while (s < z->loaded_file + len) { - stb__cfg_item a; - int n = *(stb_int16 *)s; - a.key = s + 2; - s = s + 2 + n; - a.value_len = *(int *)s; - s += 4; - a.value = s; - s += a.value_len; - stb_arr_push(z->data, a); - } - assert(s == z->loaded_file + len); - } - } - - if (mode[0] == 'w') - z->f = fopen(file, "wb"); - else - z->f = NULL; - - return z; -} - -void stb_cfg_close(stb_cfg *z) -{ - if (z->f) { - int i; - // write the file out - fwrite(stb__cfg_sig, 12, 1, z->f); - for (i = 0; i < stb_arr_len(z->data); ++i) { - stb_int16 n = strlen(z->data[i].key) + 1; - fwrite(&n, 2, 1, z->f); - fwrite(z->data[i].key, n, 1, z->f); - fwrite(&z->data[i].value_len, 4, 1, z->f); - fwrite(z->data[i].value, z->data[i].value_len, 1, z->f); - } - fclose(z->f); - } - stb_arr_free(z->data); - stb_free(z); -} - -int stb_cfg_read(stb_cfg *z, char *key, void *value, int len) -{ - int i; - for (i = 0; i < stb_arr_len(z->data); ++i) { - if (!stb_stricmp(z->data[i].key, key)) { - int n = stb_min(len, z->data[i].value_len); - memcpy(value, z->data[i].value, n); - if (n < len) - *((char *)value + n) = 0; - return 1; - } - } - return 0; -} - -void stb_cfg_write(stb_cfg *z, char *key, void *value, int len) -{ - int i; - for (i = 0; i < stb_arr_len(z->data); ++i) - if (!stb_stricmp(z->data[i].key, key)) - break; - if (i == stb_arr_len(z->data)) { - stb__cfg_item p; - p.key = stb_strdup(key, z); - p.value = NULL; - p.value_len = 0; - stb_arr_push(z->data, p); - } - z->data[i].value = stb_malloc(z, len); - z->data[i].value_len = len; - memcpy(z->data[i].value, value, len); -} - -int stb_cfg_delete(stb_cfg *z, char *key) -{ - int i; - for (i = 0; i < stb_arr_len(z->data); ++i) - if (!stb_stricmp(z->data[i].key, key)) { - stb_arr_fastdelete(z->data, i); - return 1; - } - return 0; -} - -int stb_cfg_read_string(stb_cfg *z, char *key, char *value, int len) -{ - if (!stb_cfg_read(z, key, value, len)) return 0; - value[len - 1] = 0; - return 1; -} - -void stb_cfg_write_string(stb_cfg *z, char *key, char *value) -{ - stb_cfg_write(z, key, value, strlen(value) + 1); -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// stb_dirtree - load a description of a directory tree -// uses a cache and stat()s the directories for changes -// MUCH faster on NTFS, _wrong_ on FAT32, so should -// ignore the db on FAT32 - -#ifdef _WIN32 - -typedef struct -{ - char * path; // full path from passed-in root - time_t last_modified; - int num_files; - int flag; -} stb_dirtree_dir; - -typedef struct -{ - char *name; // name relative to path - int dir; // index into dirs[] array - stb_int64 size; // size, max 4GB - time_t last_modified; - int flag; -} stb_dirtree_file; - -typedef struct -{ - stb_dirtree_dir *dirs; - stb_dirtree_file *files; - - // internal use - void * string_pool; // used to free data en masse -} stb_dirtree; - -extern void stb_dirtree_free(stb_dirtree *d); -extern stb_dirtree *stb_dirtree_get(char *dir); -extern stb_dirtree *stb_dirtree_get_dir(char *dir, char *cache_dir); -extern stb_dirtree *stb_dirtree_get_with_file(char *dir, char *cache_file); - -// get a list of all the files recursively underneath 'dir' -// -// cache_file is used to store a copy of the directory tree to speed up -// later calls. It must be unique to 'dir' and the current working -// directory! Otherwise who knows what will happen (a good solution -// is to put it _in_ dir, but this API doesn't force that). -// -// Also, it might be possible to break this if you have two different processes -// do a call to stb_dirtree_get() with the same cache file at about the same -// time, but I _think_ it might just work. - -// i needed to build an identical data structure representing the state of -// a mirrored copy WITHOUT bothering to rescan it (i.e. we're mirroring to -// it WITHOUT scanning it, e.g. it's over the net), so this requires access -// to all of the innards. -extern void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last); -extern void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last); -extern void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir); -extern void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir); - -#ifdef STB_DEFINE -static void stb__dirtree_add_dir(char *path, time_t last, stb_dirtree *active) -{ - stb_dirtree_dir d; - d.last_modified = last; - d.num_files = 0; - d.path = stb_strdup(path, active->string_pool); - stb_arr_push(active->dirs, d); -} - -static void stb__dirtree_add_file(char *name, int dir, stb_int64 size, time_t last, stb_dirtree *active) -{ - stb_dirtree_file f; - f.dir = dir; - f.size = size; - f.last_modified = last; - f.name = stb_strdup(name, active->string_pool); - ++active->dirs[dir].num_files; - stb_arr_push(active->files, f); -} - -// version 02 supports > 4GB files -static char stb__signature[12] = { 's', 'T', 'b', 'D', 'i', 'R', 't', 'R', 'e', 'E', '0', '2' }; - -static void stb__dirtree_save_db(char *filename, stb_dirtree *data, char *root) -{ - int i, num_dirs_final = 0, num_files_final; - char *info = root ? root : ""; - int *remap; - FILE *f = fopen(filename, "wb"); - if (!f) return; - - fwrite(stb__signature, sizeof(stb__signature), 1, f); - fwrite(info, strlen(info) + 1, 1, f); - // need to be slightly tricky and not write out NULLed directories, nor the root - - // build remapping table of all dirs we'll be writing out - remap = (int *)malloc(sizeof(remap[0]) * stb_arr_len(data->dirs)); - for (i = 0; i < stb_arr_len(data->dirs); ++i) { - if (data->dirs[i].path == NULL || (root && 0 == stb_stricmp(data->dirs[i].path, root))) { - remap[i] = -1; - } - else { - remap[i] = num_dirs_final++; - } - } - - fwrite(&num_dirs_final, 4, 1, f); - for (i = 0; i < stb_arr_len(data->dirs); ++i) { - if (remap[i] >= 0) { - fwrite(&data->dirs[i].last_modified, 4, 1, f); - stb_fput_string(f, data->dirs[i].path); - } - } - - num_files_final = 0; - for (i = 0; i < stb_arr_len(data->files); ++i) - if (remap[data->files[i].dir] >= 0 && data->files[i].name) - ++num_files_final; - - fwrite(&num_files_final, 4, 1, f); - for (i = 0; i < stb_arr_len(data->files); ++i) { - if (remap[data->files[i].dir] >= 0 && data->files[i].name) { - stb_fput_ranged(f, remap[data->files[i].dir], 0, num_dirs_final); - stb_fput_varlen64(f, data->files[i].size); - fwrite(&data->files[i].last_modified, 4, 1, f); - stb_fput_string(f, data->files[i].name); - } - } - - fclose(f); -} - -// note: stomps any existing data, rather than appending -static void stb__dirtree_load_db(char *filename, stb_dirtree *data, char *dir) -{ - char sig[2048]; - int i, n; - FILE *f = fopen(filename, "rb"); - - if (!f) return; - - data->string_pool = stb_malloc(0, 1); - - fread(sig, sizeof(stb__signature), 1, f); - if (memcmp(stb__signature, sig, sizeof(stb__signature))) { fclose(f); return; } - if (!fread(sig, strlen(dir) + 1, 1, f)) { fclose(f); return; } - if (stb_stricmp(sig, dir)) { fclose(f); return; } - - // we can just read them straight in, because they're guaranteed to be valid - fread(&n, 4, 1, f); - stb_arr_setlen(data->dirs, n); - for (i = 0; i < stb_arr_len(data->dirs); ++i) { - fread(&data->dirs[i].last_modified, 4, 1, f); - data->dirs[i].path = stb_fget_string(f, data->string_pool); - if (data->dirs[i].path == NULL) goto bail; - } - fread(&n, 4, 1, f); - stb_arr_setlen(data->files, n); - for (i = 0; i < stb_arr_len(data->files); ++i) { - data->files[i].dir = stb_fget_ranged(f, 0, stb_arr_len(data->dirs)); - data->files[i].size = stb_fget_varlen64(f); - fread(&data->files[i].last_modified, 4, 1, f); - data->files[i].name = stb_fget_string(f, data->string_pool); - if (data->files[i].name == NULL) goto bail; - } - - if (0) { - bail: - stb_arr_free(data->dirs); - stb_arr_free(data->files); - } - fclose(f); -} - -static int stb__dircount, stb__dircount_mask, stb__showfile; -static void stb__dirtree_scandir(char *path, time_t last_time, stb_dirtree *active) -{ - // this is dumb depth first; theoretically it might be faster - // to fully traverse each directory before visiting its children, - // but it's complicated and didn't seem like a gain in the test app - - int n; - - struct _wfinddatai64_t c_file; - long hFile; - stb__wchar full_path[1024]; - int has_slash; - if (stb__showfile) printf("<"); - - has_slash = (path[0] && path[strlen(path) - 1] == '/'); - - // @TODO: do this concatenation without using swprintf to avoid this mess: -#if defined(_MSC_VER) && _MSC_VER < 1400 - if (has_slash) - swprintf(full_path, L"%s*", stb__from_utf8(path)); - else - swprintf(full_path, L"%s/*", stb__from_utf8(path)); -#else - if (has_slash) - swprintf(full_path, 1024, L"%s*", stb__from_utf8(path)); - else - swprintf(full_path, 1024, L"%s/*", stb__from_utf8(path)); -#endif - - // it's possible this directory is already present: that means it was in the - // cache, but its parent wasn't... in that case, we're done with it - if (stb__showfile) printf("C[%d]", stb_arr_len(active->dirs)); - for (n = 0; n < stb_arr_len(active->dirs); ++n) - if (0 == stb_stricmp(active->dirs[n].path, path)) { - if (stb__showfile) printf("D"); - return; - } - if (stb__showfile) printf("E"); - - // otherwise, we need to add it - stb__dirtree_add_dir(path, last_time, active); - n = stb_arr_lastn(active->dirs); - - if (stb__showfile) printf("["); - if ((hFile = _wfindfirsti64(full_path, &c_file)) != -1L) { - do { - if (stb__showfile) printf(")"); - if (c_file.attrib & _A_SUBDIR) { - // ignore subdirectories starting with '.', e.g. "." and ".." - if (c_file.name[0] != '.') { - char *new_path = (char *)full_path; - char *temp = stb__to_utf8(c_file.name); - - if (has_slash) - sprintf(new_path, "%s%s", path, temp); - else - sprintf(new_path, "%s/%s", path, temp); - - if (stb__dircount_mask) { - ++stb__dircount; - if (!(stb__dircount & stb__dircount_mask)) { - printf("%s\r", new_path); - } - } - - stb__dirtree_scandir(new_path, c_file.time_write, active); - } - } - else { - char *temp = stb__to_utf8(c_file.name); - stb__dirtree_add_file(temp, n, c_file.size, c_file.time_write, active); - } - if (stb__showfile) printf("("); - } while (_wfindnexti64(hFile, &c_file) == 0); - if (stb__showfile) printf("]"); - _findclose(hFile); - } - if (stb__showfile) printf(">\n"); -} - -// scan the database and see if it's all valid -static int stb__dirtree_update_db(stb_dirtree *db, stb_dirtree *active) -{ - int changes_detected = STB_FALSE; - int i; - int *remap; - int *rescan = NULL; - remap = (int *)malloc(sizeof(remap[0]) * stb_arr_len(db->dirs)); - memset(remap, 0, sizeof(remap[0]) * stb_arr_len(db->dirs)); - rescan = NULL; - - for (i = 0; i < stb_arr_len(db->dirs); ++i) { - struct _stat info; - if (stb__dircount_mask) { - ++stb__dircount; - if (!(stb__dircount & stb__dircount_mask)) { - printf("."); - } - } - if (0 == _stat(db->dirs[i].path, &info)) { - if (info.st_mode & _S_IFDIR) { - // it's still a directory, as expected - int n = abs(info.st_mtime - db->dirs[i].last_modified); - if (n > 1 && n != 3600) { // the 3600 is a hack because sometimes this jumps for no apparent reason, even when no time zone or DST issues are at play - // it's changed! force a rescan - // we don't want to scan it until we've stat()d its - // subdirs, though, so we queue it - if (stb__showfile) printf("Changed: %s - %08x:%08x\n", db->dirs[i].path, db->dirs[i].last_modified, info.st_mtime); - stb_arr_push(rescan, i); - // update the last_mod time - db->dirs[i].last_modified = info.st_mtime; - // ignore existing files in this dir - remap[i] = -1; - changes_detected = STB_TRUE; - } - else { - // it hasn't changed, just copy it through unchanged - stb__dirtree_add_dir(db->dirs[i].path, db->dirs[i].last_modified, active); - remap[i] = stb_arr_lastn(active->dirs); - } - } - else { - // this path used to refer to a directory, but now it's a file! - // assume that the parent directory is going to be forced to rescan anyway - goto delete_entry; - } - } - else { - delete_entry: - // directory no longer exists, so don't copy it - // we don't free it because it's in the string pool now - db->dirs[i].path = NULL; - remap[i] = -1; - changes_detected = STB_TRUE; - } - } - - // at this point, we have: - // - // <rescan> holds a list of directory indices that need to be scanned due to being out of date - // <remap> holds the directory index in <active> for each dir in <db>, if it exists; -1 if not - // directories in <rescan> are not in <active> yet - - // so we can go ahead and remap all the known files right now - for (i = 0; i < stb_arr_len(db->files); ++i) { - int dir = db->files[i].dir; - if (remap[dir] >= 0) { - stb__dirtree_add_file(db->files[i].name, remap[dir], db->files[i].size, db->files[i].last_modified, active); - } - } - - // at this point we're done with db->files, and done with remap - free(remap); - - // now scan those directories using the standard scan - for (i = 0; i < stb_arr_len(rescan); ++i) { - int z = rescan[i]; - stb__dirtree_scandir(db->dirs[z].path, db->dirs[z].last_modified, active); - } - stb_arr_free(rescan); - - return changes_detected; -} - -static void stb__dirtree_free_raw(stb_dirtree *d) -{ - stb_free(d->string_pool); - stb_arr_free(d->dirs); - stb_arr_free(d->files); -} - -stb_dirtree *stb_dirtree_get_with_file(char *dir, char *cache_file) -{ - stb_dirtree *output = (stb_dirtree *)malloc(sizeof(*output)); - stb_dirtree db, active; - int prev_dir_count, cache_mismatch; - - char *stripped_dir; // store the directory name without a trailing '/' or '\\' - - // load the database of last-known state on disk - db.string_pool = NULL; - db.files = NULL; - db.dirs = NULL; - - stripped_dir = stb_strip_final_slash(strdup(dir)); - - if (cache_file != NULL) - stb__dirtree_load_db(cache_file, &db, stripped_dir); - else if (stb__showfile) - printf("No cache file\n"); - - active.files = NULL; - active.dirs = NULL; - active.string_pool = stb_malloc(0, 1); // @TODO: share string pools between both? - - // check all the directories in the database; make note if - // anything we scanned had changed, and rescan those things - cache_mismatch = stb__dirtree_update_db(&db, &active); - - // check the root tree - prev_dir_count = stb_arr_len(active.dirs); // record how many directories we've seen - - stb__dirtree_scandir(stripped_dir, 0, &active); // no last_modified time available for root - - if (stb__dircount_mask) - printf(" \r"); - - // done with the DB; write it back out if any changes, i.e. either - // 1. any inconsistency found between cached information and actual disk - // or 2. if scanning the root found any new directories--which we detect because - // more than one directory got added to the active db during that scan - if (cache_mismatch || stb_arr_len(active.dirs) > prev_dir_count + 1) - stb__dirtree_save_db(cache_file, &active, stripped_dir); - - free(stripped_dir); - - stb__dirtree_free_raw(&db); - - *output = active; - return output; -} - -stb_dirtree *stb_dirtree_get_dir(char *dir, char *cache_dir) -{ - int i; - stb_uint8 sha[20]; - char dir_lower[1024]; - char cache_file[1024], *s; - if (cache_dir == NULL) - return stb_dirtree_get_with_file(dir, NULL); - strcpy(dir_lower, dir); - stb_tolower(dir_lower); - stb_sha1(sha, (unsigned char *)dir_lower, strlen(dir_lower)); - strcpy(cache_file, cache_dir); - s = cache_file + strlen(cache_file); - if (s[-1] != '//' && s[-1] != '\\') *s++ = '/'; - strcpy(s, "dirtree_"); - s += strlen(s); - for (i = 0; i < 8; ++i) { - char *hex = "0123456789abcdef"; - stb_uint z = sha[i]; - *s++ = hex[z >> 4]; - *s++ = hex[z & 15]; - } - strcpy(s, ".bin"); - return stb_dirtree_get_with_file(dir, cache_file); -} - -stb_dirtree *stb_dirtree_get(char *dir) -{ - char cache_dir[256]; - strcpy(cache_dir, "c:/stb"); -#ifdef STB_HAS_REGISTRY - { - void *reg = stb_reg_open("rHKLM", "Software\\SilverSpaceship\\stb"); - if (reg) { - stb_reg_read(reg, "dirtree", cache_dir, sizeof(cache_dir)); - stb_reg_close(reg); - } - } -#endif - return stb_dirtree_get_dir(dir, cache_dir); -} - -void stb_dirtree_free(stb_dirtree *d) -{ - stb__dirtree_free_raw(d); - free(d); -} - -void stb_dirtree_db_add_dir(stb_dirtree *active, char *path, time_t last) -{ - stb__dirtree_add_dir(path, last, active); -} - -void stb_dirtree_db_add_file(stb_dirtree *active, char *name, int dir, stb_int64 size, time_t last) -{ - stb__dirtree_add_file(name, dir, size, last, active); -} - -void stb_dirtree_db_read(stb_dirtree *target, char *filename, char *dir) -{ - char *s = stb_strip_final_slash(strdup(dir)); - target->dirs = 0; - target->files = 0; - target->string_pool = 0; - stb__dirtree_load_db(filename, target, s); - free(s); -} - -void stb_dirtree_db_write(stb_dirtree *target, char *filename, char *dir) -{ - stb__dirtree_save_db(filename, target, 0); // don't strip out any directories -} - -#endif // STB_DEFINE - -#endif // _WIN32 -#endif // STB_NO_STB_STRINGS - -////////////////////////////////////////////////////////////////////////////// -// -// STB_MALLOC_WRAPPER -// -// you can use the wrapper functions with your own malloc wrapper, -// or define STB_MALLOC_WRAPPER project-wide to have -// malloc/free/realloc/strdup all get vectored to it - -// this has too many very specific error messages you could google for and find in stb.h, -// so don't use it if they don't want any stb.h-identifiable strings -#if defined(STB_DEFINE) && !defined(STB_NO_STB_STRINGS) - -typedef struct -{ - void *p; - char *file; - int line; - int size; -} stb_malloc_record; - -#ifndef STB_MALLOC_HISTORY_COUNT -#define STB_MALLOC_HISTORY_COUNT 50 // 800 bytes -#endif - -stb_malloc_record *stb__allocations; -static int stb__alloc_size, stb__alloc_limit, stb__alloc_mask; -int stb__alloc_count; - -stb_malloc_record stb__alloc_history[STB_MALLOC_HISTORY_COUNT]; -int stb__history_pos; - -static int stb__hashfind(void *p) -{ - stb_uint32 h = stb_hashptr(p); - int s, n = h & stb__alloc_mask; - if (stb__allocations[n].p == p) - return n; - s = stb_rehash(h) | 1; - for (;;) { - if (stb__allocations[n].p == NULL) - return -1; - n = (n + s) & stb__alloc_mask; - if (stb__allocations[n].p == p) - return n; - } -} - -int stb_wrapper_allocsize(void *p) -{ - int n = stb__hashfind(p); - if (n < 0) return 0; - return stb__allocations[n].size; -} - -static int stb__historyfind(void *p) -{ - int n = stb__history_pos; - int i; - for (i = 0; i < STB_MALLOC_HISTORY_COUNT; ++i) { - if (--n < 0) n = STB_MALLOC_HISTORY_COUNT - 1; - if (stb__alloc_history[n].p == p) - return n; - } - return -1; -} - -static void stb__add_alloc(void *p, int sz, char *file, int line); -static void stb__grow_alloc(void) -{ - int i, old_num = stb__alloc_size; - stb_malloc_record *old = stb__allocations; - if (stb__alloc_size == 0) - stb__alloc_size = 64; - else - stb__alloc_size *= 2; - - stb__allocations = (stb_malloc_record *)stb__realloc_raw(NULL, stb__alloc_size * sizeof(stb__allocations[0])); - if (stb__allocations == NULL) - stb_fatal("Internal error: couldn't grow malloc wrapper table"); - memset(stb__allocations, 0, stb__alloc_size * sizeof(stb__allocations[0])); - stb__alloc_limit = (stb__alloc_size * 3) >> 2; - stb__alloc_mask = stb__alloc_size - 1; - - stb__alloc_count = 0; - - for (i = 0; i < old_num; ++i) - if (old[i].p > STB_DEL) { - stb__add_alloc(old[i].p, old[i].size, old[i].file, old[i].line); - assert(stb__hashfind(old[i].p) >= 0); - } - for (i = 0; i < old_num; ++i) - if (old[i].p > STB_DEL) - assert(stb__hashfind(old[i].p) >= 0); - stb__realloc_raw(old, 0); -} - -static void stb__add_alloc(void *p, int sz, char *file, int line) -{ - stb_uint32 h; - int n; - if (stb__alloc_count >= stb__alloc_limit) - stb__grow_alloc(); - h = stb_hashptr(p); - n = h & stb__alloc_mask; - if (stb__allocations[n].p > STB_DEL) { - int s = stb_rehash(h) | 1; - do { - n = (n + s) & stb__alloc_mask; - } while (stb__allocations[n].p > STB_DEL); - } - assert(stb__allocations[n].p == NULL || stb__allocations[n].p == STB_DEL); - stb__allocations[n].p = p; - stb__allocations[n].size = sz; - stb__allocations[n].line = line; - stb__allocations[n].file = file; - ++stb__alloc_count; -} - -static void stb__remove_alloc(int n, char *file, int line) -{ - stb__alloc_history[stb__history_pos] = stb__allocations[n]; - stb__alloc_history[stb__history_pos].file = file; - stb__alloc_history[stb__history_pos].line = line; - if (++stb__history_pos == STB_MALLOC_HISTORY_COUNT) - stb__history_pos = 0; - stb__allocations[n].p = STB_DEL; - --stb__alloc_count; -} - -void stb_wrapper_malloc(void *p, int sz, char *file, int line) -{ - if (!p) return; - stb__add_alloc(p, sz, file, line); -} - -void stb_wrapper_free(void *p, char *file, int line) -{ - int n; - - if (p == NULL) return; - - n = stb__hashfind(p); - - if (n >= 0) - stb__remove_alloc(n, file, line); - else { - // tried to free something we hadn't allocated! - n = stb__historyfind(p); - assert(0); /* NOTREACHED */ - if (n >= 0) - stb_fatal("Attempted to free %d-byte block %p at %s:%d previously freed/realloced at %s:%d", - stb__alloc_history[n].size, p, - file, line, - stb__alloc_history[n].file, stb__alloc_history[n].line); - else - stb_fatal("Attempted to free unknown block %p at %s:%d", p, file, line); - } -} - -void stb_wrapper_check(void *p) -{ - int n; - - if (p == NULL) return; - - n = stb__hashfind(p); - - if (n >= 0) return; - - for (n = 0; n < stb__alloc_size; ++n) - if (stb__allocations[n].p == p) - stb_fatal("Internal error: pointer %p was allocated, but hash search failed", p); - - // tried to free something that wasn't allocated! - n = stb__historyfind(p); - if (n >= 0) - stb_fatal("Checked %d-byte block %p previously freed/realloced at %s:%d", - stb__alloc_history[n].size, p, - stb__alloc_history[n].file, stb__alloc_history[n].line); - stb_fatal("Checked unknown block %p"); -} - -void stb_wrapper_realloc(void *p, void *q, int sz, char *file, int line) -{ - int n; - if (p == NULL) { stb_wrapper_malloc(q, sz, file, line); return; } - if (q == NULL) return; // nothing happened - - n = stb__hashfind(p); - if (n == -1) { - // tried to free something we hadn't allocated! - // this is weird, though, because we got past the realloc! - n = stb__historyfind(p); - assert(0); /* NOTREACHED */ - if (n >= 0) - stb_fatal("Attempted to realloc %d-byte block %p at %s:%d previously freed/realloced at %s:%d", - stb__alloc_history[n].size, p, - file, line, - stb__alloc_history[n].file, stb__alloc_history[n].line); - else - stb_fatal("Attempted to realloc unknown block %p at %s:%d", p, file, line); - } - else { - if (q == p) { - stb__allocations[n].size = sz; - stb__allocations[n].file = file; - stb__allocations[n].line = line; - } - else { - stb__remove_alloc(n, file, line); - stb__add_alloc(q, sz, file, line); - } - } -} - -void stb_wrapper_listall(void(*func)(void *ptr, int sz, char *file, int line)) -{ - int i; - for (i = 0; i < stb__alloc_size; ++i) - if (stb__allocations[i].p > STB_DEL) - func(stb__allocations[i].p, stb__allocations[i].size, - stb__allocations[i].file, stb__allocations[i].line); -} - -void stb_wrapper_dump(char *filename) -{ - int i; - FILE *f = fopen(filename, "w"); - if (!f) return; - for (i = 0; i < stb__alloc_size; ++i) - if (stb__allocations[i].p > STB_DEL) - fprintf(f, "%p %7d - %4d %s\n", - stb__allocations[i].p, stb__allocations[i].size, - stb__allocations[i].line, stb__allocations[i].file); -} -#endif // STB_DEFINE - - -////////////////////////////////////////////////////////////////////////////// -// -// stb_pointer_set -// -// -// For data structures that support querying by key, data structure -// classes always hand-wave away the issue of what to do if two entries -// have the same key: basically, store a linked list of all the nodes -// which have the same key (a LISP-style list). -// -// The thing is, it's not that trivial. If you have an O(log n) -// lookup data structure, but then n/4 items have the same value, -// you don't want to spend O(n) time scanning that list when -// deleting an item if you already have a pointer to the item. -// (You have to spend O(n) time enumerating all the items with -// a given key, sure, and you can't accelerate deleting a particular -// item if you only have the key, not a pointer to the item.) -// -// I'm going to call this data structure, whatever it turns out to -// be, a "pointer set", because we don't store any associated data for -// items in this data structure, we just answer the question of -// whether an item is in it or not (it's effectively one bit per pointer). -// Technically they don't have to be pointers; you could cast ints -// to (void *) if you want, but you can't store 0 or 1 because of the -// hash table. -// -// Since the fastest data structure we might want to add support for -// identical-keys to is a hash table with O(1)-ish lookup time, -// that means that the conceptual "linked list of all items with -// the same indexed value" that we build needs to have the same -// performance; that way when we index a table we think is arbitrary -// ints, but in fact half of them are 0, we don't get screwed. -// -// Therefore, it needs to be a hash table, at least when it gets -// large. On the other hand, when the data has totally arbitrary ints -// or floats, there won't be many collisions, and we'll have tons of -// 1-item bitmaps. That will be grossly inefficient as hash tables; -// trade-off; the hash table is reasonably efficient per-item when -// it's large, but not when it's small. So we need to do something -// Judy-like and use different strategies depending on the size. -// -// Like Judy, we'll use the bottom bit to encode the strategy: -// -// bottom bits: -// 00 - direct pointer -// 01 - 4-item bucket (16 bytes, no length, NULLs) -// 10 - N-item array -// 11 - hash table - -typedef struct stb_ps stb_ps; - -STB_EXTERN int stb_ps_find(stb_ps *ps, void *value); -STB_EXTERN stb_ps * stb_ps_add(stb_ps *ps, void *value); -STB_EXTERN stb_ps * stb_ps_remove(stb_ps *ps, void *value); -STB_EXTERN stb_ps * stb_ps_remove_any(stb_ps *ps, void **value); -STB_EXTERN void stb_ps_delete(stb_ps *ps); -STB_EXTERN int stb_ps_count(stb_ps *ps); - -STB_EXTERN stb_ps * stb_ps_copy(stb_ps *ps); -STB_EXTERN int stb_ps_subset(stb_ps *bigger, stb_ps *smaller); -STB_EXTERN int stb_ps_eq(stb_ps *p0, stb_ps *p1); - -STB_EXTERN void ** stb_ps_getlist(stb_ps *ps, int *count); -STB_EXTERN int stb_ps_writelist(stb_ps *ps, void **list, int size); - -// enum and fastlist don't allocate storage, but you must consume the -// list before there's any chance the data structure gets screwed up; -STB_EXTERN int stb_ps_enum(stb_ps *ps, void *data, - int(*func)(void *value, void*data)); -STB_EXTERN void ** stb_ps_fastlist(stb_ps *ps, int *count); -// result: -// returns a list, *count is the length of that list, -// but some entries of the list may be invalid; -// test with 'stb_ps_fastlist_valid(x)' - -#define stb_ps_fastlist_valid(x) ((stb_uinta) (x) > 1) - -#ifdef STB_DEFINE - -enum -{ - STB_ps_direct = 0, - STB_ps_bucket = 1, - STB_ps_array = 2, - STB_ps_hash = 3, -}; - -#define STB_BUCKET_SIZE 4 - -typedef struct -{ - void *p[STB_BUCKET_SIZE]; -} stb_ps_bucket; -#define GetBucket(p) ((stb_ps_bucket *) ((char *) (p) - STB_ps_bucket)) -#define EncodeBucket(p) ((stb_ps *) ((char *) (p) + STB_ps_bucket)) - -static void stb_bucket_free(stb_ps_bucket *b) -{ - free(b); -} - -static stb_ps_bucket *stb_bucket_create2(void *v0, void *v1) -{ - stb_ps_bucket *b = (stb_ps_bucket*)malloc(sizeof(*b)); - b->p[0] = v0; - b->p[1] = v1; - b->p[2] = NULL; - b->p[3] = NULL; - return b; -} - -static stb_ps_bucket * stb_bucket_create3(void **v) -{ - stb_ps_bucket *b = (stb_ps_bucket*)malloc(sizeof(*b)); - b->p[0] = v[0]; - b->p[1] = v[1]; - b->p[2] = v[2]; - b->p[3] = NULL; - return b; -} - - -// could use stb_arr, but this will save us memory -typedef struct -{ - int count; - void *p[1]; -} stb_ps_array; -#define GetArray(p) ((stb_ps_array *) ((char *) (p) - STB_ps_array)) -#define EncodeArray(p) ((stb_ps *) ((char *) (p) + STB_ps_array)) - -static int stb_ps_array_max = 13; - -typedef struct -{ - int size, mask; - int count, count_deletes; - int grow_threshhold; - int shrink_threshhold; - int rehash_threshhold; - int any_offset; - void *table[1]; -} stb_ps_hash; -#define GetHash(p) ((stb_ps_hash *) ((char *) (p) - STB_ps_hash)) -#define EncodeHash(p) ((stb_ps *) ((char *) (p) + STB_ps_hash)) - -#define stb_ps_empty(v) (((stb_uint32) v) <= 1) - -static stb_ps_hash *stb_ps_makehash(int size, int old_size, void **old_data) -{ - int i; - stb_ps_hash *h = (stb_ps_hash *)malloc(sizeof(*h) + (size - 1) * sizeof(h->table[0])); - assert(stb_is_pow2(size)); - h->size = size; - h->mask = size - 1; - h->shrink_threshhold = (int)(0.3f * size); - h->grow_threshhold = (int)(0.8f * size); - h->rehash_threshhold = (int)(0.9f * size); - h->count = 0; - h->count_deletes = 0; - h->any_offset = 0; - memset(h->table, 0, size * sizeof(h->table[0])); - for (i = 0; i < old_size; ++i) - if (!stb_ps_empty((size_t)old_data[i])) - stb_ps_add(EncodeHash(h), old_data[i]); - return h; -} - -void stb_ps_delete(stb_ps *ps) -{ - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: break; - case STB_ps_bucket: stb_bucket_free(GetBucket(ps)); break; - case STB_ps_array: free(GetArray(ps)); break; - case STB_ps_hash: free(GetHash(ps)); break; - } -} - -stb_ps *stb_ps_copy(stb_ps *ps) -{ - int i; - // not a switch: order based on expected performance/power-law distribution - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: return ps; - case STB_ps_bucket: { - stb_ps_bucket *n = (stb_ps_bucket *)malloc(sizeof(*n)); - *n = *GetBucket(ps); - return EncodeBucket(n); - } - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - stb_ps_array *n = (stb_ps_array *)malloc(sizeof(*n) + stb_ps_array_max * sizeof(n->p[0])); - n->count = a->count; - for (i = 0; i < a->count; ++i) - n->p[i] = a->p[i]; - return EncodeArray(n); - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - stb_ps_hash *n = stb_ps_makehash(h->size, h->size, h->table); - return EncodeHash(n); - } - } - assert(0); /* NOTREACHED */ - return NULL; -} - -int stb_ps_find(stb_ps *ps, void *value) -{ - int i, code = 3 & (int)(size_t)ps; - assert((3 & (int)(size_t)value) == STB_ps_direct); - assert(stb_ps_fastlist_valid(value)); - // not a switch: order based on expected performance/power-law distribution - if (code == STB_ps_direct) - return value == ps; - if (code == STB_ps_bucket) { - stb_ps_bucket *b = GetBucket(ps); - assert(STB_BUCKET_SIZE == 4); - if (b->p[0] == value || b->p[1] == value || - b->p[2] == value || b->p[3] == value) - return STB_TRUE; - return STB_FALSE; - } - if (code == STB_ps_array) { - stb_ps_array *a = GetArray(ps); - for (i = 0; i < a->count; ++i) - if (a->p[i] == value) - return STB_TRUE; - return STB_FALSE; - } - else { - stb_ps_hash *h = GetHash(ps); - stb_uint32 hash = stb_hashptr(value); - stb_uint32 s, n = hash & h->mask; - void **t = h->table; - if (t[n] == value) return STB_TRUE; - if (t[n] == NULL) return STB_FALSE; - s = stb_rehash(hash) | 1; - do { - n = (n + s) & h->mask; - if (t[n] == value) return STB_TRUE; - } while (t[n] != NULL); - return STB_FALSE; - } -} - -stb_ps * stb_ps_add(stb_ps *ps, void *value) -{ -#ifdef STB_DEBUG - assert(!stb_ps_find(ps, value)); -#endif - if (value == NULL) return ps; // ignore NULL adds to avoid bad breakage - assert((3 & (int)(size_t)value) == STB_ps_direct); - assert(stb_ps_fastlist_valid(value)); - assert(value != STB_DEL); // STB_DEL is less likely - - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: - if (ps == NULL) return (stb_ps *)value; - return EncodeBucket(stb_bucket_create2(ps, value)); - - case STB_ps_bucket: { - stb_ps_bucket *b = GetBucket(ps); - stb_ps_array *a; - assert(STB_BUCKET_SIZE == 4); - if (b->p[0] == NULL) { b->p[0] = value; return ps; } - if (b->p[1] == NULL) { b->p[1] = value; return ps; } - if (b->p[2] == NULL) { b->p[2] = value; return ps; } - if (b->p[3] == NULL) { b->p[3] = value; return ps; } - a = (stb_ps_array *)malloc(sizeof(*a) + 7 * sizeof(a->p[0])); // 8 slots, must be 2^k - memcpy(a->p, b, sizeof(*b)); - a->p[4] = value; - a->count = 5; - stb_bucket_free(b); - return EncodeArray(a); - } - - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - if (a->count == stb_ps_array_max) { - // promote from array to hash - stb_ps_hash *h = stb_ps_makehash(2 << stb_log2_ceil(a->count), a->count, a->p); - free(a); - return stb_ps_add(EncodeHash(h), value); - } - // do we need to resize the array? the array doubles in size when it - // crosses a power-of-two - if ((a->count & (a->count - 1)) == 0) { - int newsize = a->count * 2; - // clamp newsize to max if: - // 1. it's larger than max - // 2. newsize*1.5 is larger than max (to avoid extra resizing) - if (newsize + a->count > stb_ps_array_max) - newsize = stb_ps_array_max; - a = (stb_ps_array *)realloc(a, sizeof(*a) + (newsize - 1) * sizeof(a->p[0])); - } - a->p[a->count++] = value; - return EncodeArray(a); - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - stb_uint32 hash = stb_hashptr(value); - stb_uint32 n = hash & h->mask; - void **t = h->table; - // find first NULL or STB_DEL entry - if (!stb_ps_empty((size_t)t[n])) { - stb_uint32 s = stb_rehash(hash) | 1; - do { - n = (n + s) & h->mask; - } while (!stb_ps_empty((size_t)t[n])); - } - if (t[n] == STB_DEL) - --h->count_deletes; - t[n] = value; - ++h->count; - if (h->count == h->grow_threshhold) { - stb_ps_hash *h2 = stb_ps_makehash(h->size * 2, h->size, t); - free(h); - return EncodeHash(h2); - } - if (h->count + h->count_deletes == h->rehash_threshhold) { - stb_ps_hash *h2 = stb_ps_makehash(h->size, h->size, t); - free(h); - return EncodeHash(h2); - } - return ps; - } - } - return NULL; /* NOTREACHED */ -} - -stb_ps *stb_ps_remove(stb_ps *ps, void *value) -{ -#ifdef STB_DEBUG - assert(stb_ps_find(ps, value)); -#endif - assert((3 & (int)(size_t)value) == STB_ps_direct); - if (value == NULL) return ps; // ignore NULL removes to avoid bad breakage - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: - return ps == value ? NULL : ps; - case STB_ps_bucket: { - stb_ps_bucket *b = GetBucket(ps); - int count = 0; - assert(STB_BUCKET_SIZE == 4); - if (b->p[0] == value) b->p[0] = NULL; else count += (b->p[0] != NULL); - if (b->p[1] == value) b->p[1] = NULL; else count += (b->p[1] != NULL); - if (b->p[2] == value) b->p[2] = NULL; else count += (b->p[2] != NULL); - if (b->p[3] == value) b->p[3] = NULL; else count += (b->p[3] != NULL); - if (count == 1) { // shrink bucket at size 1 - value = b->p[0]; - if (value == NULL) value = b->p[1]; - if (value == NULL) value = b->p[2]; - if (value == NULL) value = b->p[3]; - assert(value != NULL); - stb_bucket_free(b); - return (stb_ps *)value; // return STB_ps_direct of value - } - return ps; - } - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - int i; - for (i = 0; i < a->count; ++i) { - if (a->p[i] == value) { - a->p[i] = a->p[--a->count]; - if (a->count == 3) { // shrink to bucket! - stb_ps_bucket *b = stb_bucket_create3(a->p); - free(a); - return EncodeBucket(b); - } - return ps; - } - } - return ps; - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - stb_uint32 hash = stb_hashptr(value); - stb_uint32 s, n = hash & h->mask; - void **t = h->table; - if (t[n] != value) { - s = stb_rehash(hash) | 1; - do { - n = (n + s) & h->mask; - } while (t[n] != value); - } - t[n] = STB_DEL; - --h->count; - ++h->count_deletes; - // should we shrink down to an array? - if (h->count < stb_ps_array_max) { - int n = 1 << stb_log2_floor(stb_ps_array_max); - if (h->count < n) { - stb_ps_array *a = (stb_ps_array *)malloc(sizeof(*a) + (n - 1) * sizeof(a->p[0])); - int i, j = 0; - for (i = 0; i < h->size; ++i) - if (!stb_ps_empty((size_t)t[i])) - a->p[j++] = t[i]; - assert(j == h->count); - a->count = j; - free(h); - return EncodeArray(a); - } - } - if (h->count == h->shrink_threshhold) { - stb_ps_hash *h2 = stb_ps_makehash(h->size >> 1, h->size, t); - free(h); - return EncodeHash(h2); - } - return ps; - } - } - return ps; /* NOTREACHED */ -} - -stb_ps *stb_ps_remove_any(stb_ps *ps, void **value) -{ - assert(ps != NULL); - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: - *value = ps; - return NULL; - case STB_ps_bucket: { - stb_ps_bucket *b = GetBucket(ps); - int count = 0, slast = 0, last = 0; - assert(STB_BUCKET_SIZE == 4); - if (b->p[0]) { ++count; last = 0; } - if (b->p[1]) { ++count; slast = last; last = 1; } - if (b->p[2]) { ++count; slast = last; last = 2; } - if (b->p[3]) { ++count; slast = last; last = 3; } - *value = b->p[last]; - b->p[last] = 0; - if (count == 2) { - void *leftover = b->p[slast]; // second to last - stb_bucket_free(b); - return (stb_ps *)leftover; - } - return ps; - } - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - *value = a->p[a->count - 1]; - if (a->count == 4) - return stb_ps_remove(ps, *value); - --a->count; - return ps; - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - void **t = h->table; - stb_uint32 n = h->any_offset; - while (stb_ps_empty((size_t)t[n])) - n = (n + 1) & h->mask; - *value = t[n]; - h->any_offset = (n + 1) & h->mask; - // check if we need to skip down to the previous type - if (h->count - 1 < stb_ps_array_max || h->count - 1 == h->shrink_threshhold) - return stb_ps_remove(ps, *value); - t[n] = STB_DEL; - --h->count; - ++h->count_deletes; - return ps; - } - } - return ps; /* NOTREACHED */ -} - - -void ** stb_ps_getlist(stb_ps *ps, int *count) -{ - int i, n = 0; - void **p = NULL; - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: - if (ps == NULL) { *count = 0; return NULL; } - p = (void **)malloc(sizeof(*p) * 1); - p[0] = ps; - *count = 1; - return p; - case STB_ps_bucket: { - stb_ps_bucket *b = GetBucket(ps); - p = (void **)malloc(sizeof(*p) * STB_BUCKET_SIZE); - for (i = 0; i < STB_BUCKET_SIZE; ++i) - if (b->p[i] != NULL) - p[n++] = b->p[i]; - break; - } - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - p = (void **)malloc(sizeof(*p) * a->count); - memcpy(p, a->p, sizeof(*p) * a->count); - *count = a->count; - return p; - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - p = (void **)malloc(sizeof(*p) * h->count); - for (i = 0; i < h->size; ++i) - if (!stb_ps_empty((size_t)h->table[i])) - p[n++] = h->table[i]; - break; - } - } - *count = n; - return p; -} - -int stb_ps_writelist(stb_ps *ps, void **list, int size) -{ - int i, n = 0; - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: - if (ps == NULL || size <= 0) return 0; - list[0] = ps; - return 1; - case STB_ps_bucket: { - stb_ps_bucket *b = GetBucket(ps); - for (i = 0; i < STB_BUCKET_SIZE; ++i) - if (b->p[i] != NULL && n < size) - list[n++] = b->p[i]; - return n; - } - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - n = stb_min(size, a->count); - memcpy(list, a->p, sizeof(*list) * n); - return n; - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - if (size <= 0) return 0; - for (i = 0; i < h->count; ++i) { - if (!stb_ps_empty((size_t)h->table[i])) { - list[n++] = h->table[i]; - if (n == size) break; - } - } - return n; - } - } - return 0; /* NOTREACHED */ -} - -int stb_ps_enum(stb_ps *ps, void *data, int(*func)(void *value, void *data)) -{ - int i; - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: - if (ps == NULL) return STB_TRUE; - return func(ps, data); - case STB_ps_bucket: { - stb_ps_bucket *b = GetBucket(ps); - for (i = 0; i < STB_BUCKET_SIZE; ++i) - if (b->p[i] != NULL) - if (!func(b->p[i], data)) - return STB_FALSE; - return STB_TRUE; - } - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - for (i = 0; i < a->count; ++i) - if (!func(a->p[i], data)) - return STB_FALSE; - return STB_TRUE; - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - for (i = 0; i < h->count; ++i) - if (!stb_ps_empty((size_t)h->table[i])) - if (!func(h->table[i], data)) - return STB_FALSE; - return STB_TRUE; - } - } - return STB_TRUE; /* NOTREACHED */ -} - -int stb_ps_count(stb_ps *ps) -{ - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: - return ps != NULL; - case STB_ps_bucket: { - stb_ps_bucket *b = GetBucket(ps); - return (b->p[0] != NULL) + (b->p[1] != NULL) + - (b->p[2] != NULL) + (b->p[3] != NULL); - } - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - return a->count; - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - return h->count; - } - } - return 0; -} - -void ** stb_ps_fastlist(stb_ps *ps, int *count) -{ - static void *storage; - - switch (3 & (int)(size_t)ps) { - case STB_ps_direct: - if (ps == NULL) { *count = 0; return NULL; } - storage = ps; - *count = 1; - return &storage; - case STB_ps_bucket: { - stb_ps_bucket *b = GetBucket(ps); - *count = STB_BUCKET_SIZE; - return b->p; - } - case STB_ps_array: { - stb_ps_array *a = GetArray(ps); - *count = a->count; - return a->p; - } - case STB_ps_hash: { - stb_ps_hash *h = GetHash(ps); - *count = h->size; - return h->table; - } - } - return NULL; /* NOTREACHED */ -} - -int stb_ps_subset(stb_ps *bigger, stb_ps *smaller) -{ - int i, listlen; - void **list = stb_ps_fastlist(smaller, &listlen); - for (i = 0; i < listlen; ++i) - if (stb_ps_fastlist_valid(list[i])) - if (!stb_ps_find(bigger, list[i])) - return 0; - return 1; -} - -int stb_ps_eq(stb_ps *p0, stb_ps *p1) -{ - if (stb_ps_count(p0) != stb_ps_count(p1)) - return 0; - return stb_ps_subset(p0, p1); -} - -#undef GetBucket -#undef GetArray -#undef GetHash - -#undef EncodeBucket -#undef EncodeArray -#undef EncodeHash - -#endif - - -////////////////////////////////////////////////////////////////////////////// -// -// Random Numbers via Meresenne Twister or LCG -// - -STB_EXTERN unsigned long stb_srandLCG(unsigned long seed); -STB_EXTERN unsigned long stb_randLCG(void); -STB_EXTERN double stb_frandLCG(void); - -STB_EXTERN void stb_srand(unsigned long seed); -STB_EXTERN unsigned long stb_rand(void); -STB_EXTERN double stb_frand(void); -STB_EXTERN void stb_shuffle(void *p, size_t n, size_t sz, - unsigned long seed); -STB_EXTERN void stb_reverse(void *p, size_t n, size_t sz); - -STB_EXTERN unsigned long stb_randLCG_explicit(unsigned long seed); - -#define stb_rand_define(x,y) \ - \ - unsigned long x(void) \ - { \ - static unsigned long stb__rand = y; \ - stb__rand = stb__rand * 2147001325 + 715136305; /* BCPL */ \ - return 0x31415926 ^ ((stb__rand >> 16) + (stb__rand << 16)); \ - } - -#ifdef STB_DEFINE -unsigned long stb_randLCG_explicit(unsigned long seed) -{ - return seed * 2147001325 + 715136305; -} - -static unsigned long stb__rand_seed = 0; - -unsigned long stb_srandLCG(unsigned long seed) -{ - unsigned long previous = stb__rand_seed; - stb__rand_seed = seed; - return previous; -} - -unsigned long stb_randLCG(void) -{ - stb__rand_seed = stb__rand_seed * 2147001325 + 715136305; // BCPL generator - // shuffle non-random bits to the middle, and xor to decorrelate with seed - return 0x31415926 ^ ((stb__rand_seed >> 16) + (stb__rand_seed << 16)); -} - -double stb_frandLCG(void) -{ - return stb_randLCG() / ((double)(1 << 16) * (1 << 16)); -} - -void stb_shuffle(void *p, size_t n, size_t sz, unsigned long seed) -{ - char *a; - unsigned long old_seed; - int i; - if (seed) - old_seed = stb_srandLCG(seed); - a = (char *)p + (n - 1) * sz; - - for (i = n; i > 1; --i) { - int j = stb_randLCG() % i; - stb_swap(a, (char *)p + j * sz, sz); - a -= sz; - } - if (seed) - stb_srandLCG(old_seed); -} - -void stb_reverse(void *p, size_t n, size_t sz) -{ - int i, j = n - 1; - for (i = 0; i < j; ++i, --j) { - stb_swap((char *)p + i * sz, (char *)p + j * sz, sz); - } -} - -// public domain Mersenne Twister by Michael Brundage -#define STB__MT_LEN 624 - -int stb__mt_index = STB__MT_LEN * sizeof(unsigned long) + 1; -unsigned long stb__mt_buffer[STB__MT_LEN]; - -void stb_srand(unsigned long seed) -{ - int i; - unsigned long old = stb_srandLCG(seed); - for (i = 0; i < STB__MT_LEN; i++) - stb__mt_buffer[i] = stb_randLCG(); - stb_srandLCG(old); - stb__mt_index = STB__MT_LEN * sizeof(unsigned long); -} - -#define STB__MT_IA 397 -#define STB__MT_IB (STB__MT_LEN - STB__MT_IA) -#define STB__UPPER_MASK 0x80000000 -#define STB__LOWER_MASK 0x7FFFFFFF -#define STB__MATRIX_A 0x9908B0DF -#define STB__TWIST(b,i,j) ((b)[i] & STB__UPPER_MASK) | ((b)[j] & STB__LOWER_MASK) -#define STB__MAGIC(s) (((s)&1)*STB__MATRIX_A) - -unsigned long stb_rand() -{ - unsigned long * b = stb__mt_buffer; - int idx = stb__mt_index; - unsigned long s, r; - int i; - - if (idx >= STB__MT_LEN * sizeof(unsigned long)) { - if (idx > STB__MT_LEN * sizeof(unsigned long)) - stb_srand(0); - idx = 0; - i = 0; - for (; i < STB__MT_IB; i++) { - s = STB__TWIST(b, i, i + 1); - b[i] = b[i + STB__MT_IA] ^ (s >> 1) ^ STB__MAGIC(s); - } - for (; i < STB__MT_LEN - 1; i++) { - s = STB__TWIST(b, i, i + 1); - b[i] = b[i - STB__MT_IB] ^ (s >> 1) ^ STB__MAGIC(s); - } - - s = STB__TWIST(b, STB__MT_LEN - 1, 0); - b[STB__MT_LEN - 1] = b[STB__MT_IA - 1] ^ (s >> 1) ^ STB__MAGIC(s); - } - stb__mt_index = idx + sizeof(unsigned long); - - r = *(unsigned long *)((unsigned char *)b + idx); - - r ^= (r >> 11); - r ^= (r << 7) & 0x9D2C5680; - r ^= (r << 15) & 0xEFC60000; - r ^= (r >> 18); - - return r; -} - -double stb_frand(void) -{ - return stb_rand() / ((double)(1 << 16) * (1 << 16)); -} - -#endif - - -////////////////////////////////////////////////////////////////////////////// -// -// stb_dupe -// -// stb_dupe is a duplicate-finding system for very, very large data -// structures--large enough that sorting is too slow, but not so large -// that we can't keep all the data in memory. using it works as follows: -// -// 1. create an stb_dupe: -// provide a hash function -// provide an equality function -// provide an estimate for the size -// optionally provide a comparison function -// -// 2. traverse your data, 'adding' pointers to the stb_dupe -// -// 3. finish and ask for duplicates -// -// the stb_dupe will discard its intermediate data and build -// a collection of sorted lists of duplicates, with non-duplicate -// entries omitted entirely -// -// -// Implementation strategy: -// -// while collecting the N items, we keep a hash table of approximate -// size sqrt(N). (if you tell use the N up front, the hash table is -// just that size exactly) -// -// each entry in the hash table is just an stb__arr of pointers (no need -// to use stb_ps, because we don't need to delete from these) -// -// for step 3, for each entry in the hash table, we apply stb_dupe to it -// recursively. once the size gets small enough (or doesn't decrease -// significantly), we switch to either using qsort() on the comparison -// function, or else we just do the icky N^2 gather - - -typedef struct stb_dupe stb_dupe; - -typedef int(*stb_compare_func)(void *a, void *b); -typedef int(*stb_hash_func)(void *a, unsigned int seed); - -STB_EXTERN void stb_dupe_free(stb_dupe *sd); -STB_EXTERN stb_dupe *stb_dupe_create(stb_hash_func hash, - stb_compare_func eq, int size, stb_compare_func ineq); -STB_EXTERN void stb_dupe_add(stb_dupe *sd, void *item); -STB_EXTERN void stb_dupe_finish(stb_dupe *sd); -STB_EXTERN int stb_dupe_numsets(stb_dupe *sd); -STB_EXTERN void **stb_dupe_set(stb_dupe *sd, int num); -STB_EXTERN int stb_dupe_set_count(stb_dupe *sd, int num); - -struct stb_dupe -{ - void ***hash_table; - int hash_size; - int size_log2; - int population; - - int hash_shift; - stb_hash_func hash; - - stb_compare_func eq; - stb_compare_func ineq; - - void ***dupes; -}; - -#ifdef STB_DEFINE - -int stb_dupe_numsets(stb_dupe *sd) -{ - assert(sd->hash_table == NULL); - return stb_arr_len(sd->dupes); -} - -void **stb_dupe_set(stb_dupe *sd, int num) -{ - assert(sd->hash_table == NULL); - return sd->dupes[num]; -} - -int stb_dupe_set_count(stb_dupe *sd, int num) -{ - assert(sd->hash_table == NULL); - return stb_arr_len(sd->dupes[num]); -} - -stb_dupe *stb_dupe_create(stb_hash_func hash, stb_compare_func eq, int size, - stb_compare_func ineq) -{ - int i, hsize; - stb_dupe *sd = (stb_dupe *)malloc(sizeof(*sd)); - - sd->size_log2 = 4; - hsize = 1 << sd->size_log2; - while (hsize * hsize < size) { - ++sd->size_log2; - hsize *= 2; - } - - sd->hash = hash; - sd->eq = eq; - sd->ineq = ineq; - sd->hash_shift = 0; - - sd->population = 0; - sd->hash_size = hsize; - sd->hash_table = (void ***)malloc(sizeof(*sd->hash_table) * hsize); - for (i = 0; i < hsize; ++i) - sd->hash_table[i] = NULL; - - sd->dupes = NULL; - - return sd; -} - -void stb_dupe_add(stb_dupe *sd, void *item) -{ - stb_uint32 hash = sd->hash(item, sd->hash_shift); - int z = hash & (sd->hash_size - 1); - stb_arr_push(sd->hash_table[z], item); - ++sd->population; -} - -void stb_dupe_free(stb_dupe *sd) -{ - int i; - for (i = 0; i < stb_arr_len(sd->dupes); ++i) - if (sd->dupes[i]) - stb_arr_free(sd->dupes[i]); - stb_arr_free(sd->dupes); - free(sd); -} - -static stb_compare_func stb__compare; - -static int stb__dupe_compare(const void *a, const void *b) -{ - void *p = *(void **)a; - void *q = *(void **)b; - - return stb__compare(p, q); -} - -void stb_dupe_finish(stb_dupe *sd) -{ - int i, j, k; - assert(sd->dupes == NULL); - for (i = 0; i < sd->hash_size; ++i) { - void ** list = sd->hash_table[i]; - if (list != NULL) { - int n = stb_arr_len(list); - // @TODO: measure to find good numbers instead of just making them up! - int thresh = (sd->ineq ? 200 : 20); - // if n is large enough to be worth it, and n is smaller than - // before (so we can guarantee we'll use a smaller hash table); - // and there are enough hash bits left, assuming full 32-bit hash - if (n > thresh && n < (sd->population >> 3) && sd->hash_shift + sd->size_log2 * 2 < 32) { - - // recursively process this row using stb_dupe, O(N log log N) - - stb_dupe *d = stb_dupe_create(sd->hash, sd->eq, n, sd->ineq); - d->hash_shift = stb_randLCG_explicit(sd->hash_shift); - for (j = 0; j < n; ++j) - stb_dupe_add(d, list[j]); - stb_arr_free(sd->hash_table[i]); - stb_dupe_finish(d); - for (j = 0; j < stb_arr_len(d->dupes); ++j) { - stb_arr_push(sd->dupes, d->dupes[j]); - d->dupes[j] = NULL; // take over ownership - } - stb_dupe_free(d); - - } - else if (sd->ineq) { - - // process this row using qsort(), O(N log N) - stb__compare = sd->ineq; - qsort(list, n, sizeof(list[0]), stb__dupe_compare); - - // find equal subsequences of the list - for (j = 0; j < n - 1; ) { - // find a subsequence from j..k - for (k = j; k < n; ++k) - // only use ineq so eq can be left undefined - if (sd->ineq(list[j], list[k])) - break; - // k is the first one not in the subsequence - if (k - j > 1) { - void **mylist = NULL; - stb_arr_setlen(mylist, k - j); - memcpy(mylist, list + j, sizeof(list[j]) * (k - j)); - stb_arr_push(sd->dupes, mylist); - } - j = k; - } - stb_arr_free(sd->hash_table[i]); - } - else { - - // process this row using eq(), O(N^2) - for (j = 0; j < n; ++j) { - if (list[j] != NULL) { - void **output = NULL; - for (k = j + 1; k < n; ++k) { - if (sd->eq(list[j], list[k])) { - if (output == NULL) - stb_arr_push(output, list[j]); - stb_arr_push(output, list[k]); - list[k] = NULL; - } - } - list[j] = NULL; - if (output) - stb_arr_push(sd->dupes, output); - } - } - stb_arr_free(sd->hash_table[i]); - } - } - } - free(sd->hash_table); - sd->hash_table = NULL; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// templatized Sort routine -// -// This is an attempt to implement a templated sorting algorithm. -// To use it, you have to explicitly instantiate it as a _function_, -// then you call that function. This allows the comparison to be inlined, -// giving the sort similar performance to C++ sorts. -// -// It implements quicksort with three-way-median partitioning (generally -// well-behaved), with a final insertion sort pass. -// -// When you define the compare expression, you should assume you have -// elements of your array pointed to by 'a' and 'b', and perform the comparison -// on those. OR you can use one or more statements; first say '0;', then -// write whatever code you want, and compute the result into a variable 'c'. - -#define stb_declare_sort(FUNCNAME, TYPE) \ - void FUNCNAME(TYPE *p, int n) -#define stb_define_sort(FUNCNAME,TYPE,COMPARE) \ - stb__define_sort( void, FUNCNAME,TYPE,COMPARE) -#define stb_define_sort_static(FUNCNAME,TYPE,COMPARE) \ - stb__define_sort(static void, FUNCNAME,TYPE,COMPARE) - -#define stb__define_sort(MODE, FUNCNAME, TYPE, COMPARE) \ - \ -static void STB_(FUNCNAME,_ins_sort)(TYPE *p, int n) \ -{ \ - int i,j; \ - for (i=1; i < n; ++i) { \ - TYPE t = p[i], *a = &t; \ - j = i; \ - while (j > 0) { \ - TYPE *b = &p[j-1]; \ - int c = COMPARE; \ - if (!c) break; \ - p[j] = p[j-1]; \ - --j; \ - } \ - if (i != j) \ - p[j] = t; \ - } \ -} \ - \ -static void STB_(FUNCNAME,_quicksort)(TYPE *p, int n) \ -{ \ - /* threshhold for transitioning to insertion sort */ \ - while (n > 12) { \ - TYPE *a,*b,t; \ - int c01,c12,c,m,i,j; \ - \ - /* compute median of three */ \ - m = n >> 1; \ - a = &p[0]; \ - b = &p[m]; \ - c = COMPARE; \ - c01 = c; \ - a = &p[m]; \ - b = &p[n-1]; \ - c = COMPARE; \ - c12 = c; \ - /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ \ - if (c01 != c12) { \ - /* otherwise, we'll need to swap something else to middle */ \ - int z; \ - a = &p[0]; \ - b = &p[n-1]; \ - c = COMPARE; \ - /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ \ - /* 0<mid && mid>n: 0>n => 0; 0<n => n */ \ - z = (c == c12) ? 0 : n-1; \ - t = p[z]; \ - p[z] = p[m]; \ - p[m] = t; \ - } \ - /* now p[m] is the median-of-three */ \ - /* swap it to the beginning so it won't move around */ \ - t = p[0]; \ - p[0] = p[m]; \ - p[m] = t; \ - \ - /* partition loop */ \ - i=1; \ - j=n-1; \ - for(;;) { \ - /* handling of equality is crucial here */ \ - /* for sentinels & efficiency with duplicates */ \ - b = &p[0]; \ - for (;;++i) { \ - a=&p[i]; \ - c = COMPARE; \ - if (!c) break; \ - } \ - a = &p[0]; \ - for (;;--j) { \ - b=&p[j]; \ - c = COMPARE; \ - if (!c) break; \ - } \ - /* make sure we haven't crossed */ \ - if (i >= j) break; \ - t = p[i]; \ - p[i] = p[j]; \ - p[j] = t; \ - \ - ++i; \ - --j; \ - } \ - /* recurse on smaller side, iterate on larger */ \ - if (j < (n-i)) { \ - STB_(FUNCNAME,_quicksort)(p,j); \ - p = p+i; \ - n = n-i; \ - } else { \ - STB_(FUNCNAME,_quicksort)(p+i, n-i); \ - n = j; \ - } \ - } \ -} \ - \ -MODE FUNCNAME(TYPE *p, int n) \ -{ \ - STB_(FUNCNAME, _quicksort)(p, n); \ - STB_(FUNCNAME, _ins_sort)(p, n); \ -} \ - - -////////////////////////////////////////////////////////////////////////////// -// -// stb_bitset an array of booleans indexed by integers -// - -typedef stb_uint32 stb_bitset; - -STB_EXTERN stb_bitset *stb_bitset_new(int value, int len); - -#define stb_bitset_clearall(arr,len) (memset(arr, 0, 4 * (len))) -#define stb_bitset_setall(arr,len) (memset(arr, 255, 4 * (len))) - -#define stb_bitset_setbit(arr,n) ((arr)[(n) >> 5] |= (1 << (n & 31))) -#define stb_bitset_clearbit(arr,n) ((arr)[(n) >> 5] &= ~(1 << (n & 31))) -#define stb_bitset_testbit(arr,n) ((arr)[(n) >> 5] & (1 << (n & 31))) - -STB_EXTERN stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len); - -STB_EXTERN int *stb_bitset_getlist(stb_bitset *out, int start, int end); - -STB_EXTERN int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len); -STB_EXTERN int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len); -STB_EXTERN int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len); -STB_EXTERN int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len); -STB_EXTERN int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len); - -#ifdef STB_DEFINE -int stb_bitset_eq(stb_bitset *p0, stb_bitset *p1, int len) -{ - int i; - for (i = 0; i < len; ++i) - if (p0[i] != p1[i]) return 0; - return 1; -} - -int stb_bitset_disjoint(stb_bitset *p0, stb_bitset *p1, int len) -{ - int i; - for (i = 0; i < len; ++i) - if (p0[i] & p1[i]) return 0; - return 1; -} - -int stb_bitset_disjoint_0(stb_bitset *p0, stb_bitset *p1, int len) -{ - int i; - for (i = 0; i < len; ++i) - if ((p0[i] | p1[i]) != 0xffffffff) return 0; - return 1; -} - -int stb_bitset_subset(stb_bitset *bigger, stb_bitset *smaller, int len) -{ - int i; - for (i = 0; i < len; ++i) - if ((bigger[i] & smaller[i]) != smaller[i]) return 0; - return 1; -} - -stb_bitset *stb_bitset_union(stb_bitset *p0, stb_bitset *p1, int len) -{ - int i; - stb_bitset *d = (stb_bitset *)malloc(sizeof(*d) * len); - for (i = 0; i < len; ++i) d[i] = p0[i] | p1[i]; - return d; -} - -int stb_bitset_unioneq_changed(stb_bitset *p0, stb_bitset *p1, int len) -{ - int i, changed = 0; - for (i = 0; i < len; ++i) { - stb_bitset d = p0[i] | p1[i]; - if (d != p0[i]) { - p0[i] = d; - changed = 1; - } - } - return changed; -} - -stb_bitset *stb_bitset_new(int value, int len) -{ - int i; - stb_bitset *d = (stb_bitset *)malloc(sizeof(*d) * len); - if (value) value = 0xffffffff; - for (i = 0; i < len; ++i) d[i] = value; - return d; -} - -int *stb_bitset_getlist(stb_bitset *out, int start, int end) -{ - int *list = NULL; - int i; - for (i = start; i < end; ++i) - if (stb_bitset_testbit(out, i)) - stb_arr_push(list, i); - return list; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// stb_wordwrap quality word-wrapping for fixed-width fonts -// - -STB_EXTERN int stb_wordwrap(int *pairs, int pair_max, int count, char *str); -STB_EXTERN int *stb_wordwrapalloc(int count, char *str); - -#ifdef STB_DEFINE - -int stb_wordwrap(int *pairs, int pair_max, int count, char *str) -{ - int n = 0, i = 0, start = 0, nonwhite = 0; - if (pairs == NULL) pair_max = 0x7ffffff0; - else pair_max *= 2; - // parse - for (;;) { - int s = i; // first whitespace char; last nonwhite+1 - int w; // word start - // accept whitespace - while (isspace(str[i])) { - if (str[i] == '\n' || str[i] == '\r') { - if (str[i] + str[i + 1] == '\n' + '\r') ++i; - if (n >= pair_max) return -1; - if (pairs) pairs[n] = start, pairs[n + 1] = s - start; - n += 2; - nonwhite = 0; - start = i + 1; - s = start; - } - ++i; - } - if (i >= start + count) { - // we've gone off the end using whitespace - if (nonwhite) { - if (n >= pair_max) return -1; - if (pairs) pairs[n] = start, pairs[n + 1] = s - start; - n += 2; - start = s = i; - nonwhite = 0; - } - else { - // output all the whitespace - while (i >= start + count) { - if (n >= pair_max) return -1; - if (pairs) pairs[n] = start, pairs[n + 1] = count; - n += 2; - start += count; - } - s = start; - } - } - - if (str[i] == 0) break; - // now scan out a word and see if it fits - w = i; - while (str[i] && !isspace(str[i])) { - ++i; - } - // wrapped? - if (i > start + count) { - // huge? - if (i - s <= count) { - if (n >= pair_max) return -1; - if (pairs) pairs[n] = start, pairs[n + 1] = s - start; - n += 2; - start = w; - } - else { - // This word is longer than one line. If we wrap it onto N lines - // there are leftover chars. do those chars fit on the cur line? - // But if we have leading whitespace, we force it to start here. - if ((w - start) + ((i - w) % count) <= count || !nonwhite) { - // output a full line - if (n >= pair_max) return -1; - if (pairs) pairs[n] = start, pairs[n + 1] = count; - n += 2; - start += count; - w = start; - } - else { - // output a partial line, trimming trailing whitespace - if (s != start) { - if (n >= pair_max) return -1; - if (pairs) pairs[n] = start, pairs[n + 1] = s - start; - n += 2; - start = w; - } - } - // now output full lines as needed - while (start + count <= i) { - if (n >= pair_max) return -1; - if (pairs) pairs[n] = start, pairs[n + 1] = count; - n += 2; - start += count; - } - } - } - nonwhite = 1; - } - if (start < i) { - if (n >= pair_max) return -1; - if (pairs) pairs[n] = start, pairs[n + 1] = i - start; - n += 2; - } - return n >> 1; -} - -int *stb_wordwrapalloc(int count, char *str) -{ - int n = stb_wordwrap(NULL, 0, count, str); - int *z = NULL; - stb_arr_setlen(z, n * 2); - stb_wordwrap(z, n, count, str); - return z; -} -#endif - - -////////////////////////////////////////////////////////////////////////////// -// -// stb_match: wildcards and regexping -// - -STB_EXTERN int stb_wildmatch(char *expr, char *candidate); -STB_EXTERN int stb_wildmatchi(char *expr, char *candidate); -STB_EXTERN int stb_wildfind(char *expr, char *candidate); -STB_EXTERN int stb_wildfindi(char *expr, char *candidate); - -STB_EXTERN int stb_regex(char *regex, char *candidate); - -typedef struct stb_matcher stb_matcher; - -STB_EXTERN stb_matcher *stb_regex_matcher(char *regex); -STB_EXTERN int stb_matcher_match(stb_matcher *m, char *str); -STB_EXTERN int stb_matcher_find(stb_matcher *m, char *str); -STB_EXTERN void stb_matcher_free(stb_matcher *f); - -STB_EXTERN stb_matcher *stb_lex_matcher(void); -STB_EXTERN int stb_lex_item(stb_matcher *m, char *str, int result); -STB_EXTERN int stb_lex_item_wild(stb_matcher *matcher, char *regex, int result); -STB_EXTERN int stb_lex(stb_matcher *m, char *str, int *len); - - - -#ifdef STB_DEFINE - -static int stb__match_qstring(char *candidate, char *qstring, int qlen, int insensitive) -{ - int i; - if (insensitive) { - for (i = 0; i < qlen; ++i) - if (qstring[i] == '?') { - if (!candidate[i]) return 0; - } - else - if (tolower(qstring[i]) != tolower(candidate[i])) - return 0; - } - else { - for (i = 0; i < qlen; ++i) - if (qstring[i] == '?') { - if (!candidate[i]) return 0; - } - else - if (qstring[i] != candidate[i]) - return 0; - } - return 1; -} - -static int stb__find_qstring(char *candidate, char *qstring, int qlen, int insensitive) -{ - char c; - - int offset = 0; - while (*qstring == '?') { - ++qstring; - --qlen; - ++candidate; - if (qlen == 0) return 0; - if (*candidate == 0) return -1; - } - - c = *qstring++; - --qlen; - if (insensitive) c = tolower(c); - - while (candidate[offset]) { - if (c == (insensitive ? tolower(candidate[offset]) : candidate[offset])) - if (stb__match_qstring(candidate + offset + 1, qstring, qlen, insensitive)) - return offset; - ++offset; - } - - return -1; -} - -int stb__wildmatch_raw2(char *expr, char *candidate, int search, int insensitive) -{ - int where = 0; - int start = -1; - - if (!search) { - // parse to first '*' - if (*expr != '*') - start = 0; - while (*expr != '*') { - if (!*expr) - return *candidate == 0 ? 0 : -1; - if (*expr == '?') { - if (!*candidate) return -1; - } - else { - if (insensitive) { - if (tolower(*candidate) != tolower(*expr)) - return -1; - } - else - if (*candidate != *expr) - return -1; - } - ++candidate, ++expr, ++where; - } - } - else { - // 0-length search string - if (!*expr) - return 0; - } - - assert(search || *expr == '*'); - if (!search) - ++expr; - - // implicit '*' at this point - - while (*expr) { - int o = 0; - // combine redundant * characters - while (expr[0] == '*') ++expr; - - // ok, at this point, expr[-1] == '*', - // and expr[0] != '*' - - if (!expr[0]) return start >= 0 ? start : 0; - - // now find next '*' - o = 0; - while (expr[o] != '*') { - if (expr[o] == 0) - break; - ++o; - } - // if no '*', scan to end, then match at end - if (expr[o] == 0 && !search) { - int z; - for (z = 0; z < o; ++z) - if (candidate[z] == 0) - return -1; - while (candidate[z]) - ++z; - // ok, now check if they match - if (stb__match_qstring(candidate + z - o, expr, o, insensitive)) - return start >= 0 ? start : 0; - return -1; - } - else { - // if yes '*', then do stb__find_qmatch on the intervening chars - int n = stb__find_qstring(candidate, expr, o, insensitive); - if (n < 0) - return -1; - if (start < 0) - start = where + n; - expr += o; - candidate += n + o; - } - - if (*expr == 0) { - assert(search); - return start; - } - - assert(*expr == '*'); - ++expr; - } - - return start >= 0 ? start : 0; -} - -int stb__wildmatch_raw(char *expr, char *candidate, int search, int insensitive) -{ - char buffer[256]; - // handle multiple search strings - char *s = strchr(expr, ';'); - char *last = expr; - while (s) { - int z; - // need to allow for non-writeable strings... assume they're small - if (s - last < 256) { - stb_strncpy(buffer, last, s - last + 1); - z = stb__wildmatch_raw2(buffer, candidate, search, insensitive); - } - else { - *s = 0; - z = stb__wildmatch_raw2(last, candidate, search, insensitive); - *s = ';'; - } - if (z >= 0) return z; - last = s + 1; - s = strchr(last, ';'); - } - return stb__wildmatch_raw2(last, candidate, search, insensitive); -} - -int stb_wildmatch(char *expr, char *candidate) -{ - return stb__wildmatch_raw(expr, candidate, 0, 0) >= 0; -} - -int stb_wildmatchi(char *expr, char *candidate) -{ - return stb__wildmatch_raw(expr, candidate, 0, 1) >= 0; -} - -int stb_wildfind(char *expr, char *candidate) -{ - return stb__wildmatch_raw(expr, candidate, 1, 0); -} - -int stb_wildfindi(char *expr, char *candidate) -{ - return stb__wildmatch_raw(expr, candidate, 1, 1); -} - -typedef struct -{ - stb_int16 transition[256]; -} stb_dfa; - -// an NFA node represents a state you're in; it then has -// an arbitrary number of edges dangling off of it -// note this isn't utf8-y -typedef struct -{ - stb_int16 match; // character/set to match - stb_uint16 node; // output node to go to -} stb_nfa_edge; - -typedef struct -{ - stb_int16 goal; // does reaching this win the prize? - stb_uint8 active; // is this in the active list - stb_nfa_edge *out; - stb_uint16 *eps; // list of epsilon closures -} stb_nfa_node; - -#define STB__DFA_UNDEF -1 -#define STB__DFA_GOAL -2 -#define STB__DFA_END -3 -#define STB__DFA_MGOAL -4 -#define STB__DFA_VALID 0 - -#define STB__NFA_STOP_GOAL -1 - -// compiled regexp -struct stb_matcher -{ - stb_uint16 start_node; - stb_int16 dfa_start; - stb_uint32 *charset; - int num_charset; - int match_start; - stb_nfa_node *nodes; - int does_lex; - - // dfa matcher - stb_dfa * dfa; - stb_uint32 * dfa_mapping; - stb_int16 * dfa_result; - int num_words_per_dfa; -}; - -static int stb__add_node(stb_matcher *matcher) -{ - stb_nfa_node z; - z.active = 0; - z.eps = 0; - z.goal = 0; - z.out = 0; - stb_arr_push(matcher->nodes, z); - return stb_arr_len(matcher->nodes) - 1; -} - -static void stb__add_epsilon(stb_matcher *matcher, int from, int to) -{ - assert(from != to); - if (matcher->nodes[from].eps == NULL) - stb_arr_malloc((void **)&matcher->nodes[from].eps, matcher); - stb_arr_push(matcher->nodes[from].eps, to); -} - -static void stb__add_edge(stb_matcher *matcher, int from, int to, int type) -{ - stb_nfa_edge z = { (stb_int16)type, (stb_uint16)to }; - if (matcher->nodes[from].out == NULL) - stb_arr_malloc((void **)&matcher->nodes[from].out, matcher); - stb_arr_push(matcher->nodes[from].out, z); -} - -static char *stb__reg_parse_alt(stb_matcher *m, int s, char *r, stb_uint16 *e); -static char *stb__reg_parse(stb_matcher *matcher, int start, char *regex, stb_uint16 *end) -{ - int n; - int last_start = -1; - stb_uint16 last_end = start; - - while (*regex) { - switch (*regex) { - case '(': - last_start = last_end; - regex = stb__reg_parse_alt(matcher, last_end, regex + 1, &last_end); - if (regex == NULL || *regex != ')') - return NULL; - ++regex; - break; - - case '|': - case ')': - *end = last_end; - return regex; - - case '?': - if (last_start < 0) return NULL; - stb__add_epsilon(matcher, last_start, last_end); - ++regex; - break; - - case '*': - if (last_start < 0) return NULL; - stb__add_epsilon(matcher, last_start, last_end); - - // fall through - - case '+': - if (last_start < 0) return NULL; - stb__add_epsilon(matcher, last_end, last_start); - // prevent links back to last_end from chaining to last_start - n = stb__add_node(matcher); - stb__add_epsilon(matcher, last_end, n); - last_end = n; - ++regex; - break; - - case '{': // not supported! - // @TODO: given {n,m}, clone last_start to last_end m times, - // and include epsilons from start to first m-n blocks - return NULL; - - case '\\': - ++regex; - if (!*regex) return NULL; - - // fallthrough - default: // match exactly this character - n = stb__add_node(matcher); - stb__add_edge(matcher, last_end, n, *regex); - last_start = last_end; - last_end = n; - ++regex; - break; - - case '$': - n = stb__add_node(matcher); - stb__add_edge(matcher, last_end, n, '\n'); - last_start = last_end; - last_end = n; - ++regex; - break; - - case '.': - n = stb__add_node(matcher); - stb__add_edge(matcher, last_end, n, -1); - last_start = last_end; - last_end = n; - ++regex; - break; - - case '[': { - stb_uint8 flags[256]; - int invert = 0, z; - ++regex; - if (matcher->num_charset == 0) { - matcher->charset = (stb_uint *)stb_malloc(matcher, sizeof(*matcher->charset) * 256); - memset(matcher->charset, 0, sizeof(*matcher->charset) * 256); - } - - memset(flags, 0, sizeof(flags)); - - // leading ^ is special - if (*regex == '^') - ++regex, invert = 1; - - // leading ] is special - if (*regex == ']') { - flags[']'] = 1; - ++regex; - } - while (*regex != ']') { - stb_uint a; - if (!*regex) return NULL; - a = *regex++; - if (regex[0] == '-' && regex[1] != ']') { - stb_uint i, b = regex[1]; - regex += 2; - if (b == 0) return NULL; - if (a > b) return NULL; - for (i = a; i <= b; ++i) - flags[i] = 1; - } - else - flags[a] = 1; - } - ++regex; - if (invert) { - int i; - for (i = 0; i < 256; ++i) - flags[i] = 1 - flags[i]; - } - - // now check if any existing charset matches - for (z = 0; z < matcher->num_charset; ++z) { - int i, k[2] = { 0, 1 << z }; - for (i = 0; i < 256; ++i) { - unsigned int f = k[flags[i]]; - if ((matcher->charset[i] & k[1]) != f) - break; - } - if (i == 256) break; - } - - if (z == matcher->num_charset) { - int i; - ++matcher->num_charset; - if (matcher->num_charset > 32) { - assert(0); /* NOTREACHED */ - return NULL; // too many charsets, oops - } - for (i = 0; i < 256; ++i) - if (flags[i]) - matcher->charset[i] |= (1 << z); - } - - n = stb__add_node(matcher); - stb__add_edge(matcher, last_end, n, -2 - z); - last_start = last_end; - last_end = n; - break; - } - } - } - *end = last_end; - return regex; -} - -static char *stb__reg_parse_alt(stb_matcher *matcher, int start, char *regex, stb_uint16 *end) -{ - stb_uint16 last_end = start; - stb_uint16 main_end; - - int head, tail; - - head = stb__add_node(matcher); - stb__add_epsilon(matcher, start, head); - - regex = stb__reg_parse(matcher, head, regex, &last_end); - if (regex == NULL) return NULL; - if (*regex == 0 || *regex == ')') { - *end = last_end; - return regex; - } - - main_end = last_end; - tail = stb__add_node(matcher); - - stb__add_epsilon(matcher, last_end, tail); - - // start alternatives from the same starting node; use epsilon - // transitions to combine their endings - while (*regex && *regex != ')') { - assert(*regex == '|'); - head = stb__add_node(matcher); - stb__add_epsilon(matcher, start, head); - regex = stb__reg_parse(matcher, head, regex + 1, &last_end); - if (regex == NULL) - return NULL; - stb__add_epsilon(matcher, last_end, tail); - } - - *end = tail; - return regex; -} - -static char *stb__wild_parse(stb_matcher *matcher, int start, char *str, stb_uint16 *end) -{ - int n; - stb_uint16 last_end; - - last_end = stb__add_node(matcher); - stb__add_epsilon(matcher, start, last_end); - - while (*str) { - switch (*str) { - // fallthrough - default: // match exactly this character - n = stb__add_node(matcher); - if (toupper(*str) == tolower(*str)) { - stb__add_edge(matcher, last_end, n, *str); - } - else { - stb__add_edge(matcher, last_end, n, tolower(*str)); - stb__add_edge(matcher, last_end, n, toupper(*str)); - } - last_end = n; - ++str; - break; - - case '?': - n = stb__add_node(matcher); - stb__add_edge(matcher, last_end, n, -1); - last_end = n; - ++str; - break; - - case '*': - n = stb__add_node(matcher); - stb__add_edge(matcher, last_end, n, -1); - stb__add_epsilon(matcher, last_end, n); - stb__add_epsilon(matcher, n, last_end); - last_end = n; - ++str; - break; - } - } - - // now require end of string to match - n = stb__add_node(matcher); - stb__add_edge(matcher, last_end, n, 0); - last_end = n; - - *end = last_end; - return str; -} - -static int stb__opt(stb_matcher *m, int n) -{ - for (;;) { - stb_nfa_node *p = &m->nodes[n]; - if (p->goal) return n; - if (stb_arr_len(p->out)) return n; - if (stb_arr_len(p->eps) != 1) return n; - n = p->eps[0]; - } -} - -static void stb__optimize(stb_matcher *m) -{ - // if the target of any edge is a node with exactly - // one out-epsilon, shorten it - int i, j; - for (i = 0; i < stb_arr_len(m->nodes); ++i) { - stb_nfa_node *p = &m->nodes[i]; - for (j = 0; j < stb_arr_len(p->out); ++j) - p->out[j].node = stb__opt(m, p->out[j].node); - for (j = 0; j < stb_arr_len(p->eps); ++j) - p->eps[j] = stb__opt(m, p->eps[j]); - } - m->start_node = stb__opt(m, m->start_node); -} - -void stb_matcher_free(stb_matcher *f) -{ - stb_free(f); -} - -static stb_matcher *stb__alloc_matcher(void) -{ - stb_matcher *matcher = (stb_matcher *)stb_malloc(0, sizeof(*matcher)); - - matcher->start_node = 0; - stb_arr_malloc((void **)&matcher->nodes, matcher); - matcher->num_charset = 0; - matcher->match_start = 0; - matcher->does_lex = 0; - - matcher->dfa_start = STB__DFA_UNDEF; - stb_arr_malloc((void **)&matcher->dfa, matcher); - stb_arr_malloc((void **)&matcher->dfa_mapping, matcher); - stb_arr_malloc((void **)&matcher->dfa_result, matcher); - - stb__add_node(matcher); - - return matcher; -} - -static void stb__lex_reset(stb_matcher *matcher) -{ - // flush cached dfa data - stb_arr_setlen(matcher->dfa, 0); - stb_arr_setlen(matcher->dfa_mapping, 0); - stb_arr_setlen(matcher->dfa_result, 0); - matcher->dfa_start = STB__DFA_UNDEF; -} - -stb_matcher *stb_regex_matcher(char *regex) -{ - char *z; - stb_uint16 end; - stb_matcher *matcher = stb__alloc_matcher(); - if (*regex == '^') { - matcher->match_start = 1; - ++regex; - } - - z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end); - - if (!z || *z) { - stb_free(matcher); - return NULL; - } - - ((matcher->nodes)[(int)end]).goal = STB__NFA_STOP_GOAL; - - return matcher; -} - -stb_matcher *stb_lex_matcher(void) -{ - stb_matcher *matcher = stb__alloc_matcher(); - - matcher->match_start = 1; - matcher->does_lex = 1; - - return matcher; -} - -int stb_lex_item(stb_matcher *matcher, char *regex, int result) -{ - char *z; - stb_uint16 end; - - z = stb__reg_parse_alt(matcher, matcher->start_node, regex, &end); - - if (z == NULL) - return 0; - - stb__lex_reset(matcher); - - matcher->nodes[(int)end].goal = result; - return 1; -} - -int stb_lex_item_wild(stb_matcher *matcher, char *regex, int result) -{ - char *z; - stb_uint16 end; - - z = stb__wild_parse(matcher, matcher->start_node, regex, &end); - - if (z == NULL) - return 0; - - stb__lex_reset(matcher); - - matcher->nodes[(int)end].goal = result; - return 1; -} - -static void stb__clear(stb_matcher *m, stb_uint16 *list) -{ - int i; - for (i = 0; i < stb_arr_len(list); ++i) - m->nodes[(int)list[i]].active = 0; -} - -static int stb__clear_goalcheck(stb_matcher *m, stb_uint16 *list) -{ - int i, t = 0; - for (i = 0; i < stb_arr_len(list); ++i) { - t += m->nodes[(int)list[i]].goal; - m->nodes[(int)list[i]].active = 0; - } - return t; -} - -static stb_uint16 * stb__add_if_inactive(stb_matcher *m, stb_uint16 *list, int n) -{ - if (!m->nodes[n].active) { - stb_arr_push(list, n); - m->nodes[n].active = 1; - } - return list; -} - -static stb_uint16 * stb__eps_closure(stb_matcher *m, stb_uint16 *list) -{ - int i, n = stb_arr_len(list); - - for (i = 0; i < n; ++i) { - stb_uint16 *e = m->nodes[(int)list[i]].eps; - if (e) { - int j, k = stb_arr_len(e); - for (j = 0; j < k; ++j) - list = stb__add_if_inactive(m, list, e[j]); - n = stb_arr_len(list); - } - } - - return list; -} - -int stb_matcher_match(stb_matcher *m, char *str) -{ - int result = 0; - int i, j, y, z; - stb_uint16 *previous = NULL; - stb_uint16 *current = NULL; - stb_uint16 *temp; - - stb_arr_setsize(previous, 4); - stb_arr_setsize(current, 4); - - previous = stb__add_if_inactive(m, previous, m->start_node); - previous = stb__eps_closure(m, previous); - stb__clear(m, previous); - - while (*str && stb_arr_len(previous)) { - y = stb_arr_len(previous); - for (i = 0; i < y; ++i) { - stb_nfa_node *n = &m->nodes[(int)previous[i]]; - z = stb_arr_len(n->out); - for (j = 0; j < z; ++j) { - if (n->out[j].match >= 0) { - if (n->out[j].match == *str) - current = stb__add_if_inactive(m, current, n->out[j].node); - } - else if (n->out[j].match == -1) { - if (*str != '\n') - current = stb__add_if_inactive(m, current, n->out[j].node); - } - else if (n->out[j].match < -1) { - int z = -n->out[j].match - 2; - if (m->charset[(stb_uint8)*str] & (1 << z)) - current = stb__add_if_inactive(m, current, n->out[j].node); - } - } - } - stb_arr_setlen(previous, 0); - - temp = previous; - previous = current; - current = temp; - - previous = stb__eps_closure(m, previous); - stb__clear(m, previous); - - ++str; - } - - // transition to pick up a '$' at the end - y = stb_arr_len(previous); - for (i = 0; i < y; ++i) - m->nodes[(int)previous[i]].active = 1; - - for (i = 0; i < y; ++i) { - stb_nfa_node *n = &m->nodes[(int)previous[i]]; - z = stb_arr_len(n->out); - for (j = 0; j < z; ++j) { - if (n->out[j].match == '\n') - current = stb__add_if_inactive(m, current, n->out[j].node); - } - } - - previous = stb__eps_closure(m, previous); - stb__clear(m, previous); - - y = stb_arr_len(previous); - for (i = 0; i < y; ++i) - if (m->nodes[(int)previous[i]].goal) - result = 1; - - stb_arr_free(previous); - stb_arr_free(current); - - return result && *str == 0; -} - -stb_int16 stb__get_dfa_node(stb_matcher *m, stb_uint16 *list) -{ - stb_uint16 node; - stb_uint32 data[8], *state, *newstate; - int i, j, n; - - state = (stb_uint32 *)stb_temp(data, m->num_words_per_dfa * 4); - memset(state, 0, m->num_words_per_dfa * 4); - - n = stb_arr_len(list); - for (i = 0; i < n; ++i) { - int x = list[i]; - state[x >> 5] |= 1 << (x & 31); - } - - // @TODO use a hash table - n = stb_arr_len(m->dfa_mapping); - i = j = 0; - for (; j < n; ++i, j += m->num_words_per_dfa) { - // @TODO special case for <= 32 - if (!memcmp(state, m->dfa_mapping + j, m->num_words_per_dfa * 4)) { - node = i; - goto done; - } - } - - assert(stb_arr_len(m->dfa) == i); - node = i; - - newstate = stb_arr_addn(m->dfa_mapping, m->num_words_per_dfa); - memcpy(newstate, state, m->num_words_per_dfa * 4); - - // set all transitions to 'unknown' - stb_arr_add(m->dfa); - memset(m->dfa[i].transition, -1, sizeof(m->dfa[i].transition)); - - if (m->does_lex) { - int result = -1; - n = stb_arr_len(list); - for (i = 0; i < n; ++i) { - if (m->nodes[(int)list[i]].goal > result) - result = m->nodes[(int)list[i]].goal; - } - - stb_arr_push(m->dfa_result, result); - } - -done: - stb_tempfree(data, state); - return node; -} - -static int stb__matcher_dfa(stb_matcher *m, char *str_c, int *len) -{ - stb_uint8 *str = (stb_uint8 *)str_c; - stb_int16 node, prevnode; - stb_dfa *trans; - int match_length = 0; - stb_int16 match_result = 0; - - if (m->dfa_start == STB__DFA_UNDEF) { - stb_uint16 *list; - - m->num_words_per_dfa = (stb_arr_len(m->nodes) + 31) >> 5; - stb__optimize(m); - - list = stb__add_if_inactive(m, NULL, m->start_node); - list = stb__eps_closure(m, list); - if (m->does_lex) { - m->dfa_start = stb__get_dfa_node(m, list); - stb__clear(m, list); - // DON'T allow start state to be a goal state! - // this allows people to specify regexes that can match 0 - // characters without them actually matching (also we don't - // check _before_ advancing anyway - if (m->dfa_start <= STB__DFA_MGOAL) - m->dfa_start = -(m->dfa_start - STB__DFA_MGOAL); - } - else { - if (stb__clear_goalcheck(m, list)) - m->dfa_start = STB__DFA_GOAL; - else - m->dfa_start = stb__get_dfa_node(m, list); - } - stb_arr_free(list); - } - - prevnode = STB__DFA_UNDEF; - node = m->dfa_start; - trans = m->dfa; - - if (m->dfa_start == STB__DFA_GOAL) - return 1; - - for (;;) { - assert(node >= STB__DFA_VALID); - - // fast inner DFA loop; especially if STB__DFA_VALID is 0 - - do { - prevnode = node; - node = trans[node].transition[*str++]; - } while (node >= STB__DFA_VALID); - - assert(node >= STB__DFA_MGOAL - stb_arr_len(m->dfa)); - assert(node < stb_arr_len(m->dfa)); - - // special case for lex: need _longest_ match, so notice goal - // state without stopping - if (node <= STB__DFA_MGOAL) { - match_length = str - (stb_uint8 *)str_c; - node = -(node - STB__DFA_MGOAL); - match_result = node; - continue; - } - - // slow NFA->DFA conversion - - // or we hit the goal or the end of the string, but those - // can only happen once per search... - - if (node == STB__DFA_UNDEF) { - // build a list -- @TODO special case <= 32 states - // heck, use a more compact data structure for <= 16 and <= 8 ?! - - // @TODO keep states/newstates around instead of reallocating them - stb_uint16 *states = NULL; - stb_uint16 *newstates = NULL; - int i, j, y, z; - stb_uint32 *flags = &m->dfa_mapping[prevnode * m->num_words_per_dfa]; - assert(prevnode != STB__DFA_UNDEF); - stb_arr_setsize(states, 4); - stb_arr_setsize(newstates, 4); - for (j = 0; j < m->num_words_per_dfa; ++j) { - for (i = 0; i < 32; ++i) { - if (*flags & (1 << i)) - stb_arr_push(states, j * 32 + i); - } - ++flags; - } - // states is now the states we were in in the previous node; - // so now we can compute what node it transitions to on str[-1] - - y = stb_arr_len(states); - for (i = 0; i < y; ++i) { - stb_nfa_node *n = &m->nodes[(int)states[i]]; - z = stb_arr_len(n->out); - for (j = 0; j < z; ++j) { - if (n->out[j].match >= 0) { - if (n->out[j].match == str[-1] || (str[-1] == 0 && n->out[j].match == '\n')) - newstates = stb__add_if_inactive(m, newstates, n->out[j].node); - } - else if (n->out[j].match == -1) { - if (str[-1] != '\n' && str[-1]) - newstates = stb__add_if_inactive(m, newstates, n->out[j].node); - } - else if (n->out[j].match < -1) { - int z = -n->out[j].match - 2; - if (m->charset[str[-1]] & (1 << z)) - newstates = stb__add_if_inactive(m, newstates, n->out[j].node); - } - } - } - // AND add in the start state! - if (!m->match_start || (str[-1] == '\n' && !m->does_lex)) - newstates = stb__add_if_inactive(m, newstates, m->start_node); - // AND epsilon close it - newstates = stb__eps_closure(m, newstates); - // if it's a goal state, then that's all there is to it - if (stb__clear_goalcheck(m, newstates)) { - if (m->does_lex) { - match_length = str - (stb_uint8 *)str_c; - node = stb__get_dfa_node(m, newstates); - match_result = node; - node = -node + STB__DFA_MGOAL; - trans = m->dfa; // could have gotten realloc()ed - } - else - node = STB__DFA_GOAL; - } - else if (str[-1] == 0 || stb_arr_len(newstates) == 0) { - node = STB__DFA_END; - } - else { - node = stb__get_dfa_node(m, newstates); - trans = m->dfa; // could have gotten realloc()ed - } - trans[prevnode].transition[str[-1]] = node; - if (node <= STB__DFA_MGOAL) - node = -(node - STB__DFA_MGOAL); - stb_arr_free(newstates); - stb_arr_free(states); - } - - if (node == STB__DFA_GOAL) { - return 1; - } - if (node == STB__DFA_END) { - if (m->does_lex) { - if (match_result) { - if (len) *len = match_length; - return m->dfa_result[(int)match_result]; - } - } - return 0; - } - - assert(node != STB__DFA_UNDEF); - } -} - -int stb_matcher_find(stb_matcher *m, char *str) -{ - assert(m->does_lex == 0); - return stb__matcher_dfa(m, str, NULL); -} - -int stb_lex(stb_matcher *m, char *str, int *len) -{ - assert(m->does_lex); - return stb__matcher_dfa(m, str, len); -} - -int stb_regex(char *regex, char *str) -{ - static stb_perfect p; - static stb_matcher ** matchers; - static char ** regexps; - static char ** regexp_cache; - static unsigned short *mapping; - int z = stb_perfect_hash(&p, (int)(size_t)regex); - if (z >= 0) { - if (strcmp(regex, regexp_cache[(int)mapping[z]])) { - int i = mapping[z]; - stb_matcher_free(matchers[i]); - free(regexp_cache[i]); - regexps[i] = regex; - regexp_cache[i] = strdup(regex); - matchers[i] = stb_regex_matcher(regex); - } - } - else { - int i, n; - if (regex == NULL) { - for (i = 0; i < stb_arr_len(matchers); ++i) { - stb_matcher_free(matchers[i]); - free(regexp_cache[i]); - } - stb_arr_free(matchers); - stb_arr_free(regexps); - stb_arr_free(regexp_cache); - stb_perfect_destroy(&p); - free(mapping); mapping = NULL; - return -1; - } - stb_arr_push(regexps, regex); - stb_arr_push(regexp_cache, strdup(regex)); - stb_arr_push(matchers, stb_regex_matcher(regex)); - stb_perfect_destroy(&p); - n = stb_perfect_create(&p, (unsigned int *)(char **)regexps, stb_arr_len(regexps)); - mapping = (unsigned short *)realloc(mapping, n * sizeof(*mapping)); - for (i = 0; i < stb_arr_len(regexps); ++i) - mapping[stb_perfect_hash(&p, (int)(size_t)regexps[i])] = i; - z = stb_perfect_hash(&p, (int)(size_t)regex); - } - return stb_matcher_find(matchers[(int)mapping[z]], str); -} - -#endif // STB_DEFINE - - -#if 0 -////////////////////////////////////////////////////////////////////////////// -// -// C source-code introspection -// - -// runtime structure -typedef struct -{ - char *name; - char *type; // base type - char *comment; // content of comment field - int size; // size of base type - int offset; // field offset - int arrcount[8]; // array sizes; -1 = pointer indirection; 0 = end of list -} stb_info_field; - -typedef struct -{ - char *structname; - int size; - int num_fields; - stb_info_field *fields; -} stb_info_struct; - -extern stb_info_struct stb_introspect_output[]; - -// - -STB_EXTERN void stb_introspect_precompiled(stb_info_struct *compiled); -STB_EXTERN void stb__introspect(char *path, char *file); - -#define stb_introspect_ship() stb__introspect(NULL, NULL, stb__introspect_output) - -#ifdef STB_SHIP -#define stb_introspect() stb_introspect_ship() -#define stb_introspect_path(p) stb_introspect_ship() -#else -// bootstrapping: define stb_introspect() (or 'path') the first time -#define stb_introspect() stb__introspect(NULL, __FILE__, NULL) -#define stb_introspect_auto() stb__introspect(NULL, __FILE__, stb__introspect_output) - -#define stb_introspect_path(p) stb__introspect(p, __FILE__, NULL) -#define stb_introspect_path(p) stb__introspect(p, __FILE__, NULL) -#endif - -#ifdef STB_DEFINE - -#ifndef STB_INTROSPECT_CPP -#ifdef __cplusplus -#define STB_INTROSPECT_CPP 1 -#else -#define STB_INTROSPECT_CPP 0 -#endif -#endif - -void stb_introspect_precompiled(stb_info_struct *compiled) -{ - -} - - -static void stb__introspect_filename(char *buffer, char *path) -{ -#if STB_INTROSPECT_CPP - sprintf(buffer, "%s/stb_introspect.cpp", path); -#else - sprintf(buffer, "%s/stb_introspect.c", path); -#endif -} - -static void stb__introspect_compute(char *path, char *file) -{ - int i; - char ** include_list = NULL; - char ** introspect_list = NULL; - FILE *f; - f = fopen(file, "w"); - if (!f) return; - - fputs("// if you get compiler errors, change the following 0 to a 1:\n", f); - fputs("#define STB_INTROSPECT_INVALID 0\n\n", f); - fputs("// this will force the code to compile, and force the introspector\n", f); - fputs("// to run and then exit, allowing you to recompile\n\n\n", f); - fputs("#include \"stb.h\"\n\n", f); - fputs("#if STB_INTROSPECT_INVALID\n", f); - fputs(" stb_info_struct stb__introspect_output[] = { (void *) 1 }\n", f); - fputs("#else\n\n", f); - for (i = 0; i < stb_arr_len(include_list); ++i) - fprintf(f, " #include \"%s\"\n", include_list[i]); - - fputs(" stb_info_struct stb__introspect_output[] =\n{\n", f); - for (i = 0; i < stb_arr_len(introspect_list); ++i) - fprintf(f, " stb_introspect_%s,\n", introspect_list[i]); - fputs(" };\n", f); - fputs("#endif\n", f); - fclose(f); -} - -static stb_info_struct *stb__introspect_info; - -#ifndef STB_SHIP - -#endif - -void stb__introspect(char *path, char *file, stb_info_struct *compiled) -{ - static int first = 1; - if (!first) return; - first = 0; - - stb__introspect_info = compiled; - -#ifndef STB_SHIP - if (path || file) { - int bail_flag = compiled && compiled[0].structname == (void *)1; - int needs_building = bail_flag; - struct stb__stat st; - char buffer[1024], buffer2[1024]; - if (!path) { - stb_splitpath(buffer, file, STB_PATH); - path = buffer; - } - // bail if the source path doesn't exist - if (!stb_fexists(path)) return; - - stb__introspect_filename(buffer2, path); - - // get source/include files timestamps, compare to output-file timestamp; - // if mismatched, regenerate - - if (stb__stat(buffer2, &st)) - needs_building = STB_TRUE; - - { - // find any file that contains an introspection command and is newer - // if needs_building is already true, we don't need to do this test, - // but we still need these arrays, so go ahead and get them - char **all[3]; - all[0] = stb_readdir_files_mask(path, "*.h"); - all[1] = stb_readdir_files_mask(path, "*.c"); - all[2] = stb_readdir_files_mask(path, "*.cpp"); - int i, j; - if (needs_building) { - for (j = 0; j < 3; ++j) { - for (i = 0; i < stb_arr_len(all[j]); ++i) { - struct stb__stat st2; - if (!stb__stat(all[j][i], &st2)) { - if (st.st_mtime < st2.st_mtime) { - char *z = stb_filec(all[j][i], NULL); - int found = STB_FALSE; - while (y) { - y = strstr(y, "//si"); - if (y && isspace(y[4])) { - found = STB_TRUE; - break; - } - } - needs_building = STB_TRUE; - goto done; - } - } - } - } - done:; - } - char *z = stb_filec(all[i], NULL), *y = z; - int found = STB_FALSE; - while (y) { - y = strstr(y, "//si"); - if (y && isspace(y[4])) { - found = STB_TRUE; - break; - } - } - if (found) - stb_arr_push(introspect_h, strdup(all[i])); - free(z); - } - } - stb_readdir_free(all); - if (!needs_building) { - for (i = 0; i < stb_arr_len(introspect_h); ++i) { - struct stb__stat st2; - if (!stb__stat(introspect_h[i], &st2)) - if (st.st_mtime < st2.st_mtime) - needs_building = STB_TRUE; - } - } - - if (needs_building) { - stb__introspect_compute(path, buffer2); - } -} - } -#endif -} -#endif -#endif - -#ifdef STB_INTROSPECT -// compile-time code-generator -#define INTROSPECT(x) int main(int argc, char **argv) { stb__introspect(__FILE__); return 0; } -#define FILE(x) - -void stb__introspect(char *filename) -{ - char *file = stb_file(filename, NULL); - char *s = file, *t, **p; - char *out_name = "stb_introspect.c"; - char *out_path; - STB_ARR(char) filelist = NULL; - int i, n; - if (!file) stb_fatal("Couldn't open %s", filename); - - out_path = stb_splitpathdup(filename, STB_PATH); - - // search for the macros - while (*s) { - char buffer[256]; - while (*s && !isupper(*s)) ++s; - s = stb_strtok_invert(buffer, s, "ABCDEFGHIJKLMNOPQRSTUVWXYZ"); - s = stb_skipwhite(s); - if (*s == '(') { - ++s; - t = strchr(s, ')'); - if (t == NULL) stb_fatal("Error parsing %s", filename); - - } - } -} - - - -#endif - - -////////////////////////////////////////////////////////////////////////////// -// -// STB-C sliding-window dictionary compression -// -// This uses a DEFLATE-style sliding window, but no bitwise entropy. -// Everything is on byte boundaries, so you could then apply a byte-wise -// entropy code, though that's nowhere near as effective. -// -// An STB-C stream begins with a 16-byte header: -// 4 bytes: 0x57 0xBC 0x00 0x00 -// 8 bytes: big-endian size of decompressed data, 64-bits -// 4 bytes: big-endian size of window (how far back decompressor may need) -// -// The following symbols appear in the stream (these were determined ad hoc, -// not by analysis): -// -// [dict] 00000100 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx -// [END] 00000101 11111010 cccccccc cccccccc cccccccc cccccccc -// [dict] 00000110 yyyyyyyy yyyyyyyy yyyyyyyy xxxxxxxx -// [literals] 00000111 zzzzzzzz zzzzzzzz -// [literals] 00001zzz zzzzzzzz -// [dict] 00010yyy yyyyyyyy yyyyyyyy xxxxxxxx xxxxxxxx -// [dict] 00011yyy yyyyyyyy yyyyyyyy xxxxxxxx -// [literals] 001zzzzz -// [dict] 01yyyyyy yyyyyyyy xxxxxxxx -// [dict] 1xxxxxxx yyyyyyyy -// -// xxxxxxxx: match length - 1 -// yyyyyyyy: backwards distance - 1 -// zzzzzzzz: num literals - 1 -// cccccccc: adler32 checksum of decompressed data -// (all big-endian) - - -STB_EXTERN stb_uint stb_decompress_length(stb_uchar *input); -STB_EXTERN stb_uint stb_decompress(stb_uchar *out, stb_uchar *in, stb_uint len); -STB_EXTERN stb_uint stb_compress(stb_uchar *out, stb_uchar *in, stb_uint len); -STB_EXTERN void stb_compress_window(int z); -STB_EXTERN void stb_compress_hashsize(unsigned int z); - -STB_EXTERN int stb_compress_tofile(char *filename, char *in, stb_uint len); -STB_EXTERN int stb_compress_intofile(FILE *f, char *input, stb_uint len); -STB_EXTERN char *stb_decompress_fromfile(char *filename, stb_uint *len); - -STB_EXTERN int stb_compress_stream_start(FILE *f); -STB_EXTERN void stb_compress_stream_end(int close); -STB_EXTERN void stb_write(char *data, int data_len); - -#ifdef STB_DEFINE - -stb_uint stb_decompress_length(stb_uchar *input) -{ - return (input[8] << 24) + (input[9] << 16) + (input[10] << 8) + input[11]; -} - -//////////////////// decompressor /////////////////////// - -// simple implementation that just writes whole thing into big block - -static unsigned char *stb__barrier; -static unsigned char *stb__barrier2; -static unsigned char *stb__barrier3; -static unsigned char *stb__barrier4; - -static stb_uchar *stb__dout; -static void stb__match(stb_uchar *data, stb_uint length) -{ - // INVERSE of memmove... write each byte before copying the next... - assert(stb__dout + length <= stb__barrier); - if (stb__dout + length > stb__barrier) { stb__dout += length; return; } - if (data < stb__barrier4) { stb__dout = stb__barrier + 1; return; } - while (length--) *stb__dout++ = *data++; -} - -static void stb__lit(stb_uchar *data, stb_uint length) -{ - assert(stb__dout + length <= stb__barrier); - if (stb__dout + length > stb__barrier) { stb__dout += length; return; } - if (data < stb__barrier2) { stb__dout = stb__barrier + 1; return; } - memcpy(stb__dout, data, length); - stb__dout += length; -} - -#define stb__in2(x) ((i[x] << 8) + i[(x)+1]) -#define stb__in3(x) ((i[x] << 16) + stb__in2((x)+1)) -#define stb__in4(x) ((i[x] << 24) + stb__in3((x)+1)) - -static stb_uchar *stb_decompress_token(stb_uchar *i) -{ - if (*i >= 0x20) { // use fewer if's for cases that expand small - if (*i >= 0x80) stb__match(stb__dout - i[1] - 1, i[0] - 0x80 + 1), i += 2; - else if (*i >= 0x40) stb__match(stb__dout - (stb__in2(0) - 0x4000 + 1), i[2] + 1), i += 3; - else /* *i >= 0x20 */ stb__lit(i + 1, i[0] - 0x20 + 1), i += 1 + (i[0] - 0x20 + 1); - } - else { // more ifs for cases that expand large, since overhead is amortized - if (*i >= 0x18) stb__match(stb__dout - (stb__in3(0) - 0x180000 + 1), i[3] + 1), i += 4; - else if (*i >= 0x10) stb__match(stb__dout - (stb__in3(0) - 0x100000 + 1), stb__in2(3) + 1), i += 5; - else if (*i >= 0x08) stb__lit(i + 2, stb__in2(0) - 0x0800 + 1), i += 2 + (stb__in2(0) - 0x0800 + 1); - else if (*i == 0x07) stb__lit(i + 3, stb__in2(1) + 1), i += 3 + (stb__in2(1) + 1); - else if (*i == 0x06) stb__match(stb__dout - (stb__in3(1) + 1), i[4] + 1), i += 5; - else if (*i == 0x04) stb__match(stb__dout - (stb__in3(1) + 1), stb__in2(4) + 1), i += 6; - } - return i; -} - -stb_uint stb_decompress(stb_uchar *output, stb_uchar *i, stb_uint length) -{ - stb_uint olen; - if (stb__in4(0) != 0x57bC0000) return 0; - if (stb__in4(4) != 0) return 0; // error! stream is > 4GB - olen = stb_decompress_length(i); - stb__barrier2 = i; - stb__barrier3 = i + length; - stb__barrier = output + olen; - stb__barrier4 = output; - i += 16; - - stb__dout = output; - while (1) { - stb_uchar *old_i = i; - i = stb_decompress_token(i); - if (i == old_i) { - if (*i == 0x05 && i[1] == 0xfa) { - assert(stb__dout == output + olen); - if (stb__dout != output + olen) return 0; - if (stb_adler32(1, output, olen) != (stb_uint)stb__in4(2)) - return 0; - return olen; - } - else { - assert(0); /* NOTREACHED */ - return 0; - } - } - assert(stb__dout <= output + olen); - if (stb__dout > output + olen) - return 0; - } -} - -char *stb_decompress_fromfile(char *filename, unsigned int *len) -{ - unsigned int n; - char *q; - unsigned char *p; - FILE *f = fopen(filename, "rb"); if (f == NULL) return NULL; - fseek(f, 0, SEEK_END); - n = ftell(f); - fseek(f, 0, SEEK_SET); - p = (unsigned char *)malloc(n); if (p == NULL) return NULL; - fread(p, 1, n, f); - fclose(f); - if (p == NULL) return NULL; - if (p[0] != 0x57 || p[1] != 0xBc || p[2] || p[3]) { free(p); return NULL; } - q = (char *)malloc(stb_decompress_length(p) + 1); - if (!q) { free(p); return NULL; } - *len = stb_decompress((unsigned char *)q, p, n); - if (*len) q[*len] = 0; - free(p); - return q; -} - -#if 0 -// streaming decompressor - -static struct -{ - stb__uchar *in_buffer; - stb__uchar *match; - - stb__uint pending_literals; - stb__uint pending_match; -} xx; - - - -static void stb__match(stb_uchar *data, stb_uint length) -{ - // INVERSE of memmove... write each byte before copying the next... - assert(stb__dout + length <= stb__barrier); - if (stb__dout + length > stb__barrier) { stb__dout += length; return; } - if (data < stb__barrier2) { stb__dout = stb__barrier + 1; return; } - while (length--) *stb__dout++ = *data++; -} - -static void stb__lit(stb_uchar *data, stb_uint length) -{ - assert(stb__dout + length <= stb__barrier); - if (stb__dout + length > stb__barrier) { stb__dout += length; return; } - if (data < stb__barrier2) { stb__dout = stb__barrier + 1; return; } - memcpy(stb__dout, data, length); - stb__dout += length; -} - -static void sx_match(stb_uchar *data, stb_uint length) -{ - xx.match = data; - xx.pending_match = length; -} - -static void sx_lit(stb_uchar *data, stb_uint length) -{ - xx.pending_lit = length; -} - -static int stb_decompress_token_state(void) -{ - stb__uchar *i = xx.in_buffer; - - if (*i >= 0x20) { // use fewer if's for cases that expand small - if (*i >= 0x80) sx_match(stb__dout - i[1] - 1, i[0] - 0x80 + 1), i += 2; - else if (*i >= 0x40) sx_match(stb__dout - (stb__in2(0) - 0x4000 + 1), i[2] + 1), i += 3; - else /* *i >= 0x20 */ sx_lit(i + 1, i[0] - 0x20 + 1), i += 1; - } - else { // more ifs for cases that expand large, since overhead is amortized - if (*i >= 0x18) sx_match(stb__dout - (stb__in3(0) - 0x180000 + 1), i[3] + 1), i += 4; - else if (*i >= 0x10) sx_match(stb__dout - (stb__in3(0) - 0x100000 + 1), stb__in2(3) + 1), i += 5; - else if (*i >= 0x08) sx_lit(i + 2, stb__in2(0) - 0x0800 + 1), i += 2; - else if (*i == 0x07) sx_lit(i + 3, stb__in2(1) + 1), i += 3; - else if (*i == 0x06) sx_match(stb__dout - (stb__in3(1) + 1), i[4] + 1), i += 5; - else if (*i == 0x04) sx_match(stb__dout - (stb__in3(1) + 1), stb__in2(4) + 1), i += 6; - else return 0; - } - xx.in_buffer = i; - return 1; -} -#endif - - - -//////////////////// compressor /////////////////////// - -static unsigned int stb_matchlen(stb_uchar *m1, stb_uchar *m2, stb_uint maxlen) -{ - stb_uint i; - for (i = 0; i < maxlen; ++i) - if (m1[i] != m2[i]) return i; - return i; -} - -// simple implementation that just takes the source data in a big block - -static stb_uchar *stb__out; -static FILE *stb__outfile; -static stb_uint stb__outbytes; - -static void stb__write(unsigned char v) -{ - fputc(v, stb__outfile); - ++stb__outbytes; -} - -#define stb_out(v) (stb__out ? (void)(*stb__out++ = (stb_uchar) (v)) : stb__write((stb_uchar) (v))) - -static void stb_out2(stb_uint v) -{ - stb_out(v >> 8); - stb_out(v); -} - -static void stb_out3(stb_uint v) { stb_out(v >> 16); stb_out(v >> 8); stb_out(v); } -static void stb_out4(stb_uint v) { - stb_out(v >> 24); stb_out(v >> 16); - stb_out(v >> 8); stb_out(v); -} - -static void outliterals(stb_uchar *in, int numlit) -{ - while (numlit > 65536) { - outliterals(in, 65536); - in += 65536; - numlit -= 65536; - } - - if (numlit == 0); - else if (numlit <= 32) stb_out(0x000020 + numlit - 1); - else if (numlit <= 2048) stb_out2(0x000800 + numlit - 1); - else /* numlit <= 65536) */ stb_out3(0x070000 + numlit - 1); - - if (stb__out) { - memcpy(stb__out, in, numlit); - stb__out += numlit; - } - else - fwrite(in, 1, numlit, stb__outfile); -} - -static int stb__window = 0x40000; // 256K -void stb_compress_window(int z) -{ - if (z >= 0x1000000) z = 0x1000000; // limit of implementation - if (z < 0x100) z = 0x100; // insanely small - stb__window = z; -} - -static int stb_not_crap(int best, int dist) -{ - return ((best > 2 && dist <= 0x00100) - || (best > 5 && dist <= 0x04000) - || (best > 7 && dist <= 0x80000)); -} - -static stb_uint stb__hashsize = 32768; -void stb_compress_hashsize(unsigned int y) -{ - unsigned int z = 1024; - while (z < y) z <<= 1; - stb__hashsize = z >> 2; // pass in bytes, store #pointers -} - -// note that you can play with the hashing functions all you -// want without needing to change the decompressor -#define stb__hc(q,h,c) (((h) << 7) + ((h) >> 25) + q[c]) -#define stb__hc2(q,h,c,d) (((h) << 14) + ((h) >> 18) + (q[c] << 7) + q[d]) -#define stb__hc3(q,c,d,e) ((q[c] << 14) + (q[d] << 7) + q[e]) - -static stb_uint32 stb__running_adler; - -static int stb_compress_chunk(stb_uchar *history, - stb_uchar *start, - stb_uchar *end, - int length, - int *pending_literals, - stb_uchar **chash, - stb_uint mask) -{ - int window = stb__window; - stb_uint match_max; - stb_uchar *lit_start = start - *pending_literals; - stb_uchar *q = start; - -#define STB__SCRAMBLE(h) (((h) + ((h) >> 16)) & mask) - - // stop short of the end so we don't scan off the end doing - // the hashing; this means we won't compress the last few bytes - // unless they were part of something longer - while (q < start + length && q + 12 < end) { - int m; - stb_uint h1, h2, h3, h4, h; - stb_uchar *t; - int best = 2, dist = 0; - - if (q + 65536 > end) - match_max = end - q; - else - match_max = 65536; - -#define stb__nc(b,d) ((d) <= window && ((b) > 9 || stb_not_crap(b,d))) - -#define STB__TRY(t,p) /* avoid retrying a match we already tried */ \ - if (p ? dist != q-t : 1) \ - if ((m = stb_matchlen(t, q, match_max)) > best) \ - if (stb__nc(m,q-(t))) \ - best = m, dist = q - (t) - - // rather than search for all matches, only try 4 candidate locations, - // chosen based on 4 different hash functions of different lengths. - // this strategy is inspired by LZO; hashing is unrolled here using the - // 'hc' macro - h = stb__hc3(q, 0, 1, 2); h1 = STB__SCRAMBLE(h); - t = chash[h1]; if (t) STB__TRY(t, 0); - h = stb__hc2(q, h, 3, 4); h2 = STB__SCRAMBLE(h); - h = stb__hc2(q, h, 5, 6); t = chash[h2]; if (t) STB__TRY(t, 1); - h = stb__hc2(q, h, 7, 8); h3 = STB__SCRAMBLE(h); - h = stb__hc2(q, h, 9, 10); t = chash[h3]; if (t) STB__TRY(t, 1); - h = stb__hc2(q, h, 11, 12); h4 = STB__SCRAMBLE(h); - t = chash[h4]; if (t) STB__TRY(t, 1); - - // because we use a shared hash table, can only update it - // _after_ we've probed all of them - chash[h1] = chash[h2] = chash[h3] = chash[h4] = q; - - if (best > 2) - assert(dist > 0); - - // see if our best match qualifies - if (best < 3) { // fast path literals - ++q; - } - else if (best > 2 && best <= 0x80 && dist <= 0x100) { - outliterals(lit_start, q - lit_start); lit_start = (q += best); - stb_out(0x80 + best - 1); - stb_out(dist - 1); - } - else if (best > 5 && best <= 0x100 && dist <= 0x4000) { - outliterals(lit_start, q - lit_start); lit_start = (q += best); - stb_out2(0x4000 + dist - 1); - stb_out(best - 1); - } - else if (best > 7 && best <= 0x100 && dist <= 0x80000) { - outliterals(lit_start, q - lit_start); lit_start = (q += best); - stb_out3(0x180000 + dist - 1); - stb_out(best - 1); - } - else if (best > 8 && best <= 0x10000 && dist <= 0x80000) { - outliterals(lit_start, q - lit_start); lit_start = (q += best); - stb_out3(0x100000 + dist - 1); - stb_out2(best - 1); - } - else if (best > 9 && dist <= 0x1000000) { - if (best > 65536) best = 65536; - outliterals(lit_start, q - lit_start); lit_start = (q += best); - if (best <= 0x100) { - stb_out(0x06); - stb_out3(dist - 1); - stb_out(best - 1); - } - else { - stb_out(0x04); - stb_out3(dist - 1); - stb_out2(best - 1); - } - } - else { // fallback literals if no match was a balanced tradeoff - ++q; - } - } - - // if we didn't get all the way, add the rest to literals - if (q - start < length) - q = start + length; - - // the literals are everything from lit_start to q - *pending_literals = (q - lit_start); - - stb__running_adler = stb_adler32(stb__running_adler, start, q - start); - return q - start; -} - -static int stb_compress_inner(stb_uchar *input, stb_uint length) -{ - int literals = 0; - stb_uint len, i; - - stb_uchar **chash; - chash = (stb_uchar**)malloc(stb__hashsize * sizeof(stb_uchar*)); - if (chash == NULL) return 0; // failure - for (i = 0; i < stb__hashsize; ++i) - chash[i] = NULL; - - // stream signature - stb_out(0x57); stb_out(0xbc); - stb_out2(0); - - stb_out4(0); // 64-bit length requires 32-bit leading 0 - stb_out4(length); - stb_out4(stb__window); - - stb__running_adler = 1; - - len = stb_compress_chunk(input, input, input + length, length, &literals, chash, stb__hashsize - 1); - assert(len == length); - - outliterals(input + length - literals, literals); - - free(chash); - - stb_out2(0x05fa); // end opcode - - stb_out4(stb__running_adler); - - return 1; // success -} - -stb_uint stb_compress(stb_uchar *out, stb_uchar *input, stb_uint length) -{ - stb__out = out; - stb__outfile = NULL; - - stb_compress_inner(input, length); - - return stb__out - out; -} - -int stb_compress_tofile(char *filename, char *input, unsigned int length) -{ - //int maxlen = length + 512 + (length >> 2); // total guess - //char *buffer = (char *) malloc(maxlen); - //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length); - - stb__out = NULL; - stb__outfile = fopen(filename, "wb"); - if (!stb__outfile) return 0; - - stb__outbytes = 0; - - if (!stb_compress_inner((stb_uchar*)input, length)) - return 0; - - fclose(stb__outfile); - - return stb__outbytes; -} - -int stb_compress_intofile(FILE *f, char *input, unsigned int length) -{ - //int maxlen = length + 512 + (length >> 2); // total guess - //char *buffer = (char*)malloc(maxlen); - //int blen = stb_compress((stb_uchar*)buffer, (stb_uchar*)input, length); - - stb__out = NULL; - stb__outfile = f; - if (!stb__outfile) return 0; - - stb__outbytes = 0; - - if (!stb_compress_inner((stb_uchar*)input, length)) - return 0; - - return stb__outbytes; -} - -////////////////////// streaming I/O version ///////////////////// - - -static size_t stb_out_backpatch_id(void) -{ - if (stb__out) - return (size_t)stb__out; - else - return ftell(stb__outfile); -} - -static void stb_out_backpatch(size_t id, stb_uint value) -{ - - stb_uchar data[4] = { (stb_uchar)(value >> 24), (stb_uchar)(value >> 16), (stb_uchar)(value >> 8), (stb_uchar)(value) }; - if (stb__out) { - memcpy((void *)id, data, 4); - } - else { - stb_uint where = ftell(stb__outfile); - fseek(stb__outfile, id, SEEK_SET); - fwrite(data, 4, 1, stb__outfile); - fseek(stb__outfile, where, SEEK_SET); - } -} - -// ok, the wraparound buffer was a total failure. let's instead -// use a copying-in-place buffer, which lets us share the code. -// This is way less efficient but it'll do for now. - -static struct -{ - stb_uchar *buffer; - int size; // physical size of buffer in bytes - - int valid; // amount of valid data in bytes - int start; // bytes of data already output - - int window; - int fsize; - - int pending_literals; // bytes not-quite output but counted in start - int length_id; - - stb_uint total_bytes; - - stb_uchar **chash; - stb_uint hashmask; -} xtb; - -static int stb_compress_streaming_start(void) -{ - stb_uint i; - xtb.size = stb__window * 3; - xtb.buffer = (stb_uchar*)malloc(xtb.size); - if (!xtb.buffer) return 0; - - xtb.chash = (stb_uchar**)malloc(sizeof(*xtb.chash) * stb__hashsize); - if (!xtb.chash) { - free(xtb.buffer); - return 0; - } - - for (i = 0; i < stb__hashsize; ++i) - xtb.chash[i] = NULL; - - xtb.hashmask = stb__hashsize - 1; - - xtb.valid = 0; - xtb.start = 0; - xtb.window = stb__window; - xtb.fsize = stb__window; - xtb.pending_literals = 0; - xtb.total_bytes = 0; - - // stream signature - stb_out(0x57); stb_out(0xbc); stb_out2(0); - - stb_out4(0); // 64-bit length requires 32-bit leading 0 - - xtb.length_id = stb_out_backpatch_id(); - stb_out4(0); // we don't know the output length yet - - stb_out4(stb__window); - - stb__running_adler = 1; - - return 1; -} - -static int stb_compress_streaming_end(void) -{ - // flush out any remaining data - stb_compress_chunk(xtb.buffer, xtb.buffer + xtb.start, xtb.buffer + xtb.valid, - xtb.valid - xtb.start, &xtb.pending_literals, xtb.chash, xtb.hashmask); - - // write out pending literals - outliterals(xtb.buffer + xtb.valid - xtb.pending_literals, xtb.pending_literals); - - stb_out2(0x05fa); // end opcode - stb_out4(stb__running_adler); - - stb_out_backpatch(xtb.length_id, xtb.total_bytes); - - free(xtb.buffer); - free(xtb.chash); - return 1; -} - -void stb_write(char *data, int data_len) -{ - stb_uint i; - - // @TODO: fast path for filling the buffer and doing nothing else - // if (xtb.valid + data_len < xtb.size) - - xtb.total_bytes += data_len; - - while (data_len) { - // fill buffer - if (xtb.valid < xtb.size) { - int amt = xtb.size - xtb.valid; - if (data_len < amt) amt = data_len; - memcpy(xtb.buffer + xtb.valid, data, amt); - data_len -= amt; - data += amt; - xtb.valid += amt; - } - if (xtb.valid < xtb.size) - return; - - // at this point, the buffer is full - - // if we can process some data, go for it; make sure - // we leave an 'fsize's worth of data, though - if (xtb.start + xtb.fsize < xtb.valid) { - int amount = (xtb.valid - xtb.fsize) - xtb.start; - int n; - assert(amount > 0); - n = stb_compress_chunk(xtb.buffer, xtb.buffer + xtb.start, xtb.buffer + xtb.valid, - amount, &xtb.pending_literals, xtb.chash, xtb.hashmask); - xtb.start += n; - } - - assert(xtb.start + xtb.fsize >= xtb.valid); - // at this point, our future size is too small, so we - // need to flush some history. we, in fact, flush exactly - // one window's worth of history - - { - int flush = xtb.window; - assert(xtb.start >= flush); - assert(xtb.valid >= flush); - - // if 'pending literals' extends back into the shift region, - // write them out - if (xtb.start - xtb.pending_literals < flush) { - outliterals(xtb.buffer + xtb.start - xtb.pending_literals, xtb.pending_literals); - xtb.pending_literals = 0; - } - - // now shift the window - memmove(xtb.buffer, xtb.buffer + flush, xtb.valid - flush); - xtb.start -= flush; - xtb.valid -= flush; - - for (i = 0; i <= xtb.hashmask; ++i) - if (xtb.chash[i] < xtb.buffer + flush) - xtb.chash[i] = NULL; - else - xtb.chash[i] -= flush; - } - // and now that we've made room for more data, go back to the top - } -} - -int stb_compress_stream_start(FILE *f) -{ - stb__out = NULL; - stb__outfile = f; - - if (f == NULL) - return 0; - - if (!stb_compress_streaming_start()) - return 0; - - return 1; -} - -void stb_compress_stream_end(int close) -{ - stb_compress_streaming_end(); - if (close && stb__outfile) { - fclose(stb__outfile); - } -} - -#endif // STB_DEFINE - -////////////////////////////////////////////////////////////////////////////// -// -// File abstraction... tired of not having this... we can write -// compressors to be layers over these that auto-close their children. - - -typedef struct stbfile -{ - int(*getbyte)(struct stbfile *); // -1 on EOF - unsigned int(*getdata)(struct stbfile *, void *block, unsigned int len); - - int(*putbyte)(struct stbfile *, int byte); - unsigned int(*putdata)(struct stbfile *, void *block, unsigned int len); - - unsigned int(*size)(struct stbfile *); - - unsigned int(*tell)(struct stbfile *); - void(*backpatch)(struct stbfile *, unsigned int tell, void *block, unsigned int len); - - void(*close)(struct stbfile *); - - FILE *f; // file to fread/fwrite - unsigned char *buffer; // input/output buffer - unsigned char *indata, *inend; // input buffer - union { - int various; - void *ptr; - }; -} stbfile; - -STB_EXTERN unsigned int stb_getc(stbfile *f); // read -STB_EXTERN int stb_putc(stbfile *f, int ch); // write -STB_EXTERN unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len); // read -STB_EXTERN unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len); // write -STB_EXTERN unsigned int stb_tell(stbfile *f); // read -STB_EXTERN unsigned int stb_size(stbfile *f); // read/write -STB_EXTERN void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len); // write - -#ifdef STB_DEFINE - -unsigned int stb_getc(stbfile *f) { return f->getbyte(f); } -int stb_putc(stbfile *f, int ch) { return f->putbyte(f, ch); } - -unsigned int stb_getdata(stbfile *f, void *buffer, unsigned int len) -{ - return f->getdata(f, buffer, len); -} -unsigned int stb_putdata(stbfile *f, void *buffer, unsigned int len) -{ - return f->putdata(f, buffer, len); -} -void stb_close(stbfile *f) -{ - f->close(f); - free(f); -} -unsigned int stb_tell(stbfile *f) { return f->tell(f); } -unsigned int stb_size(stbfile *f) { return f->size(f); } -void stb_backpatch(stbfile *f, unsigned int tell, void *buffer, unsigned int len) -{ - f->backpatch(f, tell, buffer, len); -} - -// FILE * implementation -static int stb__fgetbyte(stbfile *f) { return fgetc(f->f); } -static int stb__fputbyte(stbfile *f, int ch) { return fputc(ch, f->f) == 0; } -static unsigned int stb__fgetdata(stbfile *f, void *buffer, unsigned int len) { return fread(buffer, 1, len, f->f); } -static unsigned int stb__fputdata(stbfile *f, void *buffer, unsigned int len) { return fwrite(buffer, 1, len, f->f); } -static unsigned int stb__fsize(stbfile *f) { return stb_filelen(f->f); } -static unsigned int stb__ftell(stbfile *f) { return ftell(f->f); } -static void stb__fbackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len) -{ - fseek(f->f, where, SEEK_SET); - fwrite(buffer, 1, len, f->f); - fseek(f->f, 0, SEEK_END); -} -static void stb__fclose(stbfile *f) { fclose(f->f); } - -stbfile *stb_openf(FILE *f) -{ - stbfile m = { stb__fgetbyte, stb__fgetdata, - stb__fputbyte, stb__fputdata, - stb__fsize, stb__ftell, stb__fbackpatch, stb__fclose, - 0,0,0, }; - stbfile *z = (stbfile *)malloc(sizeof(*z)); - if (z) { - *z = m; - z->f = f; - } - return z; -} - -static int stb__nogetbyte(stbfile *f) { assert(0); return -1; } -static unsigned int stb__nogetdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; } -static int stb__noputbyte(stbfile *f, int ch) { assert(0); return 0; } -static unsigned int stb__noputdata(stbfile *f, void *buffer, unsigned int len) { assert(0); return 0; } -static void stb__nobackpatch(stbfile *f, unsigned int where, void *buffer, unsigned int len) { assert(0); } - -static int stb__bgetbyte(stbfile *s) -{ - if (s->indata < s->inend) - return *s->indata++; - else - return -1; -} - -static unsigned int stb__bgetdata(stbfile *s, void *buffer, unsigned int len) -{ - if (s->indata + len > s->inend) - len = s->inend - s->indata; - memcpy(buffer, s->indata, len); - s->indata += len; - return len; -} -static unsigned int stb__bsize(stbfile *s) { return s->inend - s->buffer; } -static unsigned int stb__btell(stbfile *s) { return s->indata - s->buffer; } - -static void stb__bclose(stbfile *s) -{ - if (s->various) - free(s->buffer); -} - -stbfile *stb_open_inbuffer(void *buffer, unsigned int len) -{ - stbfile m = { stb__bgetbyte, stb__bgetdata, - stb__noputbyte, stb__noputdata, - stb__bsize, stb__btell, stb__nobackpatch, stb__bclose }; - stbfile *z = (stbfile *)malloc(sizeof(*z)); - if (z) { - *z = m; - z->buffer = (unsigned char *)buffer; - z->indata = z->buffer; - z->inend = z->indata + len; - } - return z; -} - -stbfile *stb_open_inbuffer_free(void *buffer, unsigned int len) -{ - stbfile *z = stb_open_inbuffer(buffer, len); - if (z) - z->various = 1; // free - return z; -} - -#ifndef STB_VERSION -// if we've been cut-and-pasted elsewhere, you get a limited -// version of stb_open, without the 'k' flag and utf8 support -static void stb__fclose2(stbfile *f) -{ - fclose(f->f); -} - -stbfile *stb_open(char *filename, char *mode) -{ - FILE *f = fopen(filename, mode); - stbfile *s; - if (f == NULL) return NULL; - s = stb_openf(f); - if (s) - s->close = stb__fclose2; - return s; -} -#else -// the full version depends on some code in stb.h; this -// also includes the memory buffer output format implemented with stb_arr -static void stb__fclose2(stbfile *f) -{ - stb_fclose(f->f, f->various); -} - -stbfile *stb_open(char *filename, char *mode) -{ - FILE *f = stb_fopen(filename, mode[0] == 'k' ? mode + 1 : mode); - stbfile *s; - if (f == NULL) return NULL; - s = stb_openf(f); - if (s) { - s->close = stb__fclose2; - s->various = mode[0] == 'k' ? stb_keep_if_different : stb_keep_yes; - } - return s; -} - -static int stb__aputbyte(stbfile *f, int ch) -{ - stb_arr_push(f->buffer, ch); - return 1; -} -static unsigned int stb__aputdata(stbfile *f, void *data, unsigned int len) -{ - memcpy(stb_arr_addn(f->buffer, (int)len), data, len); - return len; -} -static unsigned int stb__asize(stbfile *f) { return stb_arr_len(f->buffer); } -static void stb__abackpatch(stbfile *f, unsigned int where, void *data, unsigned int len) -{ - memcpy(f->buffer + where, data, len); -} -static void stb__aclose(stbfile *f) -{ - *(unsigned char **)f->ptr = f->buffer; -} - -stbfile *stb_open_outbuffer(unsigned char **update_on_close) -{ - stbfile m = { stb__nogetbyte, stb__nogetdata, - stb__aputbyte, stb__aputdata, - stb__asize, stb__asize, stb__abackpatch, stb__aclose }; - stbfile *z = (stbfile *)malloc(sizeof(*z)); - if (z) { - z->ptr = update_on_close; - *z = m; - } - return z; -} -#endif -#endif - - -////////////////////////////////////////////////////////////////////////////// -// -// Arithmetic coder... based on cbloom's notes on the subject, should be -// less code than a huffman code. - -typedef struct -{ - unsigned int range_low; - unsigned int range_high; - unsigned int code, range; // decode - int buffered_u8; - int pending_ffs; - stbfile *output; -} stb_arith; - -STB_EXTERN void stb_arith_init_encode(stb_arith *a, stbfile *out); -STB_EXTERN void stb_arith_init_decode(stb_arith *a, stbfile *in); -STB_EXTERN stbfile *stb_arith_encode_close(stb_arith *a); -STB_EXTERN stbfile *stb_arith_decode_close(stb_arith *a); - -STB_EXTERN void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq); -STB_EXTERN void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq); -STB_EXTERN unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq); -STB_EXTERN void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq); -STB_EXTERN unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2); -STB_EXTERN void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq); - -STB_EXTERN void stb_arith_encode_byte(stb_arith *a, int byte); -STB_EXTERN int stb_arith_decode_byte(stb_arith *a); - -// this is a memory-inefficient way of doing things, but it's -// fast(?) and simple -typedef struct -{ - unsigned short cumfreq; - unsigned short samples; -} stb_arith_symstate_item; - -typedef struct -{ - int num_sym; - unsigned int pow2; - int countdown; - stb_arith_symstate_item data[1]; -} stb_arith_symstate; - -#ifdef STB_DEFINE -void stb_arith_init_encode(stb_arith *a, stbfile *out) -{ - a->range_low = 0; - a->range_high = 0xffffffff; - a->pending_ffs = -1; // means no buffered character currently, to speed up normal case - a->output = out; -} - -static void stb__arith_carry(stb_arith *a) -{ - int i; - assert(a->pending_ffs != -1); // can't carry with no data - stb_putc(a->output, a->buffered_u8); - for (i = 0; i < a->pending_ffs; ++i) - stb_putc(a->output, 0); -} - -static void stb__arith_putbyte(stb_arith *a, int byte) -{ - if (a->pending_ffs) { - if (a->pending_ffs == -1) { // means no buffered data; encoded for fast path efficiency - if (byte == 0xff) - stb_putc(a->output, byte); // just write it immediately - else { - a->buffered_u8 = byte; - a->pending_ffs = 0; - } - } - else if (byte == 0xff) { - ++a->pending_ffs; - } - else { - int i; - stb_putc(a->output, a->buffered_u8); - for (i = 0; i < a->pending_ffs; ++i) - stb_putc(a->output, 0xff); - } - } - else if (byte == 0xff) { - ++a->pending_ffs; - } - else { - // fast path - stb_putc(a->output, a->buffered_u8); - a->buffered_u8 = byte; - } -} - -static void stb__arith_flush(stb_arith *a) -{ - if (a->pending_ffs >= 0) { - int i; - stb_putc(a->output, a->buffered_u8); - for (i = 0; i < a->pending_ffs; ++i) - stb_putc(a->output, 0xff); - } -} - -static void stb__renorm_encoder(stb_arith *a) -{ - stb__arith_putbyte(a, a->range_low >> 24); - a->range_low <<= 8; - a->range_high = (a->range_high << 8) | 0xff; -} - -static void stb__renorm_decoder(stb_arith *a) -{ - int c = stb_getc(a->output); - a->code = (a->code << 8) + (c >= 0 ? c : 0); // if EOF, insert 0 -} - -void stb_arith_encode(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq) -{ - unsigned int range = a->range_high - a->range_low; - unsigned int old = a->range_low; - range /= totalfreq; - a->range_low += range * cumfreq; - a->range_high = a->range_low + range*freq; - if (a->range_low < old) - stb__arith_carry(a); - while (a->range_high - a->range_low < 0x1000000) - stb__renorm_encoder(a); -} - -void stb_arith_encode_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq) -{ - unsigned int range = a->range_high - a->range_low; - unsigned int old = a->range_low; - range >>= totalfreq2; - a->range_low += range * cumfreq; - a->range_high = a->range_low + range*freq; - if (a->range_low < old) - stb__arith_carry(a); - while (a->range_high - a->range_low < 0x1000000) - stb__renorm_encoder(a); -} - -unsigned int stb_arith_decode_value(stb_arith *a, unsigned int totalfreq) -{ - unsigned int freqsize = a->range / totalfreq; - unsigned int z = a->code / freqsize; - return z >= totalfreq ? totalfreq - 1 : z; -} - -void stb_arith_decode_advance(stb_arith *a, unsigned int totalfreq, unsigned int freq, unsigned int cumfreq) -{ - unsigned int freqsize = a->range / totalfreq; // @OPTIMIZE, share with above divide somehow? - a->code -= freqsize * cumfreq; - a->range = freqsize * freq; - while (a->range < 0x1000000) - stb__renorm_decoder(a); -} - -unsigned int stb_arith_decode_value_log2(stb_arith *a, unsigned int totalfreq2) -{ - unsigned int freqsize = a->range >> totalfreq2; - unsigned int z = a->code / freqsize; - return z >= (1U << totalfreq2) ? (1U << totalfreq2) - 1 : z; -} - -void stb_arith_decode_advance_log2(stb_arith *a, unsigned int totalfreq2, unsigned int freq, unsigned int cumfreq) -{ - unsigned int freqsize = a->range >> totalfreq2; - a->code -= freqsize * cumfreq; - a->range = freqsize * freq; - while (a->range < 0x1000000) - stb__renorm_decoder(a); -} - -stbfile *stb_arith_encode_close(stb_arith *a) -{ - // put exactly as many bytes as we'll read, so we can turn on/off arithmetic coding in a stream - stb__arith_putbyte(a, a->range_low >> 24); - stb__arith_putbyte(a, a->range_low >> 16); - stb__arith_putbyte(a, a->range_low >> 8); - stb__arith_putbyte(a, a->range_low >> 0); - stb__arith_flush(a); - return a->output; -} - -stbfile *stb_arith_decode_close(stb_arith *a) -{ - return a->output; -} - -// this is a simple power-of-two based model -- using -// power of two means we need one divide per decode, -// not two. -#define POW2_LIMIT 12 -stb_arith_symstate *stb_arith_state_create(int num_sym) -{ - stb_arith_symstate *s = (stb_arith_symstate *)malloc(sizeof(*s) + (num_sym - 1) * sizeof(s->data[0])); - if (s) { - int i, cf, cf_next, next; - int start_freq, extra; - s->num_sym = num_sym; - s->pow2 = 4; - while (s->pow2 < 15 && (1 << s->pow2) < 3 * num_sym) { - ++s->pow2; - } - start_freq = (1 << s->pow2) / num_sym; - assert(start_freq >= 1); - extra = (1 << s->pow2) % num_sym; - // now set up the initial stats - - if (s->pow2 < POW2_LIMIT) - next = 0; - else - next = 1; - - cf = cf_next = 0; - for (i = 0; i < extra; ++i) { - s->data[i].cumfreq = cf; - s->data[i].samples = next; - cf += start_freq + 1; - cf_next += next; - } - for (; i < num_sym; ++i) { - s->data[i].cumfreq = cf; - s->data[i].samples = next; - cf += start_freq; - cf_next += next; - } - assert(cf == (1 << s->pow2)); - // now, how long should we go until we have 2 << s->pow2 samples? - s->countdown = (2 << s->pow2) - cf - cf_next; - } - return s; -} - -static void stb_arith_state_rescale(stb_arith_symstate *s) -{ - if (s->pow2 < POW2_LIMIT) { - int pcf, cf, cf_next, next, i; - ++s->pow2; - if (s->pow2 < POW2_LIMIT) - next = 0; - else - next = 1; - cf = cf_next = 0; - pcf = 0; - for (i = 0; i < s->num_sym; ++i) { - int sample = s->data[i].cumfreq - pcf + s->data[i].samples; - s->data[i].cumfreq = cf; - cf += sample; - s->data[i].samples = next; - cf_next += next; - } - assert(cf == (1 << s->pow2)); - s->countdown = (2 << s->pow2) - cf - cf_next; - } - else { - int pcf, cf, cf_next, i; - cf = cf_next = 0; - pcf = 0; - for (i = 0; i < s->num_sym; ++i) { - int sample = (s->data[i].cumfreq - pcf + s->data[i].samples) >> 1; - s->data[i].cumfreq = cf; - cf += sample; - s->data[i].samples = 1; - cf_next += 1; - } - assert(cf == (1 << s->pow2)); // this isn't necessarily true, due to rounding down! - s->countdown = (2 << s->pow2) - cf - cf_next; - } -} - -void stb_arith_encode_byte(stb_arith *a, int byte) -{ -} - -int stb_arith_decode_byte(stb_arith *a) -{ - return -1; -} -#endif - -////////////////////////////////////////////////////////////////////////////// -// -// Threads -// - -#ifndef _WIN32 -#ifdef STB_THREADS -#error "threads not implemented except for Windows" -#endif -#endif - -// call this function to free any global variables for memory testing -STB_EXTERN void stb_thread_cleanup(void); - -typedef void * (*stb_thread_func)(void *); - -// do not rely on these types, this is an implementation detail. -// compare against STB_THREAD_NULL and ST_SEMAPHORE_NULL -typedef void *stb_thread; -typedef void *stb_semaphore; -typedef void *stb_mutex; -typedef struct stb__sync *stb_sync; - -#define STB_SEMAPHORE_NULL NULL -#define STB_THREAD_NULL NULL -#define STB_MUTEX_NULL NULL -#define STB_SYNC_NULL NULL - -// get the number of processors (limited to those in the affinity mask for this process). -STB_EXTERN int stb_processor_count(void); -// force to run on a single core -- needed for RDTSC to work, e.g. for iprof -STB_EXTERN void stb_force_uniprocessor(void); - -// stb_work functions: queue up work to be done by some worker threads - -// set number of threads to serve the queue; you can change this on the fly, -// but if you decrease it, it won't decrease until things currently on the -// queue are finished -STB_EXTERN void stb_work_numthreads(int n); -// set maximum number of units in the queue; you can only set this BEFORE running any work functions -STB_EXTERN int stb_work_maxunits(int n); -// enqueue some work to be done (can do this from any thread, or even from a piece of work); -// return value of f is stored in *return_code if non-NULL -STB_EXTERN int stb_work(stb_thread_func f, void *d, volatile void **return_code); -// as above, but stb_sync_reach is called on 'rel' after work is complete -STB_EXTERN int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel); - - -// necessary to call this when using volatile to order writes/reads -STB_EXTERN void stb_barrier(void); - -// support for independent queues with their own threads - -typedef struct stb__workqueue stb_workqueue; - -STB_EXTERN stb_workqueue*stb_workq_new(int numthreads, int max_units); -STB_EXTERN stb_workqueue*stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex); -STB_EXTERN void stb_workq_delete(stb_workqueue *q); -STB_EXTERN void stb_workq_numthreads(stb_workqueue *q, int n); -STB_EXTERN int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code); -STB_EXTERN int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel); -STB_EXTERN int stb_workq_length(stb_workqueue *q); - -STB_EXTERN stb_thread stb_create_thread(stb_thread_func f, void *d); -STB_EXTERN stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel); -STB_EXTERN void stb_destroy_thread(stb_thread t); - -STB_EXTERN stb_semaphore stb_sem_new(int max_val); -STB_EXTERN stb_semaphore stb_sem_new_extra(int max_val, int start_val); -STB_EXTERN void stb_sem_delete(stb_semaphore s); -STB_EXTERN void stb_sem_waitfor(stb_semaphore s); -STB_EXTERN void stb_sem_release(stb_semaphore s); - -STB_EXTERN stb_mutex stb_mutex_new(void); -STB_EXTERN void stb_mutex_delete(stb_mutex m); -STB_EXTERN void stb_mutex_begin(stb_mutex m); -STB_EXTERN void stb_mutex_end(stb_mutex m); - -STB_EXTERN stb_sync stb_sync_new(void); -STB_EXTERN void stb_sync_delete(stb_sync s); -STB_EXTERN int stb_sync_set_target(stb_sync s, int count); -STB_EXTERN void stb_sync_reach_and_wait(stb_sync s); // wait for 'target' reachers -STB_EXTERN int stb_sync_reach(stb_sync s); - -typedef struct stb__threadqueue stb_threadqueue; -#define STB_THREADQ_DYNAMIC 0 -STB_EXTERN stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove); -STB_EXTERN void stb_threadq_delete(stb_threadqueue *tq); -STB_EXTERN int stb_threadq_get(stb_threadqueue *tq, void *output); -STB_EXTERN void stb_threadq_get_block(stb_threadqueue *tq, void *output); -STB_EXTERN int stb_threadq_add(stb_threadqueue *tq, void *input); -// can return FALSE if STB_THREADQ_DYNAMIC and attempt to grow fails -STB_EXTERN int stb_threadq_add_block(stb_threadqueue *tq, void *input); - -#ifdef STB_THREADS -#ifdef STB_DEFINE - -typedef struct -{ - stb_thread_func f; - void *d; - volatile void **return_val; - stb_semaphore sem; -} stb__thread; - -// this is initialized along all possible paths to create threads, therefore -// it's always initialized before any other threads are create, therefore -// it's free of races AS LONG AS you only create threads through stb_* -static stb_mutex stb__threadmutex, stb__workmutex; - -static void stb__threadmutex_init(void) -{ - if (stb__threadmutex == STB_SEMAPHORE_NULL) { - stb__threadmutex = stb_mutex_new(); - stb__workmutex = stb_mutex_new(); - } -} - -#ifdef STB_THREAD_TEST -volatile float stb__t1 = 1, stb__t2; - -static void stb__wait(int n) -{ - float z = 0; - int i; - for (i = 0; i < n; ++i) - z += 1 / (stb__t1 + i); - stb__t2 = z; -} -#else -#define stb__wait(x) -#endif - -#ifdef _WIN32 - -// avoid including windows.h -- note that our definitions aren't -// exactly the same (we don't define the security descriptor struct) -// so if you want to include windows.h, make sure you do it first. -#include <process.h> - -#ifndef _WINDOWS_ // check windows.h guard -#define STB__IMPORT STB_EXTERN __declspec(dllimport) -#define STB__DW unsigned long - -STB__IMPORT int __stdcall TerminateThread(void *, STB__DW); -STB__IMPORT void * __stdcall CreateSemaphoreA(void *sec, long, long, char*); -STB__IMPORT int __stdcall CloseHandle(void *); -STB__IMPORT STB__DW __stdcall WaitForSingleObject(void *, STB__DW); -STB__IMPORT int __stdcall ReleaseSemaphore(void *, long, long *); -STB__IMPORT void __stdcall Sleep(STB__DW); -#endif - -// necessary to call this when using volatile to order writes/reads -void stb_barrier(void) -{ -#ifdef MemoryBarrier - MemoryBarrier(); -#else - long temp; - __asm xchg temp, eax; -#endif -} - -static void stb__thread_run(void *t) -{ - void *res; - stb__thread info = *(stb__thread *)t; - free(t); - res = info.f(info.d); - if (info.return_val) - *info.return_val = res; - if (info.sem != STB_SEMAPHORE_NULL) - stb_sem_release(info.sem); -} - -static stb_thread stb_create_thread_raw(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel) -{ -#ifdef _MT -#if defined(STB_FASTMALLOC) && !defined(STB_FASTMALLOC_ITS_OKAY_I_ONLY_MALLOC_IN_ONE_THREAD) - stb_fatal("Error! Cannot use STB_FASTMALLOC with threads.\n"); - return STB_THREAD_NULL; -#else - unsigned long id; - stb__thread *data = (stb__thread *)malloc(sizeof(*data)); - if (!data) return NULL; - stb__threadmutex_init(); - data->f = f; - data->d = d; - data->return_val = return_code; - data->sem = rel; - id = _beginthread(stb__thread_run, 0, data); - if (id == -1) return NULL; - return (void *)id; -#endif -#else -#ifdef STB_NO_STB_STRINGS - stb_fatal("Invalid compilation"); -#else - stb_fatal("Must compile mult-threaded to use stb_thread/stb_work."); -#endif - return NULL; -#endif -} - -// trivial win32 wrappers -void stb_destroy_thread(stb_thread t) { TerminateThread(t, 0); } -stb_semaphore stb_sem_new(int maxv) { return CreateSemaphoreA(NULL, 0, maxv, NULL); } -stb_semaphore stb_sem_new_extra(int maxv, int start) { return CreateSemaphoreA(NULL, start, maxv, NULL); } -void stb_sem_delete(stb_semaphore s) { if (s != NULL) CloseHandle(s); } -void stb_sem_waitfor(stb_semaphore s) { WaitForSingleObject(s, 0xffffffff); } // INFINITE -void stb_sem_release(stb_semaphore s) { ReleaseSemaphore(s, 1, NULL); } -static void stb__thread_sleep(int ms) { Sleep(ms); } - -#ifndef _WINDOWS_ -STB__IMPORT int __stdcall GetProcessAffinityMask(void *, STB__DW *, STB__DW *); -STB__IMPORT void * __stdcall GetCurrentProcess(void); -STB__IMPORT int __stdcall SetProcessAffinityMask(void *, STB__DW); -#endif - -int stb_processor_count(void) -{ - unsigned long proc, sys; - GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys); - return stb_bitcount(proc); -} - -void stb_force_uniprocessor(void) -{ - unsigned long proc, sys; - GetProcessAffinityMask(GetCurrentProcess(), &proc, &sys); - if (stb_bitcount(proc) > 1) { - int z; - for (z = 0; z < 32; ++z) - if (proc & (1 << z)) - break; - if (z < 32) { - proc = 1 << z; - SetProcessAffinityMask(GetCurrentProcess(), proc); - } - } -} - -#ifdef _WINDOWS_ -#define STB_MUTEX_NATIVE -void *stb_mutex_new(void) -{ - CRITICAL_SECTION *p = (CRITICAL_SECTION *)malloc(sizeof(*p)); - if (p) -#if _WIN32_WINNT >= 0x0500 - InitializeCriticalSectionAndSpinCount(p, 500); -#else - InitializeCriticalSection(p); -#endif - return p; -} - -void stb_mutex_delete(void *p) -{ - if (p) { - DeleteCriticalSection((CRITICAL_SECTION *)p); - free(p); - } -} - -void stb_mutex_begin(void *p) -{ - stb__wait(500); - if (p) - EnterCriticalSection((CRITICAL_SECTION *)p); -} - -void stb_mutex_end(void *p) -{ - if (p) - LeaveCriticalSection((CRITICAL_SECTION *)p); - stb__wait(500); -} -#endif // _WINDOWS_ - -#if 0 -// for future reference, -// InterlockedCompareExchange for x86: -int cas64_mp(void * dest, void * xcmp, void * xxchg) { - __asm - { - mov esi, [xxchg]; exchange - mov ebx, [esi + 0] - mov ecx, [esi + 4] - - mov esi, [xcmp]; comparand - mov eax, [esi + 0] - mov edx, [esi + 4] - - mov edi, [dest]; destination - lock cmpxchg8b[edi] - jz yyyy; - - mov[esi + 0], eax; - mov[esi + 4], edx; - - yyyy: - xor eax, eax; - setz al; - }; - - inline unsigned __int64 _InterlockedCompareExchange64(volatile unsigned __int64 *dest - , unsigned __int64 exchange - , unsigned __int64 comperand) - { - //value returned in eax::edx - __asm { - lea esi, comperand; - lea edi, exchange; - - mov eax, [esi]; - mov edx, 4[esi]; - mov ebx, [edi]; - mov ecx, 4[edi]; - mov esi, dest; - lock CMPXCHG8B[esi]; - } -#endif // #if 0 - -#endif // _WIN32 - - stb_thread stb_create_thread2(stb_thread_func f, void *d, volatile void **return_code, stb_semaphore rel) - { - return stb_create_thread_raw(f, d, return_code, rel); - } - - stb_thread stb_create_thread(stb_thread_func f, void *d) - { - return stb_create_thread2(f, d, NULL, STB_SEMAPHORE_NULL); - } - - // mutex implemented by wrapping semaphore -#ifndef STB_MUTEX_NATIVE - stb_mutex stb_mutex_new(void) { return stb_sem_new_extra(1, 1); } - void stb_mutex_delete(stb_mutex m) { stb_sem_delete(m); } - void stb_mutex_begin(stb_mutex m) { stb__wait(500); if (m) stb_sem_waitfor(m); } - void stb_mutex_end(stb_mutex m) { if (m) stb_sem_release(m); stb__wait(500); } -#endif - - // thread merge operation - struct stb__sync - { - int target; // target number of threads to hit it - int sofar; // total threads that hit it - int waiting; // total threads waiting - - stb_mutex start; // mutex to prevent starting again before finishing previous - stb_mutex mutex; // mutex while tweaking state - stb_semaphore release; // semaphore wake up waiting threads - // we have to wake them up one at a time, rather than using a single release - // call, because win32 semaphores don't let you dynamically change the max count! - }; - - stb_sync stb_sync_new(void) - { - stb_sync s = (stb_sync)malloc(sizeof(*s)); - if (!s) return s; - - s->target = s->sofar = s->waiting = 0; - s->mutex = stb_mutex_new(); - s->start = stb_mutex_new(); - s->release = stb_sem_new(1); - if (s->mutex == STB_MUTEX_NULL || s->release == STB_SEMAPHORE_NULL || s->start == STB_MUTEX_NULL) { - stb_mutex_delete(s->mutex); - stb_mutex_delete(s->mutex); - stb_sem_delete(s->release); - free(s); - return NULL; - } - return s; - } - - void stb_sync_delete(stb_sync s) - { - if (s->waiting) { - // it's bad to delete while there are threads waiting! - // shall we wait for them to reach, or just bail? just bail - assert(0); - } - stb_mutex_delete(s->mutex); - stb_mutex_delete(s->release); - free(s); - } - - int stb_sync_set_target(stb_sync s, int count) - { - // don't allow setting a target until the last one is fully released; - // note that this can lead to inefficient pipelining, and maybe we'd - // be better off ping-ponging between two internal syncs? - // I tried seeing how often this happened using TryEnterCriticalSection - // and could _never_ get it to happen in imv(stb), even with more threads - // than processors. So who knows! - stb_mutex_begin(s->start); - - // this mutex is pointless, since it's not valid for threads - // to call reach() before anyone calls set_target() anyway - stb_mutex_begin(s->mutex); - - assert(s->target == 0); // enforced by start mutex - s->target = count; - s->sofar = 0; - s->waiting = 0; - stb_mutex_end(s->mutex); - return STB_TRUE; - } - - void stb__sync_release(stb_sync s) - { - if (s->waiting) - stb_sem_release(s->release); - else { - s->target = 0; - stb_mutex_end(s->start); - } - } - - int stb_sync_reach(stb_sync s) - { - int n; - stb_mutex_begin(s->mutex); - assert(s->sofar < s->target); - n = ++s->sofar; // record this value to avoid possible race if we did 'return s->sofar'; - if (s->sofar == s->target) - stb__sync_release(s); - stb_mutex_end(s->mutex); - return n; - } - - void stb_sync_reach_and_wait(stb_sync s) - { - stb_mutex_begin(s->mutex); - assert(s->sofar < s->target); - ++s->sofar; - if (s->sofar == s->target) { - stb__sync_release(s); - stb_mutex_end(s->mutex); - } - else { - ++s->waiting; // we're waiting, so one more waiter - stb_mutex_end(s->mutex); // release the mutex to other threads - - stb_sem_waitfor(s->release); // wait for merge completion - - stb_mutex_begin(s->mutex); // on merge completion, grab the mutex - --s->waiting; // we're done waiting - stb__sync_release(s); // restart the next waiter - stb_mutex_end(s->mutex); // and now we're done - // this ends the same as the first case, but it's a lot - // clearer to understand without sharing the code - } - } - - struct stb__threadqueue - { - stb_mutex add, remove; - stb_semaphore nonempty, nonfull; - int head_blockers; // number of threads blocking--used to know whether to release(avail) - int tail_blockers; - int head, tail, array_size, growable; - int item_size; - char *data; - }; - - static int stb__tq_wrap(volatile stb_threadqueue *z, int p) - { - if (p == z->array_size) - return p - z->array_size; - else - return p; - } - - int stb__threadq_get_raw(stb_threadqueue *tq2, void *output, int block) - { - volatile stb_threadqueue *tq = (volatile stb_threadqueue *)tq2; - if (tq->head == tq->tail && !block) return 0; - - stb_mutex_begin(tq->remove); - - while (tq->head == tq->tail) { - if (!block) { - stb_mutex_end(tq->remove); - return 0; - } - ++tq->head_blockers; - stb_mutex_end(tq->remove); - - stb_sem_waitfor(tq->nonempty); - - stb_mutex_begin(tq->remove); - --tq->head_blockers; - } - - memcpy(output, tq->data + tq->head*tq->item_size, tq->item_size); - stb_barrier(); - tq->head = stb__tq_wrap(tq, tq->head + 1); - - stb_sem_release(tq->nonfull); - if (tq->head_blockers) // can't check if actually non-empty due to race? - stb_sem_release(tq->nonempty); // if there are other blockers, wake one - - stb_mutex_end(tq->remove); - return STB_TRUE; - } - - int stb__threadq_grow(volatile stb_threadqueue *tq) - { - int n; - char *p; - assert(tq->remove != STB_MUTEX_NULL); // must have this to allow growth! - stb_mutex_begin(tq->remove); - - n = tq->array_size * 2; - p = (char *)realloc(tq->data, n * tq->item_size); - if (p == NULL) { - stb_mutex_end(tq->remove); - stb_mutex_end(tq->add); - return STB_FALSE; - } - if (tq->tail < tq->head) { - memcpy(p + tq->array_size * tq->item_size, p, tq->tail * tq->item_size); - tq->tail += tq->array_size; - } - tq->data = p; - tq->array_size = n; - - stb_mutex_end(tq->remove); - return STB_TRUE; - } - - int stb__threadq_add_raw(stb_threadqueue *tq2, void *input, int block) - { - int tail, pos; - volatile stb_threadqueue *tq = (volatile stb_threadqueue *)tq2; - stb_mutex_begin(tq->add); - for (;;) { - pos = tq->tail; - tail = stb__tq_wrap(tq, pos + 1); - if (tail != tq->head) break; - - // full - if (tq->growable) { - if (!stb__threadq_grow(tq)) { - stb_mutex_end(tq->add); - return STB_FALSE; // out of memory - } - } - else if (!block) { - stb_mutex_end(tq->add); - return STB_FALSE; - } - else { - ++tq->tail_blockers; - stb_mutex_end(tq->add); - - stb_sem_waitfor(tq->nonfull); - - stb_mutex_begin(tq->add); - --tq->tail_blockers; - } - } - memcpy(tq->data + tq->item_size * pos, input, tq->item_size); - stb_barrier(); - tq->tail = tail; - stb_sem_release(tq->nonempty); - if (tq->tail_blockers) // can't check if actually non-full due to race? - stb_sem_release(tq->nonfull); - stb_mutex_end(tq->add); - return STB_TRUE; - } - - int stb_threadq_length(stb_threadqueue *tq2) - { - int a, b, n; - volatile stb_threadqueue *tq = (volatile stb_threadqueue *)tq2; - stb_mutex_begin(tq->add); - a = tq->head; - b = tq->tail; - n = tq->array_size; - stb_mutex_end(tq->add); - if (a > b) b += n; - return b - a; - } - - int stb_threadq_get(stb_threadqueue *tq, void *output) - { - return stb__threadq_get_raw(tq, output, STB_FALSE); - } - - void stb_threadq_get_block(stb_threadqueue *tq, void *output) - { - stb__threadq_get_raw(tq, output, STB_TRUE); - } - - int stb_threadq_add(stb_threadqueue *tq, void *input) - { - return stb__threadq_add_raw(tq, input, STB_FALSE); - } - - int stb_threadq_add_block(stb_threadqueue *tq, void *input) - { - return stb__threadq_add_raw(tq, input, STB_TRUE); - } - - void stb_threadq_delete(stb_threadqueue *tq) - { - if (tq) { - free(tq->data); - stb_mutex_delete(tq->add); - stb_mutex_delete(tq->remove); - stb_sem_delete(tq->nonempty); - stb_sem_delete(tq->nonfull); - free(tq); - } - } - -#define STB_THREADQUEUE_DYNAMIC 0 - stb_threadqueue *stb_threadq_new(int item_size, int num_items, int many_add, int many_remove) - { - int error = 0; - stb_threadqueue *tq = (stb_threadqueue *)malloc(sizeof(*tq)); - if (tq == NULL) return NULL; - - if (num_items == STB_THREADQUEUE_DYNAMIC) { - tq->growable = STB_TRUE; - num_items = 32; - } - else - tq->growable = STB_FALSE; - - tq->item_size = item_size; - tq->array_size = num_items + 1; - - tq->add = tq->remove = STB_MUTEX_NULL; - tq->nonempty = tq->nonfull = STB_SEMAPHORE_NULL; - tq->data = NULL; - if (many_add) - { - tq->add = stb_mutex_new(); if (tq->add == STB_MUTEX_NULL) goto error; - } - if (many_remove || tq->growable) - { - tq->remove = stb_mutex_new(); if (tq->remove == STB_MUTEX_NULL) goto error; - } - tq->nonempty = stb_sem_new(1); if (tq->nonempty == STB_SEMAPHORE_NULL) goto error; - tq->nonfull = stb_sem_new(1); if (tq->nonfull == STB_SEMAPHORE_NULL) goto error; - tq->data = (char *)malloc(tq->item_size * tq->array_size); - if (tq->data == NULL) goto error; - - tq->head = tq->tail = 0; - tq->head_blockers = tq->tail_blockers = 0; - - return tq; - - error: - stb_threadq_delete(tq); - return NULL; - } - - typedef struct - { - stb_thread_func f; - void *d; - volatile void **retval; - stb_sync sync; - } stb__workinfo; - - //static volatile stb__workinfo *stb__work; - - struct stb__workqueue - { - int numthreads; - stb_threadqueue *tq; - }; - - static stb_workqueue *stb__work_global; - - static void *stb__thread_workloop(void *p) - { - volatile stb_workqueue *q = (volatile stb_workqueue *)p; - for (;;) { - void *z; - stb__workinfo w; - stb_threadq_get_block(q->tq, &w); - if (w.f == NULL) // null work is a signal to end the thread - return NULL; - z = w.f(w.d); - if (w.retval) { stb_barrier(); *w.retval = z; } - if (w.sync != STB_SYNC_NULL) stb_sync_reach(w.sync); - } - } - - stb_workqueue *stb_workq_new(int num_threads, int max_units) - { - return stb_workq_new_flags(num_threads, max_units, 0, 0); - } - - stb_workqueue *stb_workq_new_flags(int numthreads, int max_units, int no_add_mutex, int no_remove_mutex) - { - stb_workqueue *q = (stb_workqueue *)malloc(sizeof(*q)); - if (q == NULL) return NULL; - q->tq = stb_threadq_new(sizeof(stb__workinfo), max_units, !no_add_mutex, !no_remove_mutex); - if (q->tq == NULL) { free(q); return NULL; } - q->numthreads = 0; - stb_workq_numthreads(q, numthreads); - return q; - } - - void stb_workq_delete(stb_workqueue *q) - { - while (stb_workq_length(q) != 0) - stb__thread_sleep(1); - stb_threadq_delete(q->tq); - free(q); - } - - static int stb__work_maxitems = STB_THREADQUEUE_DYNAMIC; - - static void stb_work_init(int num_threads) - { - if (stb__work_global == NULL) { - stb__threadmutex_init(); - stb_mutex_begin(stb__workmutex); - stb_barrier(); - if (*(stb_workqueue * volatile *)&stb__work_global == NULL) - stb__work_global = stb_workq_new(num_threads, stb__work_maxitems); - stb_mutex_end(stb__workmutex); - } - } - - static int stb__work_raw(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel) - { - stb__workinfo w; - if (q == NULL) { - stb_work_init(1); - q = stb__work_global; - } - w.f = f; - w.d = d; - w.retval = return_code; - w.sync = rel; - return stb_threadq_add(q->tq, &w); - } - - int stb_workq_length(stb_workqueue *q) - { - return stb_threadq_length(q->tq); - } - - int stb_workq(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code) - { - if (f == NULL) return 0; - return stb_workq_reach(q, f, d, return_code, NULL); - } - - int stb_workq_reach(stb_workqueue *q, stb_thread_func f, void *d, volatile void **return_code, stb_sync rel) - { - if (f == NULL) return 0; - return stb__work_raw(q, f, d, return_code, rel); - } - - static void stb__workq_numthreads(stb_workqueue *q, int n) - { - while (q->numthreads < n) { - stb_create_thread(stb__thread_workloop, q); - ++q->numthreads; - } - while (q->numthreads > n) { - stb__work_raw(q, NULL, NULL, NULL, NULL); - --q->numthreads; - } - } - - void stb_workq_numthreads(stb_workqueue *q, int n) - { - stb_mutex_begin(stb__threadmutex); - stb__workq_numthreads(q, n); - stb_mutex_end(stb__threadmutex); - } - - int stb_work_maxunits(int n) - { - if (stb__work_global == NULL) { - stb__work_maxitems = n; - stb_work_init(1); - } - return stb__work_maxitems; - } - - int stb_work(stb_thread_func f, void *d, volatile void **return_code) - { - return stb_workq(stb__work_global, f, d, return_code); - } - - int stb_work_reach(stb_thread_func f, void *d, volatile void **return_code, stb_sync rel) - { - return stb_workq_reach(stb__work_global, f, d, return_code, rel); - } - - void stb_work_numthreads(int n) - { - if (stb__work_global == NULL) - stb_work_init(n); - else - stb_workq_numthreads(stb__work_global, n); - } -#endif // STB_DEFINE - - - ////////////////////////////////////////////////////////////////////////////// - // - // Background disk I/O - // - // - -#define STB_BGIO_READ_ALL (-1) - STB_EXTERN int stb_bgio_read(char *filename, int offset, int len, stb_uchar **result, int *olen); - STB_EXTERN int stb_bgio_readf(FILE *f, int offset, int len, stb_uchar **result, int *olen); - STB_EXTERN int stb_bgio_read_to(char *filename, int offset, int len, stb_uchar *buffer, int *olen); - STB_EXTERN int stb_bgio_readf_to(FILE *f, int offset, int len, stb_uchar *buffer, int *olen); - - typedef struct - { - int have_data; - int is_valid; - int is_dir; - time_t filetime; - stb_int64 filesize; - } stb_bgstat; - - STB_EXTERN int stb_bgio_stat(char *filename, stb_bgstat *result); - -#ifdef STB_DEFINE - - static stb_workqueue *stb__diskio; - static stb_mutex stb__diskio_mutex; - - void stb_thread_cleanup(void) - { - if (stb__work_global) stb_workq_delete(stb__work_global); stb__work_global = NULL; - if (stb__threadmutex) stb_mutex_delete(stb__threadmutex); stb__threadmutex = NULL; - if (stb__workmutex) stb_mutex_delete(stb__workmutex); stb__workmutex = NULL; - if (stb__diskio) stb_workq_delete(stb__diskio); stb__diskio = NULL; - if (stb__diskio_mutex)stb_mutex_delete(stb__diskio_mutex); stb__diskio_mutex = NULL; - } - - - typedef struct - { - char *filename; - FILE *f; - int offset; - int len; - - stb_bgstat *stat_out; - stb_uchar *output; - stb_uchar **result; - int *len_output; - int *flag; - } stb__disk_command; - -#define STB__MAX_DISK_COMMAND 100 - static stb__disk_command stb__dc_queue[STB__MAX_DISK_COMMAND]; - static int stb__dc_offset; - - void stb__io_init(void) - { - if (!stb__diskio) { - stb__threadmutex_init(); - stb_mutex_begin(stb__threadmutex); - stb_barrier(); - if (*(stb_thread * volatile *)&stb__diskio == NULL) { - stb__diskio_mutex = stb_mutex_new(); - // use many threads so OS can try to schedule seeks - stb__diskio = stb_workq_new_flags(16, STB__MAX_DISK_COMMAND, STB_FALSE, STB_FALSE); - } - stb_mutex_end(stb__threadmutex); - } - } - - static void * stb__io_error(stb__disk_command *dc) - { - if (dc->len_output) *dc->len_output = 0; - if (dc->result) *dc->result = NULL; - if (dc->flag) *dc->flag = -1; - return NULL; - } - - static void * stb__io_task(void *p) - { - stb__disk_command *dc = (stb__disk_command *)p; - int len; - FILE *f; - stb_uchar *buf; - - if (dc->stat_out) { - struct _stati64 s; - if (!_stati64(dc->filename, &s)) { - dc->stat_out->filesize = s.st_size; - dc->stat_out->filetime = s.st_mtime; - dc->stat_out->is_dir = s.st_mode & _S_IFDIR; - dc->stat_out->is_valid = (s.st_mode & _S_IFREG) || dc->stat_out->is_dir; - } - else - dc->stat_out->is_valid = 0; - stb_barrier(); - dc->stat_out->have_data = 1; - free(dc->filename); - return 0; - } - if (dc->f) { -#ifdef WIN32 - f = _fdopen(_dup(_fileno(dc->f)), "rb"); -#else - f = fdopen(dup(fileno(dc->f)), "rb"); -#endif - if (!f) - return stb__io_error(dc); - } - else { - f = fopen(dc->filename, "rb"); - free(dc->filename); - if (!f) - return stb__io_error(dc); - } - - len = dc->len; - if (len < 0) { - fseek(f, 0, SEEK_END); - len = ftell(f) - dc->offset; - } - - if (fseek(f, dc->offset, SEEK_SET)) { - fclose(f); - return stb__io_error(dc); - } - - if (dc->output) - buf = dc->output; - else { - buf = (stb_uchar *)malloc(len); - if (buf == NULL) { - fclose(f); - return stb__io_error(dc); - } - } - - len = fread(buf, 1, len, f); - fclose(f); - if (dc->len_output) *dc->len_output = len; - if (dc->result) *dc->result = buf; - if (dc->flag) *dc->flag = 1; - - return NULL; - } - - int stb__io_add(char *fname, FILE *f, int off, int len, stb_uchar *out, stb_uchar **result, int *olen, int *flag, stb_bgstat *stat) - { - int res; - stb__io_init(); - // do memory allocation outside of mutex - if (fname) fname = strdup(fname); - stb_mutex_begin(stb__diskio_mutex); - { - stb__disk_command *dc = &stb__dc_queue[stb__dc_offset]; - dc->filename = fname; - dc->f = f; - dc->offset = off; - dc->len = len; - dc->output = out; - dc->result = result; - dc->len_output = olen; - dc->flag = flag; - dc->stat_out = stat; - res = stb_workq(stb__diskio, stb__io_task, dc, NULL); - if (res) - stb__dc_offset = (stb__dc_offset + 1 == STB__MAX_DISK_COMMAND ? 0 : stb__dc_offset + 1); - } - stb_mutex_end(stb__diskio_mutex); - return res; - } - - int stb_bgio_read(char *filename, int offset, int len, stb_uchar **result, int *olen) - { - return stb__io_add(filename, NULL, offset, len, NULL, result, olen, NULL, NULL); - } - - int stb_bgio_readf(FILE *f, int offset, int len, stb_uchar **result, int *olen) - { - return stb__io_add(NULL, f, offset, len, NULL, result, olen, NULL, NULL); - } - - int stb_bgio_read_to(char *filename, int offset, int len, stb_uchar *buffer, int *olen) - { - return stb__io_add(filename, NULL, offset, len, buffer, NULL, olen, NULL, NULL); - } - - int stb_bgio_readf_to(FILE *f, int offset, int len, stb_uchar *buffer, int *olen) - { - return stb__io_add(NULL, f, offset, len, buffer, NULL, olen, NULL, NULL); - } - - STB_EXTERN int stb_bgio_stat(char *filename, stb_bgstat *result) - { - result->have_data = 0; - return stb__io_add(filename, NULL, 0, 0, 0, NULL, 0, NULL, result); - } -#endif -#endif - - - - ////////////////////////////////////////////////////////////////////////////// - // - // Fast malloc implementation - // - // This is a clone of TCMalloc, but without the thread support. - // 1. large objects are allocated directly, page-aligned - // 2. small objects are allocated in homogeonous heaps, 0 overhead - // - // We keep an allocation table for pages a la TCMalloc. This would - // require 4MB for the entire address space, but we only allocate - // the parts that are in use. The overhead from using homogenous heaps - // everywhere is 3MB. (That is, if you allocate 1 object of each size, - // you'll use 3MB.) - -#if defined(STB_DEFINE) && (defined(_WIN32) || defined(STB_FASTMALLOC)) - -#ifdef _WIN32 -#ifndef _WINDOWS_ -#ifndef STB__IMPORT -#define STB__IMPORT STB_EXTERN __declspec(dllimport) -#define STB__DW unsigned long -#endif - STB__IMPORT void * __stdcall VirtualAlloc(void *p, unsigned long size, unsigned long type, unsigned long protect); - STB__IMPORT int __stdcall VirtualFree(void *p, unsigned long size, unsigned long freetype); -#endif -#define stb__alloc_pages_raw(x) (stb_uint32) VirtualAlloc(NULL, (x), 0x3000, 0x04) -#define stb__dealloc_pages_raw(p) VirtualFree((void *) p, 0, 0x8000) -#else -#error "Platform not currently supported" -#endif - - typedef struct stb__span - { - int start, len; - struct stb__span *next, *prev; - void *first_free; - unsigned short list; // 1..256 free; 257..511 sizeclass; 0=large block - short allocations; // # outstanding allocations for sizeclass - } stb__span; // 24 - - static stb__span **stb__span_for_page; - static int stb__firstpage, stb__lastpage; - static void stb__update_page_range(int first, int last) - { - stb__span **sfp; - int i, f, l; - if (first >= stb__firstpage && last <= stb__lastpage) return; - if (stb__span_for_page == NULL) { - f = first; - l = f + stb_max(last - f, 16384); - l = stb_min(l, 1 << 20); - } - else if (last > stb__lastpage) { - f = stb__firstpage; - l = f + (stb__lastpage - f) * 2; - l = stb_clamp(last, l, 1 << 20); - } - else { - l = stb__lastpage; - f = l - (l - stb__firstpage) * 2; - f = stb_clamp(f, 0, first); - } - sfp = (stb__span **)stb__alloc_pages_raw(sizeof(void *) * (l - f)); - for (i = f; i < stb__firstpage; ++i) sfp[i - f] = NULL; - for (; i < stb__lastpage; ++i) sfp[i - f] = stb__span_for_page[i - stb__firstpage]; - for (; i < l; ++i) sfp[i - f] = NULL; - if (stb__span_for_page) stb__dealloc_pages_raw(stb__span_for_page); - stb__firstpage = f; - stb__lastpage = l; - stb__span_for_page = sfp; - } - - static stb__span *stb__span_free = NULL; - static stb__span *stb__span_first, *stb__span_end; - static stb__span *stb__span_alloc(void) - { - stb__span *s = stb__span_free; - if (s) - stb__span_free = s->next; - else { - if (!stb__span_first) { - stb__span_first = (stb__span *)stb__alloc_pages_raw(65536); - if (stb__span_first == NULL) return NULL; - stb__span_end = stb__span_first + (65536 / sizeof(stb__span)); - } - s = stb__span_first++; - if (stb__span_first == stb__span_end) stb__span_first = NULL; - } - return s; - } - - static stb__span *stb__spanlist[512]; - - static void stb__spanlist_unlink(stb__span *s) - { - if (s->prev) - s->prev->next = s->next; - else { - int n = s->list; - assert(stb__spanlist[n] == s); - stb__spanlist[n] = s->next; - } - if (s->next) - s->next->prev = s->prev; - s->next = s->prev = NULL; - s->list = 0; - } - - static void stb__spanlist_add(int n, stb__span *s) - { - s->list = n; - s->next = stb__spanlist[n]; - s->prev = NULL; - stb__spanlist[n] = s; - if (s->next) s->next->prev = s; - } - -#define stb__page_shift 12 -#define stb__page_size (1 << stb__page_shift) -#define stb__page_number(x) ((x) >> stb__page_shift) -#define stb__page_address(x) ((x) << stb__page_shift) - - static void stb__set_span_for_page(stb__span *s) - { - int i; - for (i = 0; i < s->len; ++i) - stb__span_for_page[s->start + i - stb__firstpage] = s; - } - - static stb__span *stb__coalesce(stb__span *a, stb__span *b) - { - assert(a->start + a->len == b->start); - if (a->list) stb__spanlist_unlink(a); - if (b->list) stb__spanlist_unlink(b); - a->len += b->len; - b->len = 0; - b->next = stb__span_free; - stb__span_free = b; - stb__set_span_for_page(a); - return a; - } - - static void stb__free_span(stb__span *s) - { - stb__span *n = NULL; - if (s->start > stb__firstpage) { - n = stb__span_for_page[s->start - 1 - stb__firstpage]; - if (n && n->allocations == -2 && n->start + n->len == s->start) s = stb__coalesce(n, s); - } - if (s->start + s->len < stb__lastpage) { - n = stb__span_for_page[s->start + s->len - stb__firstpage]; - if (n && n->allocations == -2 && s->start + s->len == n->start) s = stb__coalesce(s, n); - } - s->allocations = -2; - stb__spanlist_add(s->len > 256 ? 256 : s->len, s); - } - - static stb__span *stb__alloc_pages(int num) - { - stb__span *s = stb__span_alloc(); - int p; - if (!s) return NULL; - p = stb__alloc_pages_raw(num << stb__page_shift); - if (p == 0) { s->next = stb__span_free; stb__span_free = s; return 0; } - assert(stb__page_address(stb__page_number(p)) == p); - p = stb__page_number(p); - stb__update_page_range(p, p + num); - s->start = p; - s->len = num; - s->next = NULL; - s->prev = NULL; - stb__set_span_for_page(s); - return s; - } - - static stb__span *stb__alloc_span(int pagecount) - { - int i; - stb__span *p = NULL; - for (i = pagecount; i < 256; ++i) - if (stb__spanlist[i]) { - p = stb__spanlist[i]; - break; - } - if (!p) { - p = stb__spanlist[256]; - while (p && p->len < pagecount) - p = p->next; - } - if (!p) { - p = stb__alloc_pages(pagecount < 16 ? 16 : pagecount); - if (p == NULL) return 0; - } - else - stb__spanlist_unlink(p); - - if (p->len > pagecount) { - stb__span *q = stb__span_alloc(); - if (q) { - q->start = p->start + pagecount; - q->len = p->len - pagecount; - p->len = pagecount; - for (i = 0; i < q->len; ++i) - stb__span_for_page[q->start + i - stb__firstpage] = q; - stb__spanlist_add(q->len > 256 ? 256 : q->len, q); - } - } - return p; - } - -#define STB__MAX_SMALL_SIZE 32768 -#define STB__MAX_SIZE_CLASSES 256 - - static unsigned char stb__class_base[32]; - static unsigned char stb__class_shift[32]; - static unsigned char stb__pages_for_class[STB__MAX_SIZE_CLASSES]; - static int stb__size_for_class[STB__MAX_SIZE_CLASSES]; - - stb__span *stb__get_nonempty_sizeclass(int c) - { - int s = c + 256, i, size, tsize; // remap to span-list index - char *z; - void *q; - stb__span *p = stb__spanlist[s]; - if (p) { - if (p->first_free) return p; // fast path: it's in the first one in list - for (p = p->next; p; p = p->next) - if (p->first_free) { - // move to front for future queries - stb__spanlist_unlink(p); - stb__spanlist_add(s, p); - return p; - } - } - // no non-empty ones, so allocate a new one - p = stb__alloc_span(stb__pages_for_class[c]); - if (!p) return NULL; - // create the free list up front - size = stb__size_for_class[c]; - tsize = stb__pages_for_class[c] << stb__page_shift; - i = 0; - z = (char *)stb__page_address(p->start); - q = NULL; - while (i + size <= tsize) { - *(void **)z = q; q = z; - z += size; - i += size; - } - p->first_free = q; - p->allocations = 0; - stb__spanlist_add(s, p); - return p; - } - - static int stb__sizeclass(size_t sz) - { - int z = stb_log2_floor(sz); // -1 below to group e.g. 13,14,15,16 correctly - return stb__class_base[z] + ((sz - 1) >> stb__class_shift[z]); - } - - static void stb__init_sizeclass(void) - { - int i, size, overhead; - int align_shift = 2; // allow 4-byte and 12-byte blocks as well, vs. TCMalloc - int next_class = 1; - int last_log = 0; - - for (i = 0; i < align_shift; i++) { - stb__class_base[i] = next_class; - stb__class_shift[i] = align_shift; - } - - for (size = 1 << align_shift; size <= STB__MAX_SMALL_SIZE; size += 1 << align_shift) { - i = stb_log2_floor(size); - if (i > last_log) { - if (size == 16) ++align_shift; // switch from 4-byte to 8-byte alignment - else if (size >= 128 && align_shift < 8) ++align_shift; - stb__class_base[i] = next_class - ((size - 1) >> align_shift); - stb__class_shift[i] = align_shift; - last_log = i; - } - stb__size_for_class[next_class++] = size; - } - - for (i = 1; i <= STB__MAX_SMALL_SIZE; ++i) - assert(i <= stb__size_for_class[stb__sizeclass(i)]); - - overhead = 0; - for (i = 1; i < next_class; i++) { - int s = stb__size_for_class[i]; - size = stb__page_size; - while (size % s > size >> 3) - size += stb__page_size; - stb__pages_for_class[i] = (unsigned char)(size >> stb__page_shift); - overhead += size; - } - assert(overhead < (4 << 20)); // make sure it's under 4MB of overhead - } - -#ifdef STB_DEBUG -#define stb__smemset(a,b,c) memset((void *) a, b, c) -#elif defined(STB_FASTMALLOC_INIT) -#define stb__smemset(a,b,c) memset((void *) a, b, c) -#else -#define stb__smemset(a,b,c) -#endif - void *stb_smalloc(size_t sz) - { - stb__span *s; - if (sz == 0) return NULL; - if (stb__size_for_class[1] == 0) stb__init_sizeclass(); - if (sz > STB__MAX_SMALL_SIZE) { - s = stb__alloc_span((sz + stb__page_size - 1) >> stb__page_shift); - if (s == NULL) return NULL; - s->list = 0; - s->next = s->prev = NULL; - s->allocations = -32767; - stb__smemset(stb__page_address(s->start), 0xcd, (sz + 3)&~3); - return (void *)stb__page_address(s->start); - } - else { - void *p; - int c = stb__sizeclass(sz); - s = stb__spanlist[256 + c]; - if (!s || !s->first_free) - s = stb__get_nonempty_sizeclass(c); - if (s == NULL) return NULL; - p = s->first_free; - s->first_free = *(void **)p; - ++s->allocations; - stb__smemset(p, 0xcd, sz); - return p; - } - } - - int stb_ssize(void *p) - { - stb__span *s; - if (p == NULL) return 0; - s = stb__span_for_page[stb__page_number((stb_uint)p) - stb__firstpage]; - if (s->list >= 256) { - return stb__size_for_class[s->list - 256]; - } - else { - assert(s->list == 0); - return s->len << stb__page_shift; - } - } - - void stb_sfree(void *p) - { - stb__span *s; - if (p == NULL) return; - s = stb__span_for_page[stb__page_number((stb_uint)p) - stb__firstpage]; - if (s->list >= 256) { - stb__smemset(p, 0xfe, stb__size_for_class[s->list - 256]); - *(void **)p = s->first_free; - s->first_free = p; - if (--s->allocations == 0) { - stb__spanlist_unlink(s); - stb__free_span(s); - } - } - else { - assert(s->list == 0); - stb__smemset(p, 0xfe, stb_ssize(p)); - stb__free_span(s); - } - } - - void *stb_srealloc(void *p, size_t sz) - { - size_t cur_size; - if (p == NULL) return stb_smalloc(sz); - if (sz == 0) { stb_sfree(p); return NULL; } - cur_size = stb_ssize(p); - if (sz > cur_size || sz <= (cur_size >> 1)) { - void *q; - if (sz > cur_size && sz < (cur_size << 1)) sz = cur_size << 1; - q = stb_smalloc(sz); if (q == NULL) return NULL; - memcpy(q, p, sz < cur_size ? sz : cur_size); - stb_sfree(p); - return q; - } - return p; - } - - void *stb_scalloc(size_t n, size_t sz) - { - void *p; - if (n == 0 || sz == 0) return NULL; - if (stb_log2_ceil(n) + stb_log2_ceil(n) >= 32) return NULL; - p = stb_smalloc(n*sz); - if (p) memset(p, 0, n*sz); - return p; - } - - char *stb_sstrdup(char *s) - { - int n = strlen(s); - char *p = (char *)stb_smalloc(n + 1); - if (p) strcpy(p, s); - return p; - } -#endif // STB_DEFINE - - - - ////////////////////////////////////////////////////////////////////////////// - // - // Source code constants - // - // This is a trivial system to let you specify constants in source code, - // then while running you can change the constants. - // - // Note that you can't wrap the #defines, because we need to know their - // names. So we provide a pre-wrapped version without 'STB_' for convenience; - // to request it, #define STB_CONVENIENT_H, yielding: - // KI -- integer - // KU -- unsigned integer - // KF -- float - // KD -- double - // KS -- string constant - // - // Defaults to functioning in debug build, not in release builds. - // To force on, define STB_ALWAYS_H - -#ifdef STB_CONVENIENT_H -#define KI(x) STB_I(x) -#define KU(x) STB_UI(x) -#define KF(x) STB_F(x) -#define KD(x) STB_D(x) -#define KS(x) STB_S(x) -#endif - - STB_EXTERN void stb_source_path(char *str); -#ifdef STB_DEFINE - char *stb__source_path; - void stb_source_path(char *path) - { - stb__source_path = path; - } - - char *stb__get_sourcefile_path(char *file) - { - static char filebuf[512]; - if (stb__source_path) { - sprintf(filebuf, "%s/%s", stb__source_path, file); - if (stb_fexists(filebuf)) return filebuf; - } - - if (stb_fexists(file)) return file; - - sprintf(filebuf, "../%s", file); - if (!stb_fexists(filebuf)) return filebuf; - - return file; - } -#endif - -#define STB_F(x) ((float) STB_H(x)) -#define STB_UI(x) ((unsigned int) STB_I(x)) - -#if !defined(STB_DEBUG) && !defined(STB_ALWAYS_H) -#define STB_D(x) ((double) (x)) -#define STB_I(x) ((int) (x)) -#define STB_S(x) ((char *) (x)) -#else -#define STB_D(x) stb__double_constant(__FILE__, __LINE__-1, (x)) -#define STB_I(x) stb__int_constant(__FILE__, __LINE__-1, (x)) -#define STB_S(x) stb__string_constant(__FILE__, __LINE__-1, (x)) - - STB_EXTERN double stb__double_constant(char *file, int line, double x); - STB_EXTERN int stb__int_constant(char *file, int line, int x); - STB_EXTERN char * stb__string_constant(char *file, int line, char *str); - -#ifdef STB_DEFINE - - enum - { - STB__CTYPE_int, - STB__CTYPE_uint, - STB__CTYPE_float, - STB__CTYPE_double, - STB__CTYPE_string, - }; - - typedef struct - { - int line; - int type; - union { - int ival; - double dval; - char *sval; - }; - } stb__Entry; - - typedef struct - { - stb__Entry *entries; - char *filename; - time_t timestamp; - char **file_data; - int file_len; - unsigned short *line_index; - } stb__FileEntry; - - static void stb__constant_parse(stb__FileEntry *f, int i) - { - char *s; - int n; - if (!stb_arr_valid(f->entries, i)) return; - n = f->entries[i].line; - if (n >= f->file_len) return; - s = f->file_data[n]; - switch (f->entries[i].type) { - case STB__CTYPE_float: - while (*s) { - if (!strncmp(s, "STB_D(", 6)) { s += 6; goto matched_float; } - if (!strncmp(s, "STB_F(", 6)) { s += 6; goto matched_float; } - if (!strncmp(s, "KD(", 3)) { s += 3; goto matched_float; } - if (!strncmp(s, "KF(", 3)) { s += 3; goto matched_float; } - ++s; - } - break; - matched_float: - f->entries[i].dval = strtod(s, NULL); - break; - case STB__CTYPE_int: - while (*s) { - if (!strncmp(s, "STB_I(", 6)) { s += 6; goto matched_int; } - if (!strncmp(s, "STB_UI(", 7)) { s += 7; goto matched_int; } - if (!strncmp(s, "KI(", 3)) { s += 3; goto matched_int; } - if (!strncmp(s, "KU(", 3)) { s += 3; goto matched_int; } - ++s; - } - break; - matched_int: { - int neg = 0; - s = stb_skipwhite(s); - while (*s == '-') { neg = !neg; s = stb_skipwhite(s + 1); } // handle '- - 5', pointlessly - if (s[0] == '0' && tolower(s[1]) == 'x') - f->entries[i].ival = strtol(s, NULL, 16); - else if (s[0] == '0') - f->entries[i].ival = strtol(s, NULL, 8); - else - f->entries[i].ival = strtol(s, NULL, 10); - if (neg) f->entries[i].ival = -f->entries[i].ival; - break; - } - case STB__CTYPE_string: - // @TODO - break; - } - } - - static stb_sdict *stb__constant_file_hash; - - stb__Entry *stb__constant_get_entry(char *filename, int line, int type) - { - int i; - stb__FileEntry *f; - if (stb__constant_file_hash == NULL) - stb__constant_file_hash = stb_sdict_new(STB_TRUE); - f = (stb__FileEntry*)stb_sdict_get(stb__constant_file_hash, filename); - if (f == NULL) { - char *s = stb__get_sourcefile_path(filename); - if (s == NULL || !stb_fexists(s)) return 0; - f = (stb__FileEntry *)malloc(sizeof(*f)); - f->timestamp = stb_ftimestamp(s); - f->file_data = stb_stringfile(s, &f->file_len); - f->filename = strdup(s); // cache the full path - f->entries = NULL; - f->line_index = 0; - stb_arr_setlen(f->line_index, f->file_len); - memset(f->line_index, 0xff, stb_arr_storage(f->line_index)); - } - else { - time_t t = stb_ftimestamp(f->filename); - if (f->timestamp != t) { - f->timestamp = t; - free(f->file_data); - f->file_data = stb_stringfile(f->filename, &f->file_len); - stb_arr_setlen(f->line_index, f->file_len); - for (i = 0; i < stb_arr_len(f->entries); ++i) - stb__constant_parse(f, i); - } - } - - if (line >= f->file_len) return 0; - - if (f->line_index[line] >= stb_arr_len(f->entries)) { - // need a new entry - int n = stb_arr_len(f->entries); - stb__Entry e; - e.line = line; - if (line < f->file_len) - f->line_index[line] = n; - e.type = type; - stb_arr_push(f->entries, e); - stb__constant_parse(f, n); - } - return f->entries + f->line_index[line]; - } - - double stb__double_constant(char *file, int line, double x) - { - stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_float); - if (!e) return x; - return e->dval; - } - - int stb__int_constant(char *file, int line, int x) - { - stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_int); - if (!e) return x; - return e->ival; - } - - char * stb__string_constant(char *file, int line, char *x) - { - stb__Entry *e = stb__constant_get_entry(file, line, STB__CTYPE_string); - if (!e) return x; - return e->sval; - } - -#endif // STB_DEFINE -#endif // !STB_DEBUG && !STB_ALWAYS_H - - -#ifdef STB_STUA - ////////////////////////////////////////////////////////////////////////// - // - // stua: little scripting language - // - // define STB_STUA to compile it - // - // see http://nothings.org/stb/stb_stua.html for documentation - // - // basic parsing model: - // - // lexical analysis - // use stb_lex() to parse tokens; keywords get their own tokens - // - // parsing: - // recursive descent parser. too much of a hassle to make an unambiguous - // LR(1) grammar, and one-pass generation is clumsier (recursive descent - // makes it easier to e.g. compile nested functions). on the other hand, - // dictionary syntax required hackery to get extra lookahead. - // - // codegen: - // output into an evaluation tree, using array indices as 'pointers' - // - // run: - // traverse the tree; support for 'break/continue/return' is tricky - // - // garbage collection: - // stu__mark and sweep; explicit stack with non-stu__compile_global_scope roots - - typedef stb_int32 stua_obj; - - typedef stb_idict stua_dict; - - STB_EXTERN void stua_run_script(char *s); - STB_EXTERN void stua_uninit(void); - - extern stua_obj stua_globals; - - STB_EXTERN double stua_number(stua_obj z); - - STB_EXTERN stua_obj stua_getnil(void); - STB_EXTERN stua_obj stua_getfalse(void); - STB_EXTERN stua_obj stua_gettrue(void); - STB_EXTERN stua_obj stua_string(char *z); - STB_EXTERN stua_obj stua_make_number(double d); - STB_EXTERN stua_obj stua_box(int type, void *data, int size); - - enum - { - STUA_op_negate = 129, - STUA_op_shl, STUA_op_ge, - STUA_op_shr, STUA_op_le, - STUA_op_shru, - STUA_op_last - }; - -#define STUA_NO_VALUE 2 // equivalent to a tagged NULL - STB_EXTERN stua_obj(*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c); - - STB_EXTERN stua_obj stua_error(char *err, ...); - - STB_EXTERN stua_obj stua_pushroot(stua_obj o); - STB_EXTERN void stua_poproot(void); - - -#ifdef STB_DEFINE - // INTERPRETER - - // 31-bit floating point implementation - // force the (1 << 30) bit (2nd highest bit) to be zero by re-biasing the exponent; - // then shift and set the bottom bit - - static stua_obj stu__floatp(float *f) - { - unsigned int n = *(unsigned int *)f; - unsigned int e = n & (0xff << 23); - - assert(sizeof(int) == 4 && sizeof(float) == 4); - - if (!e) // zero? - n = n; // no change - else if (e < (64 << 23)) // underflow of the packed encoding? - n = (n & 0x80000000); // signed 0 - else if (e >(190 << 23)) // overflow of the encoding? (or INF or NAN) - n = (n & 0x80000000) + (127 << 23); // new INF encoding - else - n -= 0x20000000; - - // now we need to shuffle the bits so that the spare bit is at the bottom - assert((n & 0x40000000) == 0); - return (n & 0x80000000) + (n << 1) + 1; - } - - static unsigned char stu__getfloat_addend[256]; - static float stu__getfloat(stua_obj v) - { - unsigned int n; - unsigned int e = ((unsigned int)v) >> 24; - - n = (int)v >> 1; // preserve high bit - n += stu__getfloat_addend[e] << 24; - return *(float *)&n; - } - - stua_obj stua_float(float f) - { - return stu__floatp(&f); - } - - static void stu__float_init(void) - { - int i; - stu__getfloat_addend[0] = 0; // do nothing to biased exponent of 0 - for (i = 1; i < 127; ++i) - stu__getfloat_addend[i] = 32; // undo the -0x20000000 - stu__getfloat_addend[127] = 64; // convert packed INF to INF (0x3f -> 0x7f) - - for (i = 0; i < 128; ++i) // for signed floats, remove the bit we just shifted down - stu__getfloat_addend[128 + i] = stu__getfloat_addend[i] - 64; - } - - // Tagged data type implementation - - // TAGS: -#define stu__int_tag 0 // of 2 bits // 00 int -#define stu__float_tag 1 // of 1 bit // 01 float -#define stu__ptr_tag 2 // of 2 bits // 10 boxed - // 11 float - -#define stu__tag(x) ((x) & 3) -#define stu__number(x) (stu__tag(x) != stu__ptr_tag) -#define stu__isint(x) (stu__tag(x) == stu__int_tag) - -#define stu__int(x) ((x) >> 2) -#define stu__float(x) (stu__getfloat(x)) - -#define stu__makeint(v) ((v)*4+stu__int_tag) - - // boxed data, and tag support for boxed data - - enum - { - STU___float = 1, STU___int = 2, - STU___number = 3, STU___string = 4, - STU___function = 5, STU___dict = 6, - STU___boolean = 7, STU___error = 8, - }; - - // boxed data -#define STU__BOX short type, stua_gc - typedef struct stu__box { STU__BOX; } stu__box; - - stu__box stu__nil = { 0, 1 }; - stu__box stu__true = { STU___boolean, 1, }; - stu__box stu__false = { STU___boolean, 1, }; - -#define stu__makeptr(v) ((stua_obj) (v) + stu__ptr_tag) - -#define stua_nil stu__makeptr(&stu__nil) -#define stua_true stu__makeptr(&stu__true) -#define stua_false stu__makeptr(&stu__false) - - stua_obj stua_getnil(void) { return stua_nil; } - stua_obj stua_getfalse(void) { return stua_false; } - stua_obj stua_gettrue(void) { return stua_true; } - -#define stu__ptr(x) ((stu__box *) ((x) - stu__ptr_tag)) - -#define stu__checkt(t,x) ((t) == STU___float ? ((x) & 1) == stu__float_tag : \ - (t) == STU___int ? stu__isint(x) : \ - (t) == STU___number ? stu__number(x) : \ - stu__tag(x) == stu__ptr_tag && stu__ptr(x)->type == (t)) - - typedef struct - { - STU__BOX; - void *ptr; - } stu__wrapper; - - // implementation of a 'function' or function + closure - - typedef struct stu__func - { - STU__BOX; - stua_obj closure_source; // 0 - regular function; 4 - C function - // if closure, pointer to source function - union { - stua_obj closure_data; // partial-application data - void *store; // pointer to free that holds 'code' - stua_obj(*func)(stua_dict *context); - } f; - // closure ends here - short *code; - int num_param; - stua_obj *param; // list of parameter strings - } stu__func; - - // apply this to 'short *code' to get at data -#define stu__const(f) ((stua_obj *) (f)) - - static void stu__free_func(stu__func *f) - { - if (f->closure_source == 0) free(f->f.store); - if ((stb_uint)f->closure_source <= 4) free(f->param); - free(f); - } - -#define stu__pd(x) ((stua_dict *) stu__ptr(x)) -#define stu__pw(x) ((stu__wrapper *) stu__ptr(x)) -#define stu__pf(x) ((stu__func *) stu__ptr(x)) - - - // garbage-collection - - - static stu__box ** stu__gc_ptrlist; - static stua_obj * stu__gc_root_stack; - - stua_obj stua_pushroot(stua_obj o) { stb_arr_push(stu__gc_root_stack, o); return o; } - void stua_poproot(void) { stb_arr_pop(stu__gc_root_stack); } - - static stb_sdict *stu__strings; - static void stu__mark(stua_obj z) - { - int i; - stu__box *p = stu__ptr(z); - if (p->stua_gc == 1) return; // already marked - assert(p->stua_gc == 0); - p->stua_gc = 1; - switch (p->type) { - case STU___function: { - stu__func *f = (stu__func *)p; - if ((stb_uint)f->closure_source <= 4) { - if (f->closure_source == 0) { - for (i = 1; i <= f->code[0]; ++i) - if (!stu__number(((stua_obj *)f->code)[-i])) - stu__mark(((stua_obj *)f->code)[-i]); - } - for (i = 0; i < f->num_param; ++i) - stu__mark(f->param[i]); - } - else { - stu__mark(f->closure_source); - stu__mark(f->f.closure_data); - } - break; - } - case STU___dict: { - stua_dict *e = (stua_dict *)p; - for (i = 0; i < e->limit; ++i) - if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL) { - if (!stu__number(e->table[i].k)) stu__mark((int)e->table[i].k); - if (!stu__number(e->table[i].v)) stu__mark((int)e->table[i].v); - } - break; - } - } - } - - static int stu__num_allocs, stu__size_allocs; - static stua_obj stu__flow_val = stua_nil; // used for break & return - - static void stua_gc(int force) - { - int i; - if (!force && stu__num_allocs == 0 && stu__size_allocs == 0) return; - stu__num_allocs = stu__size_allocs = 0; - //printf("[gc]\n"); - - // clear marks - for (i = 0; i < stb_arr_len(stu__gc_ptrlist); ++i) - stu__gc_ptrlist[i]->stua_gc = 0; - - // stu__mark everything reachable - stu__nil.stua_gc = stu__true.stua_gc = stu__false.stua_gc = 1; - stu__mark(stua_globals); - if (!stu__number(stu__flow_val)) - stu__mark(stu__flow_val); - for (i = 0; i < stb_arr_len(stu__gc_root_stack); ++i) - if (!stu__number(stu__gc_root_stack[i])) - stu__mark(stu__gc_root_stack[i]); - - // sweep unreachables - for (i = 0; i < stb_arr_len(stu__gc_ptrlist);) { - stu__box *z = stu__gc_ptrlist[i]; - if (!z->stua_gc) { - switch (z->type) { - case STU___dict: stb_idict_destroy((stua_dict *)z); break; - case STU___error: free(((stu__wrapper *)z)->ptr); break; - case STU___string: stb_sdict_remove(stu__strings, (char*)((stu__wrapper *)z)->ptr, NULL); free(z); break; - case STU___function: stu__free_func((stu__func *)z); break; - } - // swap in the last item over this, and repeat - z = stb_arr_pop(stu__gc_ptrlist); - stu__gc_ptrlist[i] = z; - } - else - ++i; - } - } - - static void stu__consider_gc(stua_obj x) - { - if (stu__size_allocs < 100000) return; - if (stu__num_allocs < 10 && stu__size_allocs < 1000000) return; - stb_arr_push(stu__gc_root_stack, x); - stua_gc(0); - stb_arr_pop(stu__gc_root_stack); - } - - static stua_obj stu__makeobj(int type, void *data, int size, int safe_to_gc) - { - stua_obj x = stu__makeptr(data); - ((stu__box *)data)->type = type; - stb_arr_push(stu__gc_ptrlist, (stu__box *)data); - stu__num_allocs += 1; - stu__size_allocs += size; - if (safe_to_gc) stu__consider_gc(x); - return x; - } - - stua_obj stua_box(int type, void *data, int size) - { - stu__wrapper *p = (stu__wrapper *)malloc(sizeof(*p)); - p->ptr = data; - return stu__makeobj(type, p, size, 0); - } - - // a stu string can be directly compared for equality, because - // they go into a hash table - stua_obj stua_string(char *z) - { - stu__wrapper *b = (stu__wrapper *)stb_sdict_get(stu__strings, z); - if (b == NULL) { - int o = stua_box(STU___string, NULL, strlen(z) + sizeof(*b)); - b = stu__pw(o); - stb_sdict_add(stu__strings, z, b); - stb_sdict_getkey(stu__strings, z, (char **)&b->ptr); - } - return stu__makeptr(b); - } - - // stb_obj dictionary is just an stb_idict - static void stu__set(stua_dict *d, stua_obj k, stua_obj v) - { - if (stb_idict_set(d, k, v)) stu__size_allocs += 8; - } - - static stua_obj stu__get(stua_dict *d, stua_obj k, stua_obj res) - { - stb_idict_get_flag(d, k, &res); - return res; - } - - static stua_obj make_string(char *z, int len) - { - stua_obj s; - char temp[256], *q = (char *)stb_temp(temp, len + 1), *p = q; - while (len > 0) { - if (*z == '\\') { - if (z[1] == 'n') *p = '\n'; - else if (z[1] == 'r') *p = '\r'; - else if (z[1] == 't') *p = '\t'; - else *p = z[1]; - p += 1; z += 2; len -= 2; - } - else { - *p++ = *z++; len -= 1; - } - } - *p = 0; - s = stua_string(q); - stb_tempfree(temp, q); - return s; - } - - enum token_names - { - T__none = 128, - ST_shl = STUA_op_shl, ST_ge = STUA_op_ge, - ST_shr = STUA_op_shr, ST_le = STUA_op_le, - ST_shru = STUA_op_shru, STU__negate = STUA_op_negate, - ST__reset_numbering = STUA_op_last, - ST_white, - ST_id, ST_float, ST_decimal, ST_hex, ST_char, ST_string, ST_number, - // make sure the keywords come _AFTER_ ST_id, so stb_lex prefer them - ST_if, ST_while, ST_for, ST_eq, ST_nil, - ST_then, ST_do, ST_in, ST_ne, ST_true, - ST_else, ST_break, ST_let, ST_and, ST_false, - ST_elseif, ST_continue, ST_into, ST_or, ST_repeat, - ST_end, ST_as, ST_return, ST_var, ST_func, - ST_catch, ST__frame, - ST__max_terminals, - - STU__defaultparm, STU__seq, - }; - - static stua_dict * stu__globaldict; - stua_obj stua_globals; - - static enum - { - FLOW_normal, FLOW_continue, FLOW_break, FLOW_return, FLOW_error, - } stu__flow; - - stua_obj stua_error(char *z, ...) - { - stua_obj a; - char temp[4096], *x; - va_list v; va_start(v, z); vsprintf(temp, z, v); va_end(v); - x = strdup(temp); - a = stua_box(STU___error, x, strlen(x)); - stu__flow = FLOW_error; - stu__flow_val = a; - return stua_nil; - } - - double stua_number(stua_obj z) - { - return stu__tag(z) == stu__int_tag ? stu__int(z) : stu__float(z); - } - - stua_obj stua_make_number(double d) - { - double e = floor(d); - if (e == d && e < (1 << 29) && e >= -(1 << 29)) - return stu__makeint((int)e); - else - return stua_float((float)d); - } - - stua_obj(*stua_overload)(int op, stua_obj a, stua_obj b, stua_obj c) = NULL; - - static stua_obj stu__op(int op, stua_obj a, stua_obj b, stua_obj c) - { - stua_obj r = STUA_NO_VALUE; - if (op == '+') { - if (stu__checkt(STU___string, a) && stu__checkt(STU___string, b)) { - ;// @TODO: string concatenation - } - else if (stu__checkt(STU___function, a) && stu__checkt(STU___dict, b)) { - stu__func *f = (stu__func *)malloc(12); - assert(offsetof(stu__func, code) == 12); - f->closure_source = a; - f->f.closure_data = b; - return stu__makeobj(STU___function, f, 16, 1); - } - } - if (stua_overload) r = stua_overload(op, a, b, c); - if (stu__flow != FLOW_error && r == STUA_NO_VALUE) - stua_error("Typecheck for operator %d", op), r = stua_nil; - return r; - } - -#define STU__EVAL2(a,b) \ - a = stu__eval(stu__f[n+1]); if (stu__flow) break; stua_pushroot(a); \ - b = stu__eval(stu__f[n+2]); stua_poproot(); if (stu__flow) break; - -#define STU__FB(op) \ - STU__EVAL2(a,b) \ - if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \ - return ((a) op (b)); \ - if (stu__number(a) && stu__number(b)) \ - return stua_make_number(stua_number(a) op stua_number(b)); \ - return stu__op(stu__f[n], a,b, stua_nil) - -#define STU__F(op) \ - STU__EVAL2(a,b) \ - if (stu__number(a) && stu__number(b)) \ - return stua_make_number(stua_number(a) op stua_number(b)); \ - return stu__op(stu__f[n], a,b, stua_nil) - -#define STU__I(op) \ - STU__EVAL2(a,b) \ - if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) \ - return stu__makeint(stu__int(a) op stu__int(b)); \ - return stu__op(stu__f[n], a,b, stua_nil) - -#define STU__C(op) \ - STU__EVAL2(a,b) \ - if (stu__number(a) && stu__number(b)) \ - return (stua_number(a) op stua_number(b)) ? stua_true : stua_false; \ - return stu__op(stu__f[n], a,b, stua_nil) - -#define STU__CE(op) \ - STU__EVAL2(a,b) \ - return (a op b) ? stua_true : stua_false - - static short *stu__f; - static stua_obj stu__f_obj; - static stua_dict *stu__c; - static stua_obj stu__funceval(stua_obj fo, stua_obj co); - - static int stu__cond(stua_obj x) - { - if (stu__flow) return 0; - if (!stu__checkt(STU___boolean, x)) - x = stu__op('!', x, stua_nil, stua_nil); - if (x == stua_true) return 1; - if (x == stua_false) return 0; - stu__flow = FLOW_error; - return 0; - } - - // had to manually eliminate tailcall recursion for debugging complex stuff -#define TAILCALL(x) n = (x); goto top; - static stua_obj stu__eval(int n) - { - top: - if (stu__flow >= FLOW_return) return stua_nil; // is this needed? - if (n < 0) return stu__const(stu__f)[n]; - assert(n != 0 && n != 1); - switch (stu__f[n]) { - stua_obj a, b, c; - case ST_catch: a = stu__eval(stu__f[n + 1]); - if (stu__flow == FLOW_error) { a = stu__flow_val; stu__flow = FLOW_normal; } - return a; - case ST_var: b = stu__eval(stu__f[n + 2]); if (stu__flow) break; - stu__set(stu__c, stu__const(stu__f)[stu__f[n + 1]], b); - return b; - case STU__seq: stu__eval(stu__f[n + 1]); if (stu__flow) break; - TAILCALL(stu__f[n + 2]); - case ST_if: if (!stu__cond(stu__eval(stu__f[n + 1]))) return stua_nil; - TAILCALL(stu__f[n + 2]); - case ST_else: a = stu__cond(stu__eval(stu__f[n + 1])); - TAILCALL(stu__f[n + 2 + !a]); -#define STU__HANDLE_BREAK \ - if (stu__flow >= FLOW_break) { \ - if (stu__flow == FLOW_break) { \ - a = stu__flow_val; \ - stu__flow = FLOW_normal; \ - stu__flow_val = stua_nil; \ - return a; \ - } \ - return stua_nil; \ - } - case ST_as: stu__eval(stu__f[n + 3]); - STU__HANDLE_BREAK - // fallthrough! - case ST_while: a = stua_nil; stua_pushroot(a); - while (stu__cond(stu__eval(stu__f[n + 1]))) { - stua_poproot(); - a = stu__eval(stu__f[n + 2]); - STU__HANDLE_BREAK - stu__flow = FLOW_normal; // clear 'continue' flag - stua_pushroot(a); - if (stu__f[n + 3]) stu__eval(stu__f[n + 3]); - STU__HANDLE_BREAK - stu__flow = FLOW_normal; // clear 'continue' flag - } - stua_poproot(); - return a; - case ST_break: stu__flow = FLOW_break; stu__flow_val = stu__eval(stu__f[n + 1]); break; - case ST_continue:stu__flow = FLOW_continue; break; - case ST_return: stu__flow = FLOW_return; stu__flow_val = stu__eval(stu__f[n + 1]); break; - case ST__frame: return stu__f_obj; - case '[': STU__EVAL2(a, b); - if (stu__checkt(STU___dict, a)) - return stu__get(stu__pd(a), b, stua_nil); - return stu__op(stu__f[n], a, b, stua_nil); - case '=': a = stu__eval(stu__f[n + 2]); if (stu__flow) break; - n = stu__f[n + 1]; - if (stu__f[n] == ST_id) { - if (!stb_idict_update(stu__c, stu__const(stu__f)[stu__f[n + 1]], a)) - if (!stb_idict_update(stu__globaldict, stu__const(stu__f)[stu__f[n + 1]], a)) - return stua_error("Assignment to undefined variable"); - } - else if (stu__f[n] == '[') { - stua_pushroot(a); - b = stu__eval(stu__f[n + 1]); if (stu__flow) { stua_poproot(); break; } - stua_pushroot(b); - c = stu__eval(stu__f[n + 2]); stua_poproot(); stua_poproot(); - if (stu__flow) break; - if (!stu__checkt(STU___dict, b)) return stua_nil; - stu__set(stu__pd(b), c, a); - } - else { - return stu__op(stu__f[n], stu__eval(n), a, stua_nil); - } - return a; - case STU__defaultparm: - a = stu__eval(stu__f[n + 2]); - stu__flow = FLOW_normal; - if (stb_idict_add(stu__c, stu__const(stu__f)[stu__f[n + 1]], a)) - stu__size_allocs += 8; - return stua_nil; - case ST_id: a = stu__get(stu__c, stu__const(stu__f)[stu__f[n + 1]], STUA_NO_VALUE); // try local variable - return a != STUA_NO_VALUE // else try stu__compile_global_scope variable - ? a : stu__get(stu__globaldict, stu__const(stu__f)[stu__f[n + 1]], stua_nil); - case STU__negate:a = stu__eval(stu__f[n + 1]); if (stu__flow) break; - return stu__isint(a) ? -a : stu__op(stu__f[n], a, stua_nil, stua_nil); - case '~': a = stu__eval(stu__f[n + 1]); if (stu__flow) break; - return stu__isint(a) ? (~a)&~3 : stu__op(stu__f[n], a, stua_nil, stua_nil); - case '!': a = stu__eval(stu__f[n + 1]); if (stu__flow) break; - a = stu__cond(a); if (stu__flow) break; - return a ? stua_true : stua_false; - case ST_eq: STU__CE(== ); case ST_le: STU__C(<= ); case '<': STU__C(<); - case ST_ne: STU__CE(!= ); case ST_ge: STU__C(>= ); case '>': STU__C(>); - case '+': STU__FB(+); case '*': STU__F(*); case '&': STU__I(&); case ST_shl: STU__I(<< ); - case '-': STU__FB(-); case '/': STU__F(/ ); case '|': STU__I(| ); case ST_shr: STU__I(>> ); - case '%': STU__I(%); case '^': STU__I(^); - case ST_shru: STU__EVAL2(a, b); - if (stu__tag(a) == stu__int_tag && stu__tag(b) == stu__int_tag) - return stu__makeint((unsigned)stu__int(a) >> stu__int(b)); - return stu__op(stu__f[n], a, b, stua_nil); - case ST_and: a = stu__eval(stu__f[n + 1]); b = stu__cond(a); if (stu__flow) break; - return a ? stu__eval(stu__f[n + 2]) : a; - case ST_or: a = stu__eval(stu__f[n + 1]); b = stu__cond(a); if (stu__flow) break; - return a ? b : stu__eval(stu__f[n + 2]); - case'(':case':': STU__EVAL2(a, b); - if (!stu__checkt(STU___function, a)) - return stu__op(stu__f[n], a, b, stua_nil); - if (!stu__checkt(STU___dict, b)) - return stua_nil; - if (stu__f[n] == ':') - b = stu__makeobj(STU___dict, stb_idict_copy(stu__pd(b)), stb_idict_memory_usage(stu__pd(b)), 0); - a = stu__funceval(a, b); - return a; - case '{': { - stua_dict *d; - d = stb_idict_new_size(stu__f[n + 1] > 40 ? 64 : 16); - if (d == NULL) - return stua_nil; // breakpoint fodder - c = stu__makeobj(STU___dict, d, 32, 1); - stua_pushroot(c); - a = stu__f[n + 1]; - for (b = 0; b < a; ++b) { - stua_obj x = stua_pushroot(stu__eval(stu__f[n + 2 + b * 2 + 0])); - stua_obj y = stu__eval(stu__f[n + 2 + b * 2 + 1]); - stua_poproot(); - if (stu__flow) { stua_poproot(); return stua_nil; } - stu__set(d, x, y); - } - stua_poproot(); - return c; - } - default: if (stu__f[n] < 0) return stu__const(stu__f)[stu__f[n]]; - assert(0); /* NOTREACHED */ // internal error! - } - return stua_nil; - } - - int stb__stua_nesting; - static stua_obj stu__funceval(stua_obj fo, stua_obj co) - { - stu__func *f = stu__pf(fo); - stua_dict *context = stu__pd(co); - int i, j; - stua_obj p; - short *tf = stu__f; // save previous function - stua_dict *tc = stu__c; - - if (stu__flow == FLOW_error) return stua_nil; - assert(stu__flow == FLOW_normal); - - stua_pushroot(fo); - stua_pushroot(co); - stu__consider_gc(stua_nil); - - while ((stb_uint)f->closure_source > 4) { - // add data from closure to context - stua_dict *e = (stua_dict *)stu__pd(f->f.closure_data); - for (i = 0; i < e->limit; ++i) - if (e->table[i].k != STB_IEMPTY && e->table[i].k != STB_IDEL) - if (stb_idict_add(context, e->table[i].k, e->table[i].v)) - stu__size_allocs += 8; - // use add so if it's already defined, we don't override it; that way - // explicit parameters win over applied ones, and most recent applications - // win over previous ones - f = stu__pf(f->closure_source); - } - - for (j = 0, i = 0; i < f->num_param; ++i) - // if it doesn't already exist, add it from the numbered parameters - if (stb_idict_add(context, f->param[i], stu__get(context, stu__int(j), stua_nil))) - ++j; - - // @TODO: if (stu__get(context, stu__int(f->num_param+1)) != STUA_NO_VALUE) // error: too many parameters - // @TODO: ditto too few parameters - - if (f->closure_source == 4) - p = f->f.func(context); - else { - stu__f = f->code, stu__c = context; - stu__f_obj = co; - ++stb__stua_nesting; - if (stu__f[1]) - p = stu__eval(stu__f[1]); - else - p = stua_nil; - --stb__stua_nesting; - stu__f = tf, stu__c = tc; // restore previous function - if (stu__flow == FLOW_return) { - stu__flow = FLOW_normal; - p = stu__flow_val; - stu__flow_val = stua_nil; - } - } - - stua_poproot(); - stua_poproot(); - - return p; - } - - // Parser - - static int stu__tok; - static stua_obj stu__tokval; - - static char *stu__curbuf, *stu__bufstart; - - static stb_matcher *stu__lex_matcher; - - static unsigned char stu__prec[ST__max_terminals], stu__end[ST__max_terminals]; - - static void stu__nexttoken(void) - { - int len; - - retry: - stu__tok = stb_lex(stu__lex_matcher, stu__curbuf, &len); - if (stu__tok == 0) - return; - switch (stu__tok) { - case ST_white: stu__curbuf += len; goto retry; - case T__none: stu__tok = *stu__curbuf; break; - case ST_string: stu__tokval = make_string(stu__curbuf + 1, len - 2); break; - case ST_id: stu__tokval = make_string(stu__curbuf, len); break; - case ST_hex: stu__tokval = stu__makeint(strtol(stu__curbuf + 2, NULL, 16)); stu__tok = ST_number; break; - case ST_decimal: stu__tokval = stu__makeint(strtol(stu__curbuf, NULL, 10)); stu__tok = ST_number; break; - case ST_float: stu__tokval = stua_float((float)atof(stu__curbuf)); stu__tok = ST_number; break; - case ST_char: stu__tokval = stu__curbuf[2] == '\\' ? stu__curbuf[3] : stu__curbuf[2]; - if (stu__curbuf[3] == 't') stu__tokval = '\t'; - if (stu__curbuf[3] == 'n') stu__tokval = '\n'; - if (stu__curbuf[3] == 'r') stu__tokval = '\r'; - stu__tokval = stu__makeint(stu__tokval); - stu__tok = ST_number; - break; - } - stu__curbuf += len; - } - - static struct { int stu__tok; char *regex; } stu__lexemes[] = - { - ST_white , "([ \t\n\r]|/\\*(.|\n)*\\*/|//[^\r\n]*([\r\n]|$))+", - ST_id , "[_a-zA-Z][_a-zA-Z0-9]*", - ST_hex , "0x[0-9a-fA-F]+", - ST_decimal, "[0-9]+[0-9]*", - ST_float , "[0-9]+\\.?[0-9]*([eE][-+]?[0-9]+)?", - ST_float , "\\.[0-9]+([eE][-+]?[0-9]+)?", - ST_char , "c'(\\\\.|[^\\'])'", - ST_string , "\"(\\\\.|[^\\\"\n\r])*\"", - ST_string , "\'(\\\\.|[^\\\'\n\r])*\'", - -#define stua_key4(a,b,c,d) ST_##a, #a, ST_##b, #b, ST_##c, #c, ST_##d, #d, - stua_key4(if,then,else,elseif) stua_key4(while,do,for,in) - stua_key4(func,var,let,break) stua_key4(nil,true,false,end) - stua_key4(return,continue,as,repeat) stua_key4(_frame,catch,catch,catch) - - ST_shl, "<<", ST_and, "&&", ST_eq, "==", ST_ge, ">=", - ST_shr, ">>", ST_or , "||", ST_ne, "!=", ST_le, "<=", - ST_shru,">>>", ST_into, "=>", - T__none, ".", - }; - - typedef struct - { - stua_obj *data; // constants being compiled - short *code; // code being compiled - stua_dict *locals; - short *non_local_refs; - } stu__comp_func; - - static stu__comp_func stu__pfunc; - static stu__comp_func *func_stack = NULL; - static void stu__push_func_comp(void) - { - stb_arr_push(func_stack, stu__pfunc); - stu__pfunc.data = NULL; - stu__pfunc.code = NULL; - stu__pfunc.locals = stb_idict_new_size(16); - stu__pfunc.non_local_refs = NULL; - stb_arr_push(stu__pfunc.code, 0); // number of data items - stb_arr_push(stu__pfunc.code, 1); // starting execution address - } - - static void stu__pop_func_comp(void) - { - stb_arr_free(stu__pfunc.code); - stb_arr_free(stu__pfunc.data); - stb_idict_destroy(stu__pfunc.locals); - stb_arr_free(stu__pfunc.non_local_refs); - stu__pfunc = stb_arr_pop(func_stack); - } - - // if an id is a reference to an outer lexical scope, this - // function returns the "name" of it, and updates the stack - // structures to make sure the names are propogated in. - static int stu__nonlocal_id(stua_obj var_obj) - { - stua_obj dummy, var = var_obj; - int i, n = stb_arr_len(func_stack), j, k; - if (stb_idict_get_flag(stu__pfunc.locals, var, &dummy)) return 0; - for (i = n - 1; i > 1; --i) { - if (stb_idict_get_flag(func_stack[i].locals, var, &dummy)) - break; - } - if (i <= 1) return 0; // stu__compile_global_scope - j = i; // need to access variable from j'th frame - for (i = 0; i < stb_arr_len(stu__pfunc.non_local_refs); ++i) - if (stu__pfunc.non_local_refs[i] == j) return j - n; - stb_arr_push(stu__pfunc.non_local_refs, j - n); - // now make sure all the parents propogate it down - for (k = n - 1; k > 1; --k) { - if (j - k >= 0) return j - n; // comes direct from this parent - for (i = 0; i < stb_arr_len(func_stack[k].non_local_refs); ++i) - if (func_stack[k].non_local_refs[i] == j - k) - return j - n; - stb_arr_push(func_stack[k].non_local_refs, j - k); - } - assert(k != 1); - - return j - n; - } - - static int stu__off(void) { return stb_arr_len(stu__pfunc.code); } - static void stu__cc(int a) - { - assert(a >= -2000 && a < 5000); - stb_arr_push(stu__pfunc.code, a); - } - static int stu__cc1(int a) { stu__cc(a); return stu__off() - 1; } - static int stu__cc2(int a, int b) { stu__cc(a); stu__cc(b); return stu__off() - 2; } - static int stu__cc3(int a, int b, int c) { - if (a == '=') assert(c != 0); - stu__cc(a); stu__cc(b); stu__cc(c); return stu__off() - 3; - } - static int stu__cc4(int a, int b, int c, int d) { stu__cc(a); stu__cc(b); stu__cc(c); stu__cc(d); return stu__off() - 4; } - - static int stu__cdv(stua_obj p) - { - int i; - assert(p != STUA_NO_VALUE); - for (i = 0; i < stb_arr_len(stu__pfunc.data); ++i) - if (stu__pfunc.data[i] == p) - break; - if (i == stb_arr_len(stu__pfunc.data)) - stb_arr_push(stu__pfunc.data, p); - return ~i; - } - - static int stu__cdt(void) - { - int z = stu__cdv(stu__tokval); - stu__nexttoken(); - return z; - } - - static int stu__seq(int a, int b) - { - return !a ? b : !b ? a : stu__cc3(STU__seq, a, b); - } - - static char stu__comp_err_str[1024]; - static int stu__comp_err_line; - static int stu__err(char *str, ...) - { - va_list v; - char *s = stu__bufstart; - stu__comp_err_line = 1; - while (s < stu__curbuf) { - if (s[0] == '\n' || s[0] == '\r') { - if (s[0] + s[1] == '\n' + '\r') ++s; - ++stu__comp_err_line; - } - ++s; - } - va_start(v, str); - vsprintf(stu__comp_err_str, str, v); - va_end(v); - return 0; - } - - static int stu__accept(int p) - { - if (stu__tok != p) return 0; - stu__nexttoken(); - return 1; - } - - static int stu__demand(int p) - { - if (stu__accept(p)) return 1; - return stu__err("Didn't find expected stu__tok"); - } - - static int stu__demandv(int p, stua_obj *val) - { - if (stu__tok == p || p == 0) { - *val = stu__tokval; - stu__nexttoken(); - return 1; - } - else - return 0; - } - - static int stu__expr(int p); - int stu__nexpr(int p) { stu__nexttoken(); return stu__expr(p); } - static int stu__statements(int once, int as); - - static int stu__parse_if(void) // parse both ST_if and ST_elseif - { - int b, c, a; - a = stu__nexpr(1); if (!a) return 0; - if (!stu__demand(ST_then)) return stu__err("expecting THEN"); - b = stu__statements(0, 0); if (!b) return 0; - if (b == 1) b = -1; - - if (stu__tok == ST_elseif) { - return stu__parse_if(); - } - else if (stu__accept(ST_else)) { - c = stu__statements(0, 0); if (!c) return 0; - if (!stu__demand(ST_end)) return stu__err("expecting END after else clause"); - return stu__cc4(ST_else, a, b, c); - } - else { - if (!stu__demand(ST_end)) return stu__err("expecting END in if statement"); - return stu__cc3(ST_if, a, b); - } - } - - int stu__varinit(int z, int in_globals) - { - int a, b; - stu__nexttoken(); - while (stu__demandv(ST_id, &b)) { - if (!stb_idict_add(stu__pfunc.locals, b, 1)) - if (!in_globals) return stu__err("Redefined variable %s.", stu__pw(b)->ptr); - if (stu__accept('=')) { - a = stu__expr(1); if (!a) return 0; - } - else - a = stu__cdv(stua_nil); - z = stu__seq(z, stu__cc3(ST_var, stu__cdv(b), a)); - if (!stu__accept(',')) break; - } - return z; - } - - static int stu__compile_unary(int z, int outparm, int require_inparm) - { - int op = stu__tok, a, b; - stu__nexttoken(); - if (outparm) { - if (require_inparm || (stu__tok && stu__tok != ST_end && stu__tok != ST_else && stu__tok != ST_elseif && stu__tok != ';')) { - a = stu__expr(1); if (!a) return 0; - } - else - a = stu__cdv(stua_nil); - b = stu__cc2(op, a); - } - else - b = stu__cc1(op); - return stu__seq(z, b); - } - - static int stu__assign(void) - { - int z; - stu__accept(ST_let); - z = stu__expr(1); if (!z) return 0; - if (stu__accept('=')) { - int y, p = (z >= 0 ? stu__pfunc.code[z] : 0); - if (z < 0 || (p != ST_id && p != '[')) return stu__err("Invalid lvalue in assignment"); - y = stu__assign(); if (!y) return 0; - z = stu__cc3('=', z, y); - } - return z; - } - - static int stu__statements(int once, int stop_while) - { - int a, b, c, z = 0; - for (;;) { - switch (stu__tok) { - case ST_if: a = stu__parse_if(); if (!a) return 0; - z = stu__seq(z, a); - break; - case ST_while: if (stop_while) return (z ? z : 1); - a = stu__nexpr(1); if (!a) return 0; - if (stu__accept(ST_as)) c = stu__statements(0, 0); else c = 0; - if (!stu__demand(ST_do)) return stu__err("expecting DO"); - b = stu__statements(0, 0); if (!b) return 0; - if (!stu__demand(ST_end)) return stu__err("expecting END"); - if (b == 1) b = -1; - z = stu__seq(z, stu__cc4(ST_while, a, b, c)); - break; - case ST_repeat: stu__nexttoken(); - c = stu__statements(0, 1); if (!c) return 0; - if (!stu__demand(ST_while)) return stu__err("expecting WHILE"); - a = stu__expr(1); if (!a) return 0; - if (!stu__demand(ST_do)) return stu__err("expecting DO"); - b = stu__statements(0, 0); if (!b) return 0; - if (!stu__demand(ST_end)) return stu__err("expecting END"); - if (b == 1) b = -1; - z = stu__seq(z, stu__cc4(ST_as, a, b, c)); - break; - case ST_catch: a = stu__nexpr(1); if (!a) return 0; - z = stu__seq(z, stu__cc2(ST_catch, a)); - break; - case ST_var: z = stu__varinit(z, 0); break; - case ST_return: z = stu__compile_unary(z, 1, 1); break; - case ST_continue:z = stu__compile_unary(z, 0, 0); break; - case ST_break: z = stu__compile_unary(z, 1, 0); break; - case ST_into: if (z == 0 && !once) return stu__err("=> cannot be first statement in block"); - a = stu__nexpr(99); - b = (a >= 0 ? stu__pfunc.code[a] : 0); - if (a < 0 || (b != ST_id && b != '[')) return stu__err("Invalid lvalue on right side of =>"); - z = stu__cc3('=', a, z); - break; - default: if (stu__end[stu__tok]) return once ? 0 : (z ? z : 1); - a = stu__assign(); if (!a) return 0; - stu__accept(';'); - if (stu__tok && !stu__end[stu__tok]) { - if (a < 0) - return stu__err("Constant has no effect"); - if (stu__pfunc.code[a] != '(' && stu__pfunc.code[a] != '=') - return stu__err("Expression has no effect"); - } - z = stu__seq(z, a); - break; - } - if (!z) return 0; - stu__accept(';'); - if (once && stu__tok != ST_into) return z; - } - } - - static int stu__postexpr(int z, int p); - static int stu__dictdef(int end, int *count) - { - int z, n = 0, i, flags = 0; - short *dict = NULL; - stu__nexttoken(); - while (stu__tok != end) { - if (stu__tok == ST_id) { - stua_obj id = stu__tokval; - stu__nexttoken(); - if (stu__tok == '=') { - flags |= 1; - stb_arr_push(dict, stu__cdv(id)); - z = stu__nexpr(1); if (!z) return 0; - } - else { - z = stu__cc2(ST_id, stu__cdv(id)); - z = stu__postexpr(z, 1); if (!z) return 0; - flags |= 2; - stb_arr_push(dict, stu__cdv(stu__makeint(n++))); - } - } - else { - z = stu__expr(1); if (!z) return 0; - flags |= 2; - stb_arr_push(dict, stu__cdv(stu__makeint(n++))); - } - if (end != ')' && flags == 3) { z = stu__err("can't mix initialized and uninitialized defs"); goto done; } - stb_arr_push(dict, z); - if (!stu__accept(',')) break; - } - if (!stu__demand(end)) - return stu__err(end == ')' ? "Expecting ) at end of function call" - : "Expecting } at end of dictionary definition"); - z = stu__cc2('{', stb_arr_len(dict) / 2); - for (i = 0; i < stb_arr_len(dict); ++i) - stu__cc(dict[i]); - if (count) *count = n; - done: - stb_arr_free(dict); - return z; - } - - static int stu__comp_id(void) - { - int z, d; - d = stu__nonlocal_id(stu__tokval); - if (d == 0) - return z = stu__cc2(ST_id, stu__cdt()); - // access a non-local frame by naming it with the appropriate int - assert(d < 0); - z = stu__cdv(d); // relative frame # is the 'variable' in our local frame - z = stu__cc2(ST_id, z); // now access that dictionary - return stu__cc3('[', z, stu__cdt()); // now access the variable from that dir - } - - static stua_obj stu__funcdef(stua_obj *id, stua_obj *func); - static int stu__expr(int p) - { - int z; - // unary - switch (stu__tok) { - case ST_number: z = stu__cdt(); break; - case ST_string: z = stu__cdt(); break; // @TODO - string concatenation like C - case ST_id: z = stu__comp_id(); break; - case ST__frame: z = stu__cc1(ST__frame); stu__nexttoken(); break; - case ST_func: z = stu__funcdef(NULL, NULL); break; - case ST_if: z = stu__parse_if(); break; - case ST_nil: z = stu__cdv(stua_nil); stu__nexttoken(); break; - case ST_true: z = stu__cdv(stua_true); stu__nexttoken(); break; - case ST_false: z = stu__cdv(stua_false); stu__nexttoken(); break; - case '-': z = stu__nexpr(99); if (z) z = stu__cc2(STU__negate, z); else return z; break; - case '!': z = stu__nexpr(99); if (z) z = stu__cc2('!', z); else return z; break; - case '~': z = stu__nexpr(99); if (z) z = stu__cc2('~', z); else return z; break; - case '{': z = stu__dictdef('}', NULL); break; - default: return stu__err("Unexpected token"); - case '(': stu__nexttoken(); z = stu__statements(0, 0); if (!stu__demand(')')) return stu__err("Expecting )"); - } - return stu__postexpr(z, p); - } - - static int stu__postexpr(int z, int p) - { - int q; - // postfix - while (stu__tok == '(' || stu__tok == '[' || stu__tok == '.') { - if (stu__accept('.')) { - // MUST be followed by a plain identifier! use [] for other stuff - if (stu__tok != ST_id) return stu__err("Must follow . with plain name; try [] instead"); - z = stu__cc3('[', z, stu__cdv(stu__tokval)); - stu__nexttoken(); - } - else if (stu__accept('[')) { - while (stu__tok != ']') { - int r = stu__expr(1); if (!r) return 0; - z = stu__cc3('[', z, r); - if (!stu__accept(',')) break; - } - if (!stu__demand(']')) return stu__err("Expecting ]"); - } - else { - int n, p = stu__dictdef(')', &n); if (!p) return 0; -#if 0 // this is incorrect! - if (z > 0 && stu__pfunc.code[z] == ST_id) { - stua_obj q = stu__get(stu__globaldict, stu__pfunc.data[-stu__pfunc.code[z + 1] - 1], stua_nil); - if (stu__checkt(STU___function, q)) - if ((stu__pf(q))->num_param != n) - return stu__err("Incorrect number of parameters"); - } -#endif - z = stu__cc3('(', z, p); - } - } - // binop - this implementation taken from lcc - for (q = stu__prec[stu__tok]; q >= p; --q) { - while (stu__prec[stu__tok] == q) { - int o = stu__tok, y = stu__nexpr(p + 1); if (!y) return 0; - z = stu__cc3(o, z, y); - } - } - return z; - } - - static stua_obj stu__finish_func(stua_obj *param, int start) - { - int n, size; - stu__func *f = (stu__func *)malloc(sizeof(*f)); - f->closure_source = 0; - f->num_param = stb_arr_len(param); - f->param = (int *)stb_copy(param, f->num_param * sizeof(*f->param)); - size = stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data) + sizeof(*f) + 8; - f->f.store = malloc(stb_arr_storage(stu__pfunc.code) + stb_arr_storage(stu__pfunc.data)); - f->code = (short *)((char *)f->f.store + stb_arr_storage(stu__pfunc.data)); - memcpy(f->code, stu__pfunc.code, stb_arr_storage(stu__pfunc.code)); - f->code[1] = start; - f->code[0] = stb_arr_len(stu__pfunc.data); - for (n = 0; n < f->code[0]; ++n) - ((stua_obj *)f->code)[-1 - n] = stu__pfunc.data[n]; - return stu__makeobj(STU___function, f, size, 0); - } - - static int stu__funcdef(stua_obj *id, stua_obj *result) - { - int n, z = 0, i, q; - stua_obj *param = NULL; - short *nonlocal; - stua_obj v, f = stua_nil; - assert(stu__tok == ST_func); - stu__nexttoken(); - if (id) { - if (!stu__demandv(ST_id, id)) return stu__err("Expecting function name"); - } - else - stu__accept(ST_id); - if (!stu__demand('(')) return stu__err("Expecting ( for function parameter"); - stu__push_func_comp(); - while (stu__tok != ')') { - if (!stu__demandv(ST_id, &v)) { z = stu__err("Expecting parameter name"); goto done; } - stb_idict_add(stu__pfunc.locals, v, 1); - if (stu__tok == '=') { - n = stu__nexpr(1); if (!n) { z = 0; goto done; } - z = stu__seq(z, stu__cc3(STU__defaultparm, stu__cdv(v), n)); - } - else - stb_arr_push(param, v); - if (!stu__accept(',')) break; - } - if (!stu__demand(')')) { z = stu__err("Expecting ) at end of parameter list"); goto done; } - n = stu__statements(0, 0); if (!n) { z = 0; goto done; } - if (!stu__demand(ST_end)) { z = stu__err("Expecting END at end of function"); goto done; } - if (n == 1) n = 0; - n = stu__seq(z, n); - f = stu__finish_func(param, n); - if (result) { *result = f; z = 1; stu__pop_func_comp(); } - else { - nonlocal = stu__pfunc.non_local_refs; - stu__pfunc.non_local_refs = NULL; - stu__pop_func_comp(); - z = stu__cdv(f); - if (nonlocal) { // build a closure with references to the needed frames - short *initcode = NULL; - for (i = 0; i < stb_arr_len(nonlocal); ++i) { - int k = nonlocal[i], p; - stb_arr_push(initcode, stu__cdv(k)); - if (k == -1) p = stu__cc1(ST__frame); - else { p = stu__cdv(stu__makeint(k + 1)); p = stu__cc2(ST_id, p); } - stb_arr_push(initcode, p); - } - q = stu__cc2('{', stb_arr_len(nonlocal)); - for (i = 0; i < stb_arr_len(initcode); ++i) - stu__cc(initcode[i]); - z = stu__cc3('+', z, q); - stb_arr_free(initcode); - } - stb_arr_free(nonlocal); - } - done: - stb_arr_free(param); - if (!z) stu__pop_func_comp(); - return z; - } - - static int stu__compile_global_scope(void) - { - stua_obj o; - int z = 0; - - stu__push_func_comp(); - while (stu__tok != 0) { - if (stu__tok == ST_func) { - stua_obj id, f; - if (!stu__funcdef(&id, &f)) - goto error; - stu__set(stu__globaldict, id, f); - } - else if (stu__tok == ST_var) { - z = stu__varinit(z, 1); if (!z) goto error; - } - else { - int y = stu__statements(1, 0); if (!y) goto error; - z = stu__seq(z, y); - } - stu__accept(';'); - } - o = stu__finish_func(NULL, z); - stu__pop_func_comp(); - - o = stu__funceval(o, stua_globals); // initialize stu__globaldict - if (stu__flow == FLOW_error) - printf("Error: %s\n", ((stu__wrapper *)stu__ptr(stu__flow_val))->ptr); - return 1; - error: - stu__pop_func_comp(); - return 0; - } - - stua_obj stu__myprint(stua_dict *context) - { - stua_obj x = stu__get(context, stua_string("x"), stua_nil); - if ((x & 1) == stu__float_tag) printf("%f", stu__getfloat(x)); - else if (stu__tag(x) == stu__int_tag) printf("%d", stu__int(x)); - else { - stu__wrapper *s = stu__pw(x); - if (s->type == STU___string || s->type == STU___error) - printf("%s", s->ptr); - else if (s->type == STU___dict) printf("{{dictionary}}"); - else if (s->type == STU___function) printf("[[function]]"); - else - printf("[[ERROR:%s]]", s->ptr); - } - return x; - } - - void stua_init(void) - { - if (!stu__globaldict) { - int i; - stua_obj s; - stu__func *f; - - stu__prec[ST_and] = stu__prec[ST_or] = 1; - stu__prec[ST_eq] = stu__prec[ST_ne] = stu__prec[ST_le] = - stu__prec[ST_ge] = stu__prec['>'] = stu__prec['<'] = 2; - stu__prec[':'] = 3; - stu__prec['&'] = stu__prec['|'] = stu__prec['^'] = 4; - stu__prec['+'] = stu__prec['-'] = 5; - stu__prec['*'] = stu__prec['/'] = stu__prec['%'] = - stu__prec[ST_shl] = stu__prec[ST_shr] = stu__prec[ST_shru] = 6; - - stu__end[')'] = stu__end[ST_end] = stu__end[ST_else] = 1; - stu__end[ST_do] = stu__end[ST_elseif] = 1; - - stu__float_init(); - stu__lex_matcher = stb_lex_matcher(); - for (i = 0; i < sizeof(stu__lexemes) / sizeof(stu__lexemes[0]); ++i) - stb_lex_item(stu__lex_matcher, stu__lexemes[i].regex, stu__lexemes[i].stu__tok); - - stu__globaldict = stb_idict_new_size(64); - stua_globals = stu__makeobj(STU___dict, stu__globaldict, 0, 0); - stu__strings = stb_sdict_new(0); - - stu__curbuf = stu__bufstart = "func _print(x) end\n" - "func print()\n var x=0 while _frame[x] != nil as x=x+1 do _print(_frame[x]) end end\n"; - stu__nexttoken(); - if (!stu__compile_global_scope()) - printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str); - - s = stu__get(stu__globaldict, stua_string("_print"), stua_nil); - if (stu__tag(s) == stu__ptr_tag && stu__ptr(s)->type == STU___function) { - f = stu__pf(s); - free(f->f.store); - f->closure_source = 4; - f->f.func = stu__myprint; - f->code = NULL; - } - } - } - - void stua_uninit(void) - { - if (stu__globaldict) { - stb_idict_remove_all(stu__globaldict); - stb_arr_setlen(stu__gc_root_stack, 0); - stua_gc(1); - stb_idict_destroy(stu__globaldict); - stb_sdict_delete(stu__strings); - stb_matcher_free(stu__lex_matcher); - stb_arr_free(stu__gc_ptrlist); - stb_arr_free(func_stack); - stb_arr_free(stu__gc_root_stack); - stu__globaldict = NULL; - } - } - - void stua_run_script(char *s) - { - stua_init(); - - stu__curbuf = stu__bufstart = s; - stu__nexttoken(); - - stu__flow = FLOW_normal; - - if (!stu__compile_global_scope()) - printf("Compile error in line %d: %s\n", stu__comp_err_line, stu__comp_err_str); - stua_gc(1); - } -#endif // STB_DEFINE -#endif // STB_STUA - -#undef STB_EXTERN -#endif // STB_INCLUDE_STB_H - - /* - ------------------------------------------------------------------------------ - This software is available under 2 licenses -- choose whichever you prefer. - ------------------------------------------------------------------------------ - ALTERNATIVE A - MIT License - Copyright (c) 2017 Sean Barrett - 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. - ------------------------------------------------------------------------------ - ALTERNATIVE B - Public Domain (www.unlicense.org) - This is free and unencumbered software released into the public domain. - Anyone is free to copy, modify, publish, use, compile, sell, or distribute this - software, either in source code form or as a compiled binary, for any purpose, - commercial or non-commercial, and by any means. - In jurisdictions that recognize copyright laws, the author or authors of this - software dedicate any and all copyright interest in the software to the public - domain. We make this dedication for the benefit of the public at large and to - the detriment of our heirs and successors. We intend this dedication to be an - overt act of relinquishment in perpetuity of all present and future rights to - this software under copyright law. - 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 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. - ------------------------------------------------------------------------------ - */
\ No newline at end of file diff --git a/libjin/3rdparty/tekcos/tekcos.c b/libjin/3rdparty/tekcos/tekcos.c index a1fc94e..e2b7e5c 100644 --- a/libjin/3rdparty/tekcos/tekcos.c +++ b/libjin/3rdparty/tekcos/tekcos.c @@ -91,12 +91,11 @@ const char* tk_hltostr(uint32 ip) /* TCP socket */ /********************************************/ -tk_TCPsocket* tk_tcp_open(tk_IPaddress ip) +tk_TCPsocket tk_tcp_open(tk_IPaddress ip) { - tk_TCPsocket* sk; - sk = (tk_TCPsocket*)malloc(sizeof(tk_TCPsocket)); - sk->id = socket(AF_INET, SOCK_STREAM, 0); - if (sk->id == INVALID_SOCKET) + tk_TCPsocket sk; + sk.id = socket(AF_INET, SOCK_STREAM, 0); + if (sk.id == INVALID_SOCKET) { state = TK_COULDNETCREATESOCKET; goto error; @@ -115,36 +114,36 @@ tk_TCPsocket* tk_tcp_open(tk_IPaddress ip) if (ip.host != INADDR_NONE && ip.host != INADDR_ANY) { addr.sin_addr.s_addr = htonl(ip.host); - if (connect(sk->id, (const struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) + if (connect(sk.id, (const struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { state = TK_CONNECTFAILED; goto error; } - sk->type = SOCKET_TCLIENT; + sk.type = SOCKET_TCLIENT; } else { addr.sin_addr.s_addr = htonl(INADDR_ANY); - if (bind(sk->id, (const struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) + if (bind(sk.id, (const struct sockaddr*)&addr, sizeof(addr)) == SOCKET_ERROR) { state = TK_BINDSOCKETFAILED; goto error; } - if (listen(sk->id, 8) == SOCKET_ERROR) + if (listen(sk.id, 8) == SOCKET_ERROR) { state = TK_LISTENSOCKETFAILED; goto error; } - sk->type = SOCKET_TSERVER; + sk.type = SOCKET_TSERVER; } - sk->remote.host = ntohl(addr.sin_addr.s_addr); - sk->remote.port = ntohs(addr.sin_port); + sk.remote.host = ntohl(addr.sin_addr.s_addr); + sk.remote.port = ntohs(addr.sin_port); return sk; error: - return 0; + return sk; } int tk_tcp_close(tk_TCPsocket* sk) @@ -169,15 +168,17 @@ error: int tk_tcp_send(tk_TCPsocket* client, const void* buffer, int size, int* sent) { const char *data = (const char*)buffer; + int left; + int len; if (client->type != SOCKET_TCLIENT) { state = TK_WRONGSOCKETTPYE; goto error; } - int left = size; + left = size; if(sent) *sent = 0; - int len = 0; + len = 0; do { len = send(client->id, data, left, 0); if (len > 0) { @@ -195,12 +196,13 @@ error: int tk_tcp_recv(tk_TCPsocket* client, char* buffer, int size, int* len) { *len = 0; + int l; if (client->type != SOCKET_TCLIENT) { state = TK_WRONGSOCKETTPYE; goto error; } - int l = 0; + l = 0; do { l = recv(client->id, buffer, size - *len, 0); @@ -217,10 +219,12 @@ error: return 0; } -tk_TCPsocket* tk_tcp_accept(tk_TCPsocket* server) +tk_TCPsocket tk_tcp_accept(tk_TCPsocket* server) { // client socket - tk_TCPsocket* csk = (tk_TCPsocket*) malloc(sizeof(tk_TCPsocket)); + tk_TCPsocket csk; + memset(&csk, 0, sizeof(csk)); + int addr_len; if (server->type != SOCKET_TSERVER) { state = TK_WRONGSOCKETTPYE; @@ -228,22 +232,22 @@ tk_TCPsocket* tk_tcp_accept(tk_TCPsocket* server) } struct sockaddr_in addr; memset(&addr, 0, sizeof(addr)); - int addr_len = sizeof(addr); - csk->id = accept(server->id, (struct sockaddr *)&addr, &addr_len); - if (csk->id == INVALID_SOCKET) + addr_len = sizeof(addr); + csk.id = accept(server->id, (struct sockaddr *)&addr, &addr_len); + if (csk.id == INVALID_SOCKET) { state = TK_INVALIDSOCKET; goto error; } - csk->remote.host = ntohl(addr.sin_addr.s_addr); - csk->remote.port = ntohs(addr.sin_port); + csk.remote.host = ntohl(addr.sin_addr.s_addr); + csk.remote.port = ntohs(addr.sin_port); - csk->type = SOCKET_TCLIENT; + csk.type = SOCKET_TCLIENT; return csk; error: - return 0; + return csk; } int tk_tcp_nonblocking(tk_TCPsocket* sk) @@ -304,12 +308,12 @@ int tk_tcp_blocking(tk_TCPsocket* sk) * ***************************************************/ -tk_UDPsocket* tk_udp_open(uint16 portnumber) +tk_UDPsocket tk_udp_open(uint16 portnumber) { - tk_UDPsocket* sk; - sk = (tk_UDPsocket*)malloc(sizeof(tk_UDPsocket)); - sk->id = socket(AF_INET, SOCK_DGRAM, 0); - if (sk->id == INVALID_SOCKET) + tk_UDPsocket sk; + memset(&sk, 0, sizeof(sk)); + sk.id = socket(AF_INET, SOCK_DGRAM, 0); + if (sk.id == INVALID_SOCKET) { state = TK_COULDNETCREATESOCKET; goto error; @@ -325,12 +329,12 @@ tk_UDPsocket* tk_udp_open(uint16 portnumber) addr.sin_addr.s_addr = htonl(INADDR_ANY); addr.sin_port = htons(portnumber); addr.sin_family = AF_INET; - bind(sk->id, (const struct sockaddr*)&addr, sizeof(addr)); + bind(sk.id, (const struct sockaddr*)&addr, sizeof(addr)); return sk; } error: - return 0; + return sk; } int tk_udp_sendto(tk_UDPsocket* sk, tk_UDPpack* pack) diff --git a/libjin/3rdparty/tekcos/tekcos.h b/libjin/3rdparty/tekcos/tekcos.h index a212aae..cddc8f3 100644 --- a/libjin/3rdparty/tekcos/tekcos.h +++ b/libjin/3rdparty/tekcos/tekcos.h @@ -1,4 +1,3 @@ -// copyright chai #ifndef _TEKCOS_H #define _TEKCOS_H @@ -56,11 +55,11 @@ typedef struct // INADDR_ANY, creeate a listenning server socket, // otherwise, connect to a remote server with given // ip address. -tk_TCPsocket* tk_tcp_open(tk_IPaddress ip); +tk_TCPsocket tk_tcp_open(tk_IPaddress ip); int tk_tcp_close(tk_TCPsocket* sk); int tk_tcp_send(tk_TCPsocket* client, const void* buffer, int bsize, int* len); int tk_tcp_recv(tk_TCPsocket* client, char* buffer, int bsize, int* len); -tk_TCPsocket* tk_tcp_accept(tk_TCPsocket* server); +tk_TCPsocket tk_tcp_accept(tk_TCPsocket* server); int tk_tcp_nonblocking(tk_TCPsocket* sk); int tk_tcp_blocking(tk_TCPsocket* sk); @@ -83,7 +82,7 @@ typedef struct char* data; // data }tk_UDPpack; -tk_UDPsocket* tk_udp_open(uint16 portnumber); +tk_UDPsocket tk_udp_open(uint16 portnumber); int tk_udp_close(tk_UDPsocket* sk); int tk_udp_sendto(tk_UDPsocket* sk, tk_UDPpack* pack); int tk_udp_recvfrom(tk_UDPsocket* sk, tk_UDPpack* pack); @@ -91,4 +90,4 @@ int tk_freepack(tk_UDPpack* pack); // Get error message if some errors occured. const char* tk_errmsg(); -#endif +#endif
\ No newline at end of file diff --git a/libjin/Audio/OpenAL/ALAudio.cpp b/libjin/Audio/OpenAL/ALAudio.cpp deleted file mode 100644 index e69de29..0000000 --- a/libjin/Audio/OpenAL/ALAudio.cpp +++ /dev/null diff --git a/libjin/Audio/OpenAL/ALAudio.h b/libjin/Audio/OpenAL/ALAudio.h deleted file mode 100644 index e69de29..0000000 --- a/libjin/Audio/OpenAL/ALAudio.h +++ /dev/null diff --git a/libjin/Audio/OpenAL/ALSource.cpp b/libjin/Audio/OpenAL/ALSource.cpp deleted file mode 100644 index e69de29..0000000 --- a/libjin/Audio/OpenAL/ALSource.cpp +++ /dev/null diff --git a/libjin/Audio/OpenAL/ALSource.h b/libjin/Audio/OpenAL/ALSource.h deleted file mode 100644 index e69de29..0000000 --- a/libjin/Audio/OpenAL/ALSource.h +++ /dev/null diff --git a/libjin/Audio/SDL/SDLAudio.cpp b/libjin/Audio/SDL/SDLAudio.cpp index f7ca70d..040ca96 100644 --- a/libjin/Audio/SDL/SDLAudio.cpp +++ b/libjin/Audio/SDL/SDLAudio.cpp @@ -27,7 +27,7 @@ namespace audio audio->unlock(); } - onlyonce bool SDLAudio::initSystem(const SettingBase* s) + /*call only once*/ bool SDLAudio::initSystem(const SettingBase* s) { #if JIN_DEBUG Loghelper::log(Loglevel::LV_INFO, "Init Audio System"); @@ -58,7 +58,7 @@ namespace audio return true; } - onlyonce void SDLAudio::quitSystem() + /*call only once*/ void SDLAudio::quitSystem() { SDL_CloseAudio(); } diff --git a/libjin/Audio/SDL/SDLSource.cpp b/libjin/Audio/SDL/SDLSource.cpp index c868df5..5c6abb8 100644 --- a/libjin/Audio/SDL/SDLSource.cpp +++ b/libjin/Audio/SDL/SDLSource.cpp @@ -52,7 +52,7 @@ namespace audio STEREO = 2, // }; - typedef MASK enum STATUS + typedef /*mask*/ enum STATUS { PLAYING = 1, PAUSED = 2, @@ -63,10 +63,10 @@ namespace audio #define Action Command::Action #define Manager SDLSourceManager - //shared std::queue<Command*> Manager::commands; - //shared std::stack<Command*> Manager::commandsPool; - //shared std::vector<SDLSource*> Manager::sources; - shared Manager* Manager::manager = nullptr; + ///*class member*/ std::queue<Command*> Manager::commands; + ///*class member*/ std::stack<Command*> Manager::commandsPool; + ///*class member*/ std::vector<SDLSource*> Manager::sources; + /*class member*/ Manager* Manager::manager = nullptr; SDLSource* SDLSource::createSource(const char* file) { diff --git a/libjin/Audio/SDL/SDLSource.h b/libjin/Audio/SDL/SDLSource.h index 9a3dd9b..dd792c7 100644 --- a/libjin/Audio/SDL/SDLSource.h +++ b/libjin/Audio/SDL/SDLSource.h @@ -45,7 +45,7 @@ namespace audio inline void handle(SDLSourceManager* manager, SDLSourceCommand* cmd); inline void process(void* buffer, size_t size); - private: + protected: SDLSource(); diff --git a/libjin/Audio/Source.cpp b/libjin/Audio/Source.cpp index ceb882d..61f4055 100644 --- a/libjin/Audio/Source.cpp +++ b/libjin/Audio/Source.cpp @@ -9,7 +9,7 @@ namespace jin namespace audio { - static int check_header(const void *data, int size, char *str, int offset) { + static int check_header(const void *data, int size, const char *str, int offset) { int len = strlen(str); return (size >= offset + len) && !memcmp((char*)data + offset, str, len); } diff --git a/libjin/Common/Data.h b/libjin/Common/Data.h index 7fcc389..4b0f1ba 100644 --- a/libjin/Common/Data.h +++ b/libjin/Common/Data.h @@ -1,6 +1,8 @@ #ifndef __JIN_COMMON_DATA_H #define __JIN_COMMON_DATA_H + + namespace jin { diff --git a/libjin/Common/Subsystem.hpp b/libjin/Common/Subsystem.hpp index c3af3dc..59013c6 100644 --- a/libjin/Common/Subsystem.hpp +++ b/libjin/Common/Subsystem.hpp @@ -22,8 +22,9 @@ namespace jin void quit() { - CALLONCE(quitSystem()); - destroy(); + /*call only once*/ + static char __dummy__ = (quitSystem(), 1); + Singleton<System>::destroy(); } protected: @@ -33,8 +34,8 @@ namespace jin SINGLETON(System); - virtual onlyonce bool initSystem(const Setting* setting) = 0; - virtual onlyonce void quitSystem() = 0; + /*onlyonce*/ virtual bool initSystem(const Setting* setting) = 0; + /*onlyonce*/ virtual void quitSystem() = 0; }; diff --git a/libjin/Common/utf8.cpp b/libjin/Common/utf8.cpp index f21a0d9..bef6c85 100644 --- a/libjin/Common/utf8.cpp +++ b/libjin/Common/utf8.cpp @@ -37,6 +37,6 @@ namespace jin } } -} // jins +} // jin #endif // JIN_OS == JIN_WINDOWS
\ No newline at end of file diff --git a/libjin/Core/Game.cpp b/libjin/Core/Game.cpp index b480b12..3f905f2 100644 --- a/libjin/Core/Game.cpp +++ b/libjin/Core/Game.cpp @@ -19,7 +19,8 @@ namespace core void Game::run() { - SAFECALL(_onLoad); + if (_onLoad != nullptr) + _onLoad(); Window* wnd = Window::get(); const int FPS = wnd ? wnd->getFPS() : 60; const int MS_PER_UPDATE = 1000.0f / FPS; @@ -31,11 +32,12 @@ namespace core { while (jin::input::pollEvent(&e)) { - SAFECALL(_onEvent, &e); + if (_onEvent != nullptr) + _onEvent(&e); if (!_running) goto quitloop; } - SAFECALL(_onUpdate, dt); - SAFECALL(_onDraw); + if (_onUpdate != nullptr) _onUpdate(dt); + if (_onDraw != nullptr) _onDraw(); wnd->swapBuffers(); const int current = getMilliSecond(); dt = current - previous; diff --git a/libjin/Graphics/Canvas.cpp b/libjin/Graphics/Canvas.cpp index f5bd09f..99f022d 100644 --- a/libjin/Graphics/Canvas.cpp +++ b/libjin/Graphics/Canvas.cpp @@ -10,7 +10,7 @@ namespace jin namespace graphics { - shared Canvas* Canvas::createCanvas(int w, int h) + /*class member*/ Canvas* Canvas::createCanvas(int w, int h) { return new Canvas(w, h); } @@ -25,7 +25,7 @@ namespace graphics { } - shared GLint Canvas::cur = -1; + /*class member*/ GLint Canvas::cur = -1; bool Canvas::init() { @@ -102,7 +102,7 @@ namespace graphics /** * bind to default screen render buffer. */ - shared void Canvas::unbind() + /*class member*/ void Canvas::unbind() { if (hasbind(0)) return; diff --git a/libjin/Graphics/Canvas.h b/libjin/Graphics/Canvas.h index bccb3f6..0d5635e 100644 --- a/libjin/Graphics/Canvas.h +++ b/libjin/Graphics/Canvas.h @@ -22,7 +22,7 @@ namespace graphics static bool hasbind(GLint fbo); - private: + protected: Canvas(int w, int h); diff --git a/libjin/Graphics/Drawable.h b/libjin/Graphics/Drawable.h index 0b96379..e04ac6b 100644 --- a/libjin/Graphics/Drawable.h +++ b/libjin/Graphics/Drawable.h @@ -19,12 +19,12 @@ namespace graphics void draw(int x, int y, float sx, float sy, float r); - inline int Drawable::getWidth() const + inline int getWidth() const { return width; } - inline int Drawable::getHeight() const + inline int getHeight() const { return height; } diff --git a/libjin/Graphics/Graphics.h b/libjin/Graphics/Graphics.h index 0823978..210dadf 100644 --- a/libjin/Graphics/Graphics.h +++ b/libjin/Graphics/Graphics.h @@ -6,7 +6,7 @@ #include "canvas.h" #include "color.h" #include "font.h" -#include "Geometry.h" +#include "Shapes.h" #include "texture.h" #include "jsl.h" #include "window.h" diff --git a/libjin/Graphics/JSL.cpp b/libjin/Graphics/JSL.cpp index b877e60..2ab7ceb 100644 --- a/libjin/Graphics/JSL.cpp +++ b/libjin/Graphics/JSL.cpp @@ -22,7 +22,7 @@ namespace graphics " gl_FragColor = effect(gl_Color, _tex0_, gl_TexCoord[0].xy, gl_FragCoord.xy);\n" "}\0"; - shared JSLProgram* JSLProgram::currentJSLProgram = nullptr; + /*static*/ JSLProgram* JSLProgram::currentJSLProgram = nullptr; JSLProgram* JSLProgram::createJSLProgram(const char* program) { diff --git a/libjin/Graphics/JSL.h b/libjin/Graphics/JSL.h index 3872802..8d4712b 100644 --- a/libjin/Graphics/JSL.h +++ b/libjin/Graphics/JSL.h @@ -22,15 +22,15 @@ namespace graphics static JSLProgram* createJSLProgram(const char* program); - ~JSLProgram(); + virtual ~JSLProgram(); - inline void JSLProgram::use() + inline void use() { glUseProgram(pid); currentJSLProgram = this; } - static inline void JSLProgram::unuse() + static inline void unuse() { glUseProgram(0); currentJSLProgram = nullptr; @@ -49,7 +49,7 @@ namespace graphics return currentJSLProgram; } - private: + protected: JSLProgram(const char* program); diff --git a/libjin/Graphics/Geometry.cpp b/libjin/Graphics/Shapes.cpp index 69e3596..4b136a1 100644 --- a/libjin/Graphics/Geometry.cpp +++ b/libjin/Graphics/Shapes.cpp @@ -1,7 +1,7 @@ #include "../modules.h" #if JIN_MODULES_RENDER -#include "Geometry.h" +#include "Shapes.h" #include "../math/matrix.h" #include "../math/constant.h" #include <string> diff --git a/libjin/Graphics/Geometry.h b/libjin/Graphics/Shapes.h index afd4f7a..afd4f7a 100644 --- a/libjin/Graphics/Geometry.h +++ b/libjin/Graphics/Shapes.h diff --git a/libjin/Graphics/Window.h b/libjin/Graphics/Window.h index e09e9f9..e4939f6 100644 --- a/libjin/Graphics/Window.h +++ b/libjin/Graphics/Window.h @@ -44,8 +44,8 @@ namespace graphics int width, height; int fps; - onlyonce bool initSystem(const SettingBase* setting) override; - onlyonce void quitSystem() override; + /*call only once*/ bool initSystem(const SettingBase* setting) override; + /*call only once*/ void quitSystem() override; }; } // render diff --git a/libjin/Net/Net.cpp b/libjin/Net/Net.cpp index 0545b6c..db39be7 100644 --- a/libjin/Net/Net.cpp +++ b/libjin/Net/Net.cpp @@ -17,6 +17,7 @@ namespace net void Net::quitSystem() { + } } diff --git a/libjin/Net/Socket.cpp b/libjin/Net/Socket.cpp index b7c621e..cfc593a 100644 --- a/libjin/Net/Socket.cpp +++ b/libjin/Net/Socket.cpp @@ -4,22 +4,25 @@ namespace jin { namespace net { + Socket::Socket(const Socket& socket) + : handle(socket.handle) + , type(socket.type) + { + } - Socket::Socket(SocketInformation info) - : tcpHandle(nullptr) - , udpHandle(nullptr) + Socket::Socket(const SocketInformation& info) + : type(info.type) { - type = info.type; if (type == SocketType::TCP) { tk_IPaddress ip; ip.host = info.address; ip.port = info.port; - tcpHandle = tk_tcp_open(ip); + handle.tcpHandle = tk_tcp_open(ip); } else if (type == SocketType::UDP) { - udpHandle = tk_udp_open(info.port); + handle.udpHandle = tk_udp_open(info.port); } } @@ -32,12 +35,12 @@ namespace net #if JIN_NET_TEKCOS ip.host = tk_strtohl(address); ip.port = port; - tcpHandle = tk_tcp_open(ip); + handle.tcpHandle = tk_tcp_open(ip); #endif } else if (type == SocketType::UDP) { - udpHandle = tk_udp_open(port); + handle.udpHandle = tk_udp_open(port); } } @@ -49,11 +52,11 @@ namespace net tk_IPaddress ip; ip.host = address; ip.port = port; - tcpHandle = tk_tcp_open(ip); + handle.tcpHandle = tk_tcp_open(ip); } else if (type == SocketType::UDP) { - udpHandle = tk_udp_open(port); + handle.udpHandle = tk_udp_open(port); } } @@ -65,26 +68,24 @@ namespace net tk_IPaddress ip; ip.host = 0; ip.port = port; - tcpHandle = tk_tcp_open(ip); + handle.tcpHandle = tk_tcp_open(ip); } else if (type == SocketType::UDP) { - udpHandle = tk_udp_open(port); + handle.udpHandle = tk_udp_open(port); } } #if JIN_NET_TEKCOS - Socket::Socket(tk_TCPsocket* handle) - : tcpHandle(handle) - , udpHandle(nullptr) + Socket::Socket(const tk_TCPsocket& tcphandle) { + handle.tcpHandle = tcphandle; } - Socket::Socket(tk_UDPsocket* handle) - : tcpHandle(nullptr) - , udpHandle(handle) + Socket::Socket(const tk_UDPsocket& udphandle) { + handle.udpHandle = udphandle; } #endif // JIN_NET_TEKCOS @@ -99,9 +100,9 @@ namespace net return; #if JIN_NET_TEKCOS if (blocking) - tk_tcp_blocking(tcpHandle); + tk_tcp_blocking(&handle.tcpHandle); else - tk_tcp_nonblocking(tcpHandle); + tk_tcp_nonblocking(&handle.tcpHandle); #endif } @@ -111,7 +112,7 @@ namespace net return nullptr; Socket* client; #if JIN_NET_TEKCOS - tk_TCPsocket* socket = tk_tcp_accept(tcpHandle); + tk_TCPsocket socket = tk_tcp_accept(&handle.tcpHandle); client = new Socket(socket); #endif return client; @@ -123,7 +124,7 @@ namespace net return 0; #if JIN_NET_TEKCOS int len; - tk_tcp_recv(tcpHandle, buffer, size, &len); + tk_tcp_recv(&handle.tcpHandle, buffer, size, &len); return len; #endif } @@ -134,7 +135,7 @@ namespace net return 0; #if JIN_NET_TEKCOS int len; - tk_tcp_send(tcpHandle, buffer, size, &len); + tk_tcp_send(&handle.tcpHandle, buffer, size, &len); return len; #endif } @@ -149,7 +150,7 @@ namespace net pack.len = size; pack.ip.host = address; pack.ip.port = port; - tk_udp_sendto(udpHandle, &pack); + tk_udp_sendto(&handle.udpHandle, &pack); #endif } @@ -164,7 +165,7 @@ namespace net pack.len = size; pack.ip.host = address; pack.ip.port = port; - tk_udp_recvfrom(udpHandle, &pack); + tk_udp_recvfrom(&handle.udpHandle, &pack); return pack.len; #endif } @@ -174,13 +175,13 @@ namespace net if (type == SocketType::TCP) { #if JIN_NET_TEKCOS - tk_tcp_close(tcpHandle); + tk_tcp_close(&handle.tcpHandle); #endif } else if (type == SocketType::UDP) { #if JIN_NET_TEKCOS - tk_udp_close(udpHandle); + tk_udp_close(&handle.udpHandle); #endif } } diff --git a/libjin/Net/Socket.h b/libjin/Net/Socket.h index 0eb27e0..6d9e09b 100644 --- a/libjin/Net/Socket.h +++ b/libjin/Net/Socket.h @@ -26,14 +26,15 @@ namespace net class Socket { public: - Socket(SocketInformation socketInformation); + Socket() {}; + Socket(const Socket& socket); + Socket(const SocketInformation& socketInformation); Socket(SocketType type, unsigned short port); Socket(SocketType type, unsigned int address, unsigned short port); Socket(SocketType type, const char* address, unsigned short port); ~Socket(); void configureBlocking(bool bocking); - Socket* accept(); int receive(char* buffer, int size); int send(char* buffer, int size); @@ -41,13 +42,16 @@ namespace net int receiveFrom(char* buffer, int size, unsigned int address, unsigned int port); void close(); - private: + protected: #if JIN_NET_TEKCOS - Socket(tk_TCPsocket* tcpHandle); - Socket(tk_UDPsocket* udpHandle); - tk_TCPsocket* tcpHandle; - tk_UDPsocket* udpHandle; - #endif + Socket(const tk_TCPsocket& tcpHandle); + Socket(const tk_UDPsocket& udpHandle); + union + { + tk_TCPsocket tcpHandle; + tk_UDPsocket udpHandle; + } handle; + #endif SocketType type; }; diff --git a/libjin/Physics/Physics.h b/libjin/Physics/Physics.h deleted file mode 100644 index 9927301..0000000 --- a/libjin/Physics/Physics.h +++ /dev/null @@ -1,12 +0,0 @@ -#ifndef __JIN_PHYSICS_H -#define __JIN_PHYSICS_H - -namespace jin -{ -namespace physics -{ - -} -} - -#endif
\ No newline at end of file diff --git a/libjin/Physics/Rigid.h b/libjin/Physics/Rigid.h deleted file mode 100644 index e69de29..0000000 --- a/libjin/Physics/Rigid.h +++ /dev/null diff --git a/libjin/Thread/Thread.cpp b/libjin/Thread/Thread.cpp index 064d3db..13e691a 100644 --- a/libjin/Thread/Thread.cpp +++ b/libjin/Thread/Thread.cpp @@ -171,14 +171,6 @@ namespace thread ////////////////////////////////////////////////////////////////////// - int Thread::ThreadFunciton(void* p) - { - Thread* thread = (Thread*)p; - if (thread->threadRunner != nullptr) - thread->threadRunner(thread); - return 0; - } - Thread::Thread(const std::string tname, ThreadRunner runner) : name(tname) , running(false) @@ -207,7 +199,7 @@ namespace thread return running; }; - bool Thread::start() + bool Thread::start(void* p) { Lock l(mutex); if (running) @@ -219,8 +211,8 @@ namespace thread #endif } #if JIN_THREAD_SDL - handle = SDL_CreateThread(ThreadFunciton, name.c_str(), this); - #elif JIN_THREAD_CPP + handle = SDL_CreateThread(threadRunner, name.c_str(), p); + #elif JIN_THREAD_CPP handle = new std::thread(); #endif return (running = (handle != nullptr)); @@ -253,7 +245,7 @@ namespace thread mutex->unlock(); } - void Thread::send(int slot, Variant value) + void Thread::send(int slot, const Variant& value) { lock(); common->set(slot, value); diff --git a/libjin/Thread/Thread.h b/libjin/Thread/Thread.h index 0777656..046c8f6 100644 --- a/libjin/Thread/Thread.h +++ b/libjin/Thread/Thread.h @@ -46,7 +46,7 @@ namespace thread { enum Type { - INVALID = 0, + NONE = 0, INTERGER, BOOLEAN, CHARACTER, @@ -64,7 +64,7 @@ namespace thread void* pointer; float real; }; - Variant() :type(INVALID) {}; + Variant() :type(NONE) {}; Variant(const Variant& v){ memcpy(this, &v, sizeof(v)); } Variant(int i) : integer(i), type(INTERGER) {}; Variant(float f) : real(f), type(REAL) {}; @@ -97,12 +97,12 @@ namespace thread }; public: - typedef void(ThreadRunner)(Thread* thread); + typedef int(*ThreadRunner)(void* obj); Thread(const std::string name, ThreadRunner threadfuncs); ~Thread(); - bool start(); + bool start(void* p); void wait(); - void send(int slot, Variant value); + void send(int slot, const Variant& value); bool receive(int slot); Variant fetch(int slot); Variant demand(int slot); @@ -112,7 +112,7 @@ namespace thread void lock(); void unlock(); - private: + protected: #if JIN_THREAD_SDL SDL_Thread* handle; // SDL thread #elif JIN_THREAD_CPP @@ -120,7 +120,7 @@ namespace thread #endif Mutex* mutex; // mutex variable Conditional* condition; // condition variable - ThreadRunner* threadRunner; // thread function + ThreadRunner threadRunner; // thread function ThreadData* common; // threads common data const std::string name; // thread name, for debugging purposes /** @@ -154,8 +154,6 @@ namespace thread */ bool running; // running - static int ThreadFunciton(void* p); - }; } // thread diff --git a/libjin/Tilemap/Tilemap.cpp b/libjin/Tilemap/Tilemap.cpp deleted file mode 100644 index e69de29..0000000 --- a/libjin/Tilemap/Tilemap.cpp +++ /dev/null diff --git a/libjin/Tilemap/Tilemap.h b/libjin/Tilemap/Tilemap.h deleted file mode 100644 index a2bce62..0000000 --- a/libjin/Tilemap/Tilemap.h +++ /dev/null @@ -1,17 +0,0 @@ -#ifndef __JIN_TILEMAP_H -#define __JIN_TILEMAP_H -#include "../modules.h" -#if JIN_MODULES_TILEMAP - -namespace jin -{ -namespace tilemap -{ - - - -}// tilemap -}// jin - -#endif // JIN_MODULES_TILEMAP -#endif // __JIN_TILEMAP_H
\ No newline at end of file diff --git a/libjin/Time/Timer.cpp b/libjin/Time/Timer.cpp index 9d18248..cfdb4bd 100644 --- a/libjin/Time/Timer.cpp +++ b/libjin/Time/Timer.cpp @@ -28,11 +28,11 @@ namespace time if (!(*it)->process(ms)) { Timer* t = *it; + timers.erase(it); delete t; - it = timers.erase(it); + return; } - else - ++it; + ++it; } } diff --git a/libjin/UI/UI.h b/libjin/UI/UI.h deleted file mode 100644 index 6f70f09..0000000 --- a/libjin/UI/UI.h +++ /dev/null @@ -1 +0,0 @@ -#pragma once diff --git a/libjin/Utils/CSV/CSV.cpp b/libjin/Utils/CSV/CSV.cpp deleted file mode 100644 index e69de29..0000000 --- a/libjin/Utils/CSV/CSV.cpp +++ /dev/null diff --git a/libjin/Utils/CSV/CSV.h b/libjin/Utils/CSV/CSV.h deleted file mode 100644 index 6f70f09..0000000 --- a/libjin/Utils/CSV/CSV.h +++ /dev/null @@ -1 +0,0 @@ -#pragma once diff --git a/libjin/Utils/Component/Component.h b/libjin/Utils/Component/Component.h deleted file mode 100644 index f63fb59..0000000 --- a/libjin/Utils/Component/Component.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifndef __JIN_TOOLS_COMPONENT_H -#define __JIN_TOOLS_COMPONENT_H -#include "../../modules.h" -#if JIN_MODULES_TOOLS && JIN_TOOLS_COMPONENT - -namespace jin -{ -namespace utils -{ - - class GameObject; - - class Component - { - public: - Component(GameObject* obj) - : gameObject(obj) - {} - - virtual void update(float dt) = 0; - - private: - GameObject* gameObject; - }; - -} // tools -} // jin - -#endif // JIN_MODULES_TOOLS && JIN_TOOLS_COMPONENT -#endif // __JIN_TOOLS_COMPONENT_H
\ No newline at end of file diff --git a/libjin/Utils/Component/GameObject.h b/libjin/Utils/Component/GameObject.h deleted file mode 100644 index e4f3aa5..0000000 --- a/libjin/Utils/Component/GameObject.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef __JIN_TOOLS_GAMEOBJECT_H -#define __JIN_TOOLS_GAMEOBJECT_H -#include "../../modules.h" -#if JIN_MODULES_TOOLS && JIN_TOOLS_COMPONENT - -#include <vector> -#include "Component.h" - -namespace jin -{ -namespace utils -{ - - class GameObject - { - public: - - GameObject() - : components() - { - } - - virtual void update(float dt) - { - for each (Component* component in components) - component->update(dt); - } - - virtual void draw() = 0; - - protected: - - std::vector<Component*> components; - }; - -} // tools -} // jin - -#endif // JIN_MODULES_TOOLS && JIN_TOOLS_COMPONENT -#endif // __JIN_TOOLS_GAMEOBJECT_H
\ No newline at end of file diff --git a/libjin/Utils/EventMsgCenter/EventMsgCenter.h b/libjin/Utils/EventMsgCenter/EventMsgCenter.h deleted file mode 100644 index 6717b83..0000000 --- a/libjin/Utils/EventMsgCenter/EventMsgCenter.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef __JIN_TOOLS_EVENTMSGCENTER_H -#define __JIN_TOOLS_EVENTMSGCENTER_H -#include "../../modules.h" -#if JIN_MODULES_TOOLS && JIN_TOOLS_EVENTMSGCENTER - -namespace jin -{ -namespace utils -{ - - class EventMSGCenter - { - - }; - -} // tools -} // jin - -#endif // JIN_MODULES_TOOLS && JIN_TOOLS_EVENTMSGCENTER -#endif // __JIN_TOOLS_EVENTMSGCENTER_H
\ No newline at end of file diff --git a/libjin/Utils/EventMsgCenter/Events.h b/libjin/Utils/EventMsgCenter/Events.h deleted file mode 100644 index 9ebc30d..0000000 --- a/libjin/Utils/EventMsgCenter/Events.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef __JIN_TOOLS_EVENTS_H -#define __JIN_TOOLS_EVENTS_H -#include "../../modules.h" -#if JIN_MODULES_TOOLS && JIN_TOOLS_EVENTMSGCENTER - -namespace jin -{ -namespace utils -{ - - enum Event - { - - }; - -} // tools -} // jin - -#endif // JIN_MODULES_TOOLS && JIN_TOOLS_EVENTMSGCENTER -#endif // __JIN_TOOLS_EVENTS_H
\ No newline at end of file diff --git a/libjin/Utils/Json/Json.cpp b/libjin/Utils/Json/Json.cpp deleted file mode 100644 index e69de29..0000000 --- a/libjin/Utils/Json/Json.cpp +++ /dev/null diff --git a/libjin/Utils/Json/Json.h b/libjin/Utils/Json/Json.h deleted file mode 100644 index 6f70f09..0000000 --- a/libjin/Utils/Json/Json.h +++ /dev/null @@ -1 +0,0 @@ -#pragma once diff --git a/libjin/Utils/Log.h b/libjin/Utils/Log.h index 50ec3c8..e4ed879 100644 --- a/libjin/Utils/Log.h +++ b/libjin/Utils/Log.h @@ -61,7 +61,7 @@ void Loghelper::log(Level _level, const char* _fmt, ...) if (!hasbit(levels, _level)) return; #define FORMAT_MSG_BUFFER_SIZE (204800) - char* levelStr = nullptr; + const char* levelStr = nullptr; switch (_level) { case LV_ERROR: diff --git a/libjin/Utils/Proxy/lock.h b/libjin/Utils/Proxy/lock.h deleted file mode 100644 index 29194a1..0000000 --- a/libjin/Utils/Proxy/lock.h +++ /dev/null @@ -1,4 +0,0 @@ -class Lock -{ - -};
\ No newline at end of file diff --git a/libjin/Utils/XML/XML.cpp b/libjin/Utils/XML/XML.cpp deleted file mode 100644 index e69de29..0000000 --- a/libjin/Utils/XML/XML.cpp +++ /dev/null diff --git a/libjin/Utils/XML/XML.h b/libjin/Utils/XML/XML.h deleted file mode 100644 index 6f70f09..0000000 --- a/libjin/Utils/XML/XML.h +++ /dev/null @@ -1 +0,0 @@ -#pragma once diff --git a/libjin/Utils/macros.h b/libjin/Utils/macros.h index a57cb7c..290bcf7 100644 --- a/libjin/Utils/macros.h +++ b/libjin/Utils/macros.h @@ -2,16 +2,16 @@ #define __JIN_MACROS_H #include <cstring> -#define implement // ʵֽӿ - -#define shared // ķ - -#define MASK // enum - -#define onlyonce // ֻһ -#define CALLONCE(call) static char __dummy__=(call, 1) // ֻһ -#define SAFECALL(func, params) if(func) func(params) - -#define zero(mem) memset(&mem, 0, sizeof(mem)) +//#define implement // ʵֽӿ +// +//#define shared // ķ +// +//#define MASK // enum +// +//#define onlyonce // ֻһ +//#define CALLONCE(call) static char __dummy__=(call, 1) // ֻһ +//#define SAFECALL(func, params) if(func) func(params) +// +//#define zero(mem) memset(&mem, 0, sizeof(mem)) #endif
\ No newline at end of file diff --git a/libjin/modules.h b/libjin/modules.h index 6cc9336..5992f0c 100644 --- a/libjin/modules.h +++ b/libjin/modules.h @@ -22,7 +22,7 @@ #define JIN_MODULES_NET 1 #define JIN_NET_TEKCOS 1 -#define JIN_MODULES_PHYSICS 1 +#define JIN_MODULES_PHYSICS 0 #define JIN_PHYSICS_BOX2D 1 #define JIN_PHYSICS_NEWTON 1 @@ -30,7 +30,7 @@ #define JIN_MODULES_UI 1 -#define JIN_MODULES_TOOLS 1 +#define JIN_MODULES_TOOLS 0 #define JIN_TOOLS_COMPONENT 1 #define JIN_TOOLS_EVENTMSGCENTER 1 #define JIN_TOOLS_XML 1 @@ -49,7 +49,7 @@ * Open libjin debug */ -#define JIN_DEBUG 1 +#define JIN_DEBUG 0 /* * Operating system |