Free games for graphing calculators: NumWorks, TI-Nspire CX, Casio fx-CG50 and soon TI-84 Plus CE. Balatro, Celeste, Hollow Knight, Minecraft and more.
C calculatorcalculator-gamescasiochesscrossy-roaddrive-madfx-cg50gamesgeometry-dashgraphing-calculatorndlessnumworksnumworks-appsnumworks-calculatornumworks-gamenumworks-gamestetristi-84-plus-ceti-nspire
Mr Bullet: every level has its ground, and the levels can be won
Mason3632b46c9115a3c
diff --git a/games/mrbullet/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp b/games/mrbullet/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.cppindex 2ef6529d..077a30ef 100644--- a/games/mrbullet/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp+++ b/games/mrbullet/src/box2d/Box2D/Collision/Shapes/b2PolygonShape.cpp@@ -1,467 +1,470 @@-/*-* 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)- {- 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 (;;)- {- 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;-}+/* Altered for NumPlay's Mr Bullet (NumWorks calculator): points welded as in later Box2D (half the slop apart) */+/*+* 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)+ {+ // (as Mr Bullet's Box2D welds them: points closer than half the slop, 0.15 of its units; 2.3.1 itself+ // compares the squared distance with half the slop, 3 units, and turns small pieces into 2 m boxes)+ 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 (;;)+ {+ 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/games/mrbullet/src/data.bin b/games/mrbullet/src/data.binindex 0eea332a..44fa6a8b 100644Binary files a/games/mrbullet/src/data.bin and b/games/mrbullet/src/data.bin differdiff --git a/games/mrbullet/src/data.h b/games/mrbullet/src/data.hindex 76a798cb..2888b41a 100644--- a/games/mrbullet/src/data.h+++ b/games/mrbullet/src/data.h@@ -2,7 +2,7 @@#ifndef MB_DATA_H#define MB_DATA_H#define LEVEL_COUNT 596-#define LEVEL_MAX_BYTES 3104+#define LEVEL_MAX_BYTES 3456#define MODE_COUNT 4#define MODE_FIRST {0, 320, 404, 488, 596}#define PIC_BG 0diff --git a/games/mrbullet/src/draw.c b/games/mrbullet/src/draw.cindex 86dc075e..bb5874ed 100644--- a/games/mrbullet/src/draw.c+++ b/games/mrbullet/src/draw.c@@ -208,7 +208,7 @@ static void draw_obj(int i) {ncont = 0;cstart[0] = 0;int total = o->nout;- const uint8_t *hq = o->outline + 4 * o->nout;+ const uint8_t *hq = o->outline + 4 * o->nout + 1; /* (the holes, past their number) */for (int part = 0; part <= o->nholes && ncont < 16; part++) {if (part) {total = *hq++;diff --git a/games/mrbullet/src/game.c b/games/mrbullet/src/game.cindex 23fbdf86..2d8779d4 100644--- a/games/mrbullet/src/game.c+++ b/games/mrbullet/src/game.c@@ -32,6 +32,11 @@ static uint8_t pending_blast[MAX_OBJ]; /* explosives set off, going off in a f#define GRENADE_R 5.0f#define FUSE 150#define BLAST_R 160.0f+/* what a blast gives what it reaches: BLAST_PUSH kg m/s at its middle, less further off (its nearest part), but no+ faster than BLAST_SPEED m/s (not read in the original: fitted by the bot in tests/play.c, so that a grenade by a+ plank sends it across the floor, as Grenades 15 and 57 need) */+#define BLAST_PUSH 20.0f+#define BLAST_SPEED 12.0f/* blows to characters, as friction x friction x speed (m/s): one that knocks them over, one that kills */#define KNOCK_BLOW 0.06f#define KILL_BLOW 0.2f@@ -221,13 +226,14 @@ static bool build_poly(Obj *o, int oi, const uint8_t *parts, int nparts) {if (o->flags & F_HV) f.density *= 3;const uint8_t *save = rp;if (fixed) {- /* a static one: its outline and holes as loops of edges (its convex parts' boxes overlap too much: thousands- of contacts with what lies on it) */+ /* a static one: loops of edges (its convex parts' boxes overlap too much: thousands of contacts with what lies+ on it), the outline of its parts put together (tools/pack.py), or else its drawn outline and holes */float *xy = mb_scratch;- rp = o->outline;- int n = o->nout;- for (int h = 0; h <= o->nholes; h++) {- if (h) n = rd8();+ rp = nparts ? parts : o->outline;+ int n = nparts ? 0 : o->nout;+ for (int h = 0; h < (nparts ? nparts : o->nholes + 1); h++) {+ if (h == 1 && !nparts) rp++; /* (past the number of holes, to the first one's) */+ if (h || nparts) n = rd8();int m = n < SCRATCH_FLOATS / 2 ? n : SCRATCH_FLOATS / 2;for (int i = 0; i < n; i++) {float x = rdc(), y = rdc();@@ -295,10 +301,12 @@ bool game_load(int level, uint8_t *buf) {c->alive = 1;c->left = (flags & F_RH) != 0;c->hittable = (flags & (F_HKI | F_HGKI)) != 0;- c->fx = x0, c->fy = y0;- c->h = sqrtf((x1 - x0) * (x1 - x0) + (y1 - y0) * (y1 - y0));+ /* as the game makes him: upright, as tall as his segment is high, about its middle (a segment drawn+ leaning gives a man standing) */+ c->h = fabsf(y1 - y0);if (c->h < 20) c->h = 80;- c->tilt = atan2f(x1 - x0, -(y1 - y0));+ c->fx = (x0 + x1) / 2, c->fy = (y0 + y1) / 2 + c->h / 2;+ c->tilt = 0;c->body = -1;for (int p = 0; p < P_COUNT; p++) c->part[p] = -1;if (c->role == R_HERO && g.hero < 0) {@@ -368,15 +376,18 @@ bool game_load(int level, uint8_t *buf) {}if (!build_obj(i)) return false;}+ /* (Mr Bullet himself is a picture where he stands, with no body, unless his bullets can kill him: Friendly Fire) */for (int i = 0; i < g.nchar; i++)- if (!make_standing(&g.ch[i], i)) return false;+ if ((g.ch[i].role != R_HERO || g.ch[i].hittable) && !make_standing(&g.ch[i], i)) return false;for (int i = 0; i < g.nsw; i++) {Switch *s = &g.sw[i];float mx = (s->x0 + s->x1) / 2, my = (s->y0 + s->y1) / 2, dx = s->x1 - s->x0, dy = s->y1 - s->y0;float len = sqrtf(dx * dx + dy * dy);s->body = (int16_t)world_body(WB_STATIC, mx, my, atan2f(dy, dx), CODE(T_SWITCH, i), false, false, 1);if (s->body < 0) return false;- world_box(s->body, 0, 0, len / 2 + 2, 6, &FIX_SENSOR);+ /* (as the game makes it: the segment and 0.4 of its length in front of it, on its right going from its end+ to its start, where the bullet comes from) */+ world_box(s->body, 0, -0.2f * len, len / 2, 0.2f * len, &FIX_SENSOR);}rp = pins;for (int i = 0; i < npin; i++) {@@ -397,11 +408,13 @@ bool game_load(int level, uint8_t *buf) {p->t = (uint8_t)t, p->motor = (uint8_t)motor, p->a = (int8_t)a, p->b = (int8_t)b, p->joint = -1;if (t == 2) {if (ba < 0 && bb < 0) continue;- p->joint = (int16_t)world_revolute(ba, bb, vx[0], vy[0], false, 0, 0, motor != 0, ms, mt);+ /* (a motor turns at ms radians a second, clockwise when its mcw is set: Box2D's speed is anticlockwise) */+ p->joint = (int16_t)world_revolute(ba, bb, vx[0], vy[0], false, 0, 0, motor & 1, motor & 2 ? -ms : ms, mt);p->x0 = vx[0], p->y0 = vy[0];} else if (t == 3) {if (ba < 0 && bb < 0) continue;- float len = rl > 0 ? rl : sqrtf((lbx - lax) * (lbx - lax) + (lby - lay) * (lby - lay));+ /* (as long as drawn, and rl longer: the game's rope) */+ float len = sqrtf((lbx - lax) * (lbx - lax) + (lby - lay) * (lby - lay)) + rl;p->joint = (int16_t)world_rope(ba, bb, lax, lay, lbx, lby, len);p->x0 = lax, p->y0 = lay, p->x1 = lbx, p->y1 = lby;} else if (t == 5) {@@ -605,7 +618,7 @@ static void blast(float x, float y) {float cx, cy, s, cs;world_xf(o->body, &cx, &cy, &s, &cs);if (o->kind == K_SEG) cx += 0, cy += 0;- /* the nearest point of its box: its centre is enough for these sizes */+ /* from the blast to its middle, and how far its nearest part is */float dx = cx - x, dy = cy - y;if (o->kind == K_POLY && o->nout) {/* (polygons' origins can be far from them: use their outline's middle) */@@ -618,15 +631,17 @@ static void blast(float x, float y) {mx /= o->nout, my /= o->nout;dx = cx + cs * mx - s * my - x, dy = cy + s * mx + cs * my - y;}- float d = sqrtf(dx * dx + dy * dy);+ float px, py, d = world_nearest(o->body, x, y, &px, &py);+ if (d > 1) dx = px - x, dy = py - y; /* (pushed away from the blast at its nearest point) */if (d >= BLAST_R) continue;if (o->flags & F_EXPL) { if (!pending_blast[i]) pending_blast[i] = 6; continue; }if (o->flags & F_BREAK) { remove_obj(i); continue; }if (!world_dynamic(o->body)) continue;- float m = world_mass(o->body), f = 3.0f * (1 - d / BLAST_R) / (d > 1 ? d : 1);- float cap = m * 12.0f / (f * (d > 1 ? d : 1) + 1e-6f);+ float l = sqrtf(dx * dx + dy * dy);+ float m = world_mass(o->body), f = BLAST_PUSH * (1 - d / BLAST_R) / (l > 1 ? l : 1);+ float cap = m * BLAST_SPEED / (f * (l > 1 ? l : 1) + 1e-6f);if (cap < 1) f *= cap;- world_impulse(o->body, dx * f, dy * f, cx + dx * 0.5f, cy + dy * 0.5f);+ world_impulse(o->body, dx * f, dy * f, px, py);}}@@ -663,6 +678,8 @@ static void switch_on(int si) {o->gone = 0;build_obj(i);}+ } else if (o->flags & F_EXPL) {+ if (!pending_blast[i]) pending_blast[i] = 1; /* (a crate of TNT on a switch goes off) */} else {remove_obj(i);}diff --git a/games/mrbullet/src/world.cpp b/games/mrbullet/src/world.cppindex 1c9da792..c0083455 100644--- a/games/mrbullet/src/world.cpp+++ b/games/mrbullet/src/world.cpp@@ -141,6 +141,14 @@ extern "C" bool world_poly(int b, const float *xy, int n, const WFix *f) {b2PolygonShape p;p.Set(v, n);if (p.m_count < 3) return false;+ /* (and anything else it made that box of: a point of it outside the piece's points) */+ b2AABB box;+ box.lowerBound = box.upperBound = v[0];+ for (int i = 1; i < n; i++) box.lowerBound = b2Min(box.lowerBound, v[i]), box.upperBound = b2Max(box.upperBound, v[i]);+ for (int i = 0; i < p.m_count; i++)+ if (p.m_vertices[i].x < box.lowerBound.x - U || p.m_vertices[i].x > box.upperBound.x + U ||+ p.m_vertices[i].y < box.lowerBound.y - U || p.m_vertices[i].y > box.upperBound.y + U)+ return false;return add_shape(b, &p, f);}@@ -150,8 +158,8 @@ extern "C" bool world_chain(int b, float *xy, int n, const WFix *f) {int m = 0;for (int i = 0; i < n; i++) {b2Vec2 p(xy[2 * i] * U, -xy[2 * i + 1] * U);- /* (the rounded corners' points 3 units apart at most: fewer edges, each a box in the broad phase) */- if (m && b2DistanceSquared(p, v[m - 1]) < 9.0f * U * U) continue;+ /* (points closer than a unit: one) */+ if (m && b2DistanceSquared(p, v[m - 1]) < 1.0f * U * U) continue;v[m++] = p;}while (m > 3 && b2DistanceSquared(v[0], v[m - 1]) < 0.25f * U * U) m--;@@ -359,6 +367,25 @@ extern "C" int world_query(float x0, float y0, float x1, float y1, int *out, intreturn q.n;}+extern "C" float world_nearest(int b, float x, float y, float *nx, float *ny) {+ /* the nearest point of the body's shapes' boxes to (x, y), and how far it is */+ float best = 1e9f;+ *nx = x, *ny = y;+ if (!world_alive(b)) return best;+ b2Vec2 p = M(x, y);+ for (b2Fixture *f = bodies[b]->GetFixtureList(); f; f = f->GetNext()) {+ if (f->IsSensor()) continue;+ for (int c = 0; c < f->GetShape()->GetChildCount(); c++) {+ b2AABB box;+ f->GetShape()->ComputeAABB(&box, bodies[b]->GetTransform(), c);+ b2Vec2 q = b2Clamp(p, box.lowerBound, box.upperBound);+ float d = b2Distance(p, q) / U;+ if (d < best) best = d, *nx = q.x / U, *ny = -q.y / U;+ }+ }+ return best;+}+extern "C" int world_bodies(void) { return world ? world->GetBodyCount() : 0; }extern "C" int world_contacts(void) { return world ? world->GetContactCount() : 0; }diff --git a/games/mrbullet/src/world.h b/games/mrbullet/src/world.hindex d7f92803..126c2636 100644--- a/games/mrbullet/src/world.h+++ b/games/mrbullet/src/world.h@@ -77,6 +77,8 @@ int world_query(float x0, float y0, float x1, float y1, int *out, int max);void game_contact(int obj_a, int obj_b, int body_a, int body_b, float speed, float px, float py);bool game_contact_enabled(int obj_a, int obj_b);+/* the nearest point of a body's shapes' boxes to (x, y): how far, and where */+float world_nearest(int b, float x, float y, float *nx, float *ny);int world_bodies(void);int world_contacts(void);#ifdef __cplusplusdiff --git a/games/mrbullet/tests/play.c b/games/mrbullet/tests/play.cindex b3751b9e..c40fae61 100644--- a/games/mrbullet/tests/play.c+++ b/games/mrbullet/tests/play.c@@ -1,8 +1,16 @@/* Mr Bullet on a computer: the tests (make test) and pictures.*- * build/play test DIR physics checks, a bot through the first levels of every mode, every level played- * with random keys, saves; pictures of a few levels into DIR- * build/play shot LEVEL OUT a picture of a level (PPM), after FRAMES steps with the aim at ANGLE (env) */+ * build/play test DIR physics checks, a bot through the first levels of every mode, every level left+ * alone, plays that win, every level played with random keys, saves; pictures into DIR+ * build/play shot LEVEL OUT a picture of a level (PPM), after FRAMES steps with the aim at ANGLE and POWER (env;+ * a shot fired first, unless NOFIRE)+ * build/play settle [A B] every level (or A to B) left alone 4 seconds: nothing falls out, no one falls or dies+ * build/play plan LEVEL 'P' a level played with shots, each once the last is done: "-171 69" (degrees), "40/2"+ * (a grenade, power 0.2 + 0.1 x 2), "16@60" (after 60 steps); PLAN_OBJS=1 lists where+ * things end up, a third argument saves a picture+ * build/play win A B levels A to B played through by a bot (shot by shot, the best few kept), up to the+ * level's three-star shots and two more; FINE=1 tries finer angles and powers+ * build/play fine LEVEL S one shot at every S degrees (and power) until one wins */#include <math.h>#include <stdio.h>#include <stdlib.h>@@ -153,6 +161,162 @@ static int solve(int level, int *stars_out) {return best;}+/* ---- a level played through with several shots: each fired once the last one is done and things have settled+ (or after a wait, for what moves on its own), as a player would */+typedef struct {+ int16_t aim; /* degrees x 20 */+ uint8_t power; /* grenades: 0 to 8 (0.2 to 1) */+ uint8_t wait; /* steps / 15 before it */+} Plan;+#define MAX_PLAN 8+static bool shots_flying(void) {+ for (int i = 0; i < MAX_SHOT; i++)+ if (g.shot[i].body >= 0) return true;+ return false;+}+/* plays the plan; its state (ST_WON, ST_LOST, or ST_PLAY: not over yet) and the enemies still standing */+static int play_plan(int level, const Plan *p, int n, bool finish, int *left) {+ if (!game_load(level, (uint8_t *)level_mem)) return -1;+ for (int k = 0; k < n && g.state == ST_PLAY; k++) {+ for (int s = 0; s < p[k].wait * 15 && g.state == ST_PLAY; s++) game_step();+ g.aim = p[k].aim * 0.05f * 3.14159265f / 180;+ g.ch[g.hero].left = cosf(g.aim) < 0;+ g.power = 0.2f + 0.1f * p[k].power;+ game_fire();+ /* until the shot is done and nothing has moved for a while (at most 6 seconds) */+ for (int s = 0; s < 360 && g.state == ST_PLAY; s++) {+ game_step();+ if (s >= 60 && !shots_flying() && !g.end_wait) break;+ }+ }+ if (finish)+ for (int s = 0; s < 900 && g.state == ST_PLAY; s++) game_step();+ *left = g.enemies_left;+ return g.state;+}+static void plan_text(char *o, const Plan *p, int n) {+ for (int k = 0; k < n; k++) {+ o += sprintf(o, p[k].aim % 10 ? "%s%.2f" : "%s%.1f", k ? " " : "", p[k].aim * 0.05f);+ if (g.grenades) o += sprintf(o, "/%d", p[k].power);+ if (p[k].wait) o += sprintf(o, "@%d", p[k].wait * 15);+ }+}+/* a plan from its text ("-171 69", grenades "40/2", a wait "16@60"); its length */+static int plan_parse(const char *t, Plan *p) {+ int n = 0;+ while (*t && n < MAX_PLAN) {+ char *e;+ float a = strtof(t, &e);+ if (e == t) break;+ p[n] = (Plan){(int16_t)lroundf(a * 20), 0, 0};+ t = e;+ if (*t == '/') p[n].power = (uint8_t)strtol(t + 1, &e, 10), t = e;+ if (*t == '@') p[n].wait = (uint8_t)(strtol(t + 1, &e, 10) / 15), t = e;+ while (*t == ' ') t++;+ n++;+ }+ return n;+}++/* plays that win (level numbers from 1, across the modes; found by `play win`): see main */+static const struct {+ int level;+ const char *plan;+} known_wins[] = {+ {13, "-109"}, /* Classic 13: a cave in the ground (a static shape with a hole) */+ {16, "-73"}, /* Classic 16: the tower stands (no piece made a 2 m box) */+ {18, "-171 69"}, /* Classic 18: the ball's rope as long as the game makes it */+ {66, "-84"}, /* Classic 66: TNT on a switch goes off */+ {80, "63 -71"}, /* Classic 80: switches in front of the wall */+ {98, "-80"}, /* Classic 98: a motor turning clockwise */+ {123, "-82"}, /* Classic 123: a rope with slack */+ {124, "-107"},+ {170, "-177 -131 145@60 -71"},+ {208, "45 19 44"}, /* Classic 208: Mr Bullet stands where he is */+ {224, "22 -8"}, /* Classic 224: a ball on a rope */+ {255, "30"},+ {335, "-39/0 -87/0"}, /* Grenades 15: the plank under the wall */+ {377, "-126/8"}, /* Grenades 57: the crate in its notch */+ {569, "-130"}, /* Friendly Fire 81: the ball stays on the peak */+};++/* a beam search, shot by shot, for a plan that wins with the level's bullets: the best few after each shot (by+ enemies down) kept; 1 if found (in out) */+static int win(int level, Plan *out, int *nout) {+ enum { BEAM = 8, CANDS = 8192 };+ static Plan beam[BEAM][MAX_PLAN], nbeam[BEAM][MAX_PLAN];+ static struct { int score, from; Plan s; } cand[CANDS];+ int left;+ if (!game_load(level, (uint8_t *)level_mem)) return 0;+ bool gren = g.grenades, moving = false, fine = getenv("FINE") != 0; /* (FINE: a half degree, power by tenths) */+ for (int i = 0; i < g.nobj; i++) moving |= g.obj[i].kin != 0;+ for (int i = 0; i < g.npin; i++) moving |= g.pin[i].motor != 0;+ int shots = g.tr + 2 < 6 ? g.tr + 2 : 6, nb = 1, enemies = g.enemies_left; /* (the gold bullet left over) */+ for (int depth = 0; depth < shots; depth++) {+ int nc = 0;+ for (int b = 0; b < nb; b++)+ for (int w = 0; w < (moving ? 6 : 1); w++)+ for (int pw = 0; pw < (gren ? 9 : 1); pw += fine ? 1 : 2)+ for (int a = 0; a < 720; a += fine ? 1 : gren ? 6 : 2) {+ Plan *p = beam[b];+ p[depth] = (Plan){(int16_t)((a - 360) * 10), (uint8_t)pw, (uint8_t)(w * 2)};+ int st = play_plan(level, p, depth + 1, depth + 1 == shots, &left);+ if (st == ST_PLAY && depth + 1 < shots) { /* (not over: is it won once things finish?) */+ int l2, s2 = ST_PLAY;+ for (int s = 0; s < 240 && g.state == ST_PLAY; s++) game_step();+ s2 = g.state, l2 = g.enemies_left;+ if (s2 == ST_WON) st = ST_WON, left = l2;+ }+ if (st == ST_WON) {+ memcpy(out, p, sizeof(Plan) * (depth + 1));+ *nout = depth + 1;+ return 1;+ }+ if (st == ST_LOST || nc >= CANDS) continue;+ /* (and what changed on the way: glass broken, crates gone off, switches, ropes cut, things moved) */+ int changed = 0;+ for (int i = 0; i < g.nobj; i++) {+ Obj *o = &g.obj[i];+ if (o->gone != (o->sw && (o->flags & F_SI))) changed += 3;+ else if (o->body >= 0 && world_dynamic(o->body)) {+ float x, y, sn, cs;+ world_xf(o->body, &x, &y, &sn, &cs);+ float x0 = o->cx + (o->kind == K_SEG ? o->bx : 0), y0 = o->cy + (o->kind == K_SEG ? o->by : 0);+ if (fabsf(x - x0) + fabsf(y - y0) > 20) changed++;+ }+ }+ for (int i = 0; i < g.nsw; i++) changed += 3 * g.sw[i].on;+ for (int i = 0; i < g.npin; i++) changed += 3 * (g.pin[i].t == 3 && g.pin[i].joint < 0);+ cand[nc].score = (enemies - left) * 1000 + (changed < 30 ? changed : 30) * 16 ++ (int)((uint32_t)(a * 7 + w * 131 + pw * 17) * 2654435761u >> 28);+ cand[nc].from = b, cand[nc].s = p[depth];+ nc++;+ }+ if (!nc) return 0;+ /* the best, a few degrees apart */+ int nn = 0;+ for (int pick = 0; pick < BEAM; pick++) {+ int best = -1;+ for (int c = 0; c < nc; c++) {+ if (cand[c].score < 0) continue;+ bool near = false;+ for (int k = 0; k < nn && !near; k++)+ near = nbeam[k][depth].power == cand[c].s.power && nbeam[k][depth].wait == cand[c].s.wait &&+ abs(nbeam[k][depth].aim - cand[c].s.aim) < 100;+ if (!near && (best < 0 || cand[c].score > cand[best].score)) best = c;+ }+ if (best < 0) break;+ memcpy(nbeam[nn], beam[cand[best].from], sizeof(Plan) * depth);+ nbeam[nn][depth] = cand[best].s;+ cand[best].score = -1;+ nn++;+ }+ memcpy(beam, nbeam, sizeof beam);+ nb = nn;+ }+ return 0;+}+static uint32_t rng = 12345;static uint32_t rnd(void) { rng ^= rng << 13, rng ^= rng >> 17, rng ^= rng << 5; return rng; }@@ -188,6 +352,54 @@ static void fuzz_level(int level) {game_end();}+/* a level left alone for 4 seconds: nothing falls out of the world (the ground holds what stands on it), no one+ falls far (a man on a seesaw may go down with it) or dies; the problems found, printed */+static int settle_level(int level) {+ static const char *const mode_names[] = {"Classic", "Grenades", "Hostages", "Friendly Fire"};+ int bad = 0;+ if (!game_load(level, (uint8_t *)level_mem)) {+ printf("FAIL level %d: it doesn't load\n", level + 1);+ return 1;+ }+ int mode = g.mode, n = level - res_mode_first(mode) + 1, alive = 0;+ float y0[MAX_CHAR];+ for (int i = 0; i < g.nchar; i++) {+ float x, s, c;+ y0[i] = 0;+ game_part(&g.ch[i], P_TORSO, &x, &y0[i], &s, &c);+ alive += g.ch[i].alive;+ }+ for (int s = 0; s < 240 && g.state == ST_PLAY; s++) game_step();+ for (int i = 0; i < g.nobj; i++) {+ Obj *o = &g.obj[i];+ float x, y, s, c;+ if (o->gone || o->body < 0 || !world_dynamic(o->body)) continue;+ world_xf(o->body, &x, &y, &s, &c);+ if (!(y < 300 && y > -600 && x > -400 && x < 400)) { /* (the field: 440 x 568 about its middle) */+ printf("FAIL %s %d (level %d): object %d fell out of the world, at %.0f %.0f\n", mode_names[mode], n, level + 1,+ o->idx, x, y);+ bad++;+ }+ }+ for (int i = 0; i < g.nchar; i++) {+ float x, y, s, c;+ if (!g.ch[i].alive) continue;+ if (game_part(&g.ch[i], P_TORSO, &x, &y, &s, &c) && !(y - y0[i] < 150 && y < 300)) {+ printf("FAIL %s %d (level %d): character %d fell %.0f\n", mode_names[mode], n, level + 1, i, y - y0[i]);+ bad++;+ }+ }+ int now = 0;+ for (int i = 0; i < g.nchar; i++) now += g.ch[i].alive;+ if (now < alive) {+ printf("FAIL %s %d (level %d): %d of its characters died on their own\n", mode_names[mode], n, level + 1,+ alive - now);+ bad++;+ }+ game_end();+ return bad;+}+static void ui_fuzz(void) {ui_init((uint8_t *)level_mem, (uint16_t *)strip, scratch);static const uint32_t keys[] = {0, KB_OK, KB_UP, KB_DOWN, KB_LEFT, KB_RIGHT, KB_BACK, KB_OK | KB_UP};@@ -227,7 +439,8 @@ int main(int argc, char **argv) {g.ch[g.hero].left = cosf(g.aim) < 0;}int frames = fr ? atoi(fr) : 0;- if (frames > 0) game_fire();+ if (getenv("POWER")) g.power = (float)atof(getenv("POWER"));+ if (frames > 0 && !getenv("NOFIRE")) game_fire();for (int i = 0; i < frames; i++) game_step();char name[32];snprintf(name, sizeof name, "level%d", level + 1);@@ -301,6 +514,64 @@ int main(int argc, char **argv) {}return 0;}+ if (argc >= 4 && !strcmp(argv[1], "fine")) {+ /* one shot at every STEP degrees (grenades: and every tenth of power) until it wins: "fine LEVEL STEP" */+ int l = atoi(argv[2]) - 1, stars;+ float step = (float)atof(argv[3]);+ game_load(l, (uint8_t *)level_mem);+ int powers = g.grenades ? 9 : 1;+ for (int pw = 0; pw < powers; pw++)+ for (float a = -180; a < 180; a += step)+ if (try_shot(l, a * 3.14159265f / 180, 0.2f + 0.1f * pw, &stars) == ST_WON) {+ printf("level %d: won with 1 shot: %.2f", l + 1, a);+ if (g.grenades) printf("/%d", pw);+ printf("\n");+ return 0;+ }+ printf("level %d: no one shot wins\n", l + 1);+ return 1;+ }+ if (argc >= 4 && !strcmp(argv[1], "plan")) {+ /* a level played with a plan: "plan LEVEL '-171 69'" */+ Plan p[MAX_PLAN];+ int left, n = plan_parse(argv[3], p), st = play_plan(atoi(argv[2]) - 1, p, n, true, &left);+ printf("level %s: %s, %d enemies left, %d shots\n", argv[2], st == ST_WON ? "won" : st == ST_LOST ? "lost" : "not over",+ left, g.shots);+ if (getenv("PLAN_OBJS"))+ for (int i = 0; i < g.nobj; i++)+ if (g.obj[i].body >= 0 && world_dynamic(g.obj[i].body)) {+ float x, y, sn, cs;+ world_xf(g.obj[i].body, &x, &y, &sn, &cs);+ printf(" object %d (i %d) at %.0f %.0f\n", i, g.obj[i].idx, x, y);+ }+ if (argc >= 5) picture(argv[4]);+ return st != ST_WON;+ }+ if (argc >= 4 && !strcmp(argv[1], "win")) {+ /* levels A to B played through with several shots if need be */+ int bad = 0;+ for (int l = atoi(argv[2]) - 1; l < atoi(argv[3]); l++) {+ Plan p[MAX_PLAN];+ int n = 0;+ char text[256];+ if (win(l, p, &n)) {+ plan_text(text, p, n);+ printf("level %d: won with %d shot%s: %s\n", l + 1, n, n > 1 ? "s" : "", text);+ } else {+ printf("level %d: no win found\n", l + 1);+ bad++;+ }+ fflush(stdout);+ }+ return bad != 0;+ }+ if (argc >= 2 && !strcmp(argv[1], "settle")) {+ /* every level (or FROM to TO) left alone */+ int a = argc >= 4 ? atoi(argv[2]) - 1 : 0, b = argc >= 4 ? atoi(argv[3]) : LEVEL_COUNT, bad = 0;+ for (int l = a; l < b; l++) bad += settle_level(l) != 0;+ printf("settle: %d of %d levels with a problem\n", bad, b - a);+ return bad != 0;+ }if (argc >= 2 && !strcmp(argv[1], "mem")) {/* Box2D's memory: loaded, then the most while played with random keys */for (int l = 0; l < LEVEL_COUNT; l++) {@@ -336,6 +607,22 @@ int main(int argc, char **argv) {}printf("bot: %d of %d levels cleared with one shot\n", solved, tried);CHECK(solved * 10 >= tried * 7, "the bot clears most of the first levels with one shot");+ /* every level left alone: the ground holds, nothing falls out of the world, no one dies on his own */+ int unsettled = 0;+ for (int l = 0; l < LEVEL_COUNT; l++) unsettled += settle_level(l) != 0;+ CHECK(!unsettled, "%d levels lose something when left alone", unsettled);+ printf("settle: %d levels left alone\n", LEVEL_COUNT);+ /* plays that win (found by `play win`): the levels of issue #365 (no ground, the ball's rope, the crate) and+ others whose shapes, ropes or men were wrong */+ int won = 0, nwins = (int)(sizeof known_wins / sizeof *known_wins);+ for (int k = 0; k < nwins; k++) {+ Plan p[MAX_PLAN];+ int left, n = plan_parse(known_wins[k].plan, p), st = play_plan(known_wins[k].level - 1, p, n, true, &left);+ CHECK(st == ST_WON, "level %d: '%s' wins (state %d, %d enemies left)", known_wins[k].level, known_wins[k].plan, st,+ left);+ won += st == ST_WON;+ }+ printf("wins: %d of %d known plays win\n", won, nwins);/* every level, random keys; Box2D's memory held as on the calculator (its blocks are bigger here: 64 bits) */b2_heap_limit = 120000;long peak = 0;diff --git a/games/mrbullet/tools/pack.py b/games/mrbullet/tools/pack.pyindex 36fa7736..4688c9a4 100644--- a/games/mrbullet/tools/pack.py+++ b/games/mrbullet/tools/pack.py@@ -79,6 +79,70 @@ def convex_parts(p):return [[v for xy in s for v in xy]]+def boundary(parts):+ """A static shape's edges as the game's physics has them: the outline of its convex parts put together (their+ edges met by no other part's), loops of points; None when they don't close (then its drawn outline stands in)"""+ def key(x, y): return (q(x), q(y))+ polys = []+ for part in parts:+ ps = [key(part[i], part[i + 1]) for i in range(0, len(part), 2)]+ ps = [v for i, v in enumerate(ps) if v != ps[i - 1]]+ if len(ps) < 3 or area(ps) == 0: continue+ polys.append(ps if area(ps) > 0 else ps[::-1])+ verts = {v for ps in polys for v in ps}+ edges = {}+ for ps in polys:+ for i in range(len(ps)):+ a, b = ps[i], ps[(i + 1) % len(ps)]+ # (split where another part's corner lies on it)+ d2 = (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2+ on = sorted((((v[0] - a[0]) * (b[0] - a[0]) + (v[1] - a[1]) * (b[1] - a[1])) / d2, v) for v in verts+ if v != a and v != b and abs((b[0] - a[0]) * (v[1] - a[1]) - (b[1] - a[1]) * (v[0] - a[0])) <= 0.5 * d2 ** 0.5)+ seq = [a] + [v for t, v in on if 0 < t < 1] + [b]+ for j in range(len(seq) - 1):+ edges[seq[j], seq[j + 1]] = edges.get((seq[j], seq[j + 1]), 0) + 1+ for (a, b) in list(edges):+ m = min(edges[a, b], edges.get((b, a), 0))+ if m: edges[a, b] -= m; edges[b, a] -= m+ nxt = {}+ for (a, b), n in sorted(edges.items()):+ nxt.setdefault(a, []).extend([b] * n)+ loops = []+ while any(nxt.values()):+ start = min(a for a, l in nxt.items() if l)+ loop, a = [start], start+ while True:+ if not nxt.get(a): return None+ a = nxt[a].pop()+ if a == start: break+ loop.append(a)+ if len(loop) > 255: return None+ loops.append([c / 8 for v in thin(loop) for c in v])+ return loops+++def thin(loop):+ """Fewer points on the rounded corners (runs of edges under 3 units, each point an edge in Box2D's broad phase):+ a run keeps its ends and every other point from each end inwards, so that a shape the same both ways stays so+ (a ball on a peak stays on it)"""+ n = len(loop)+ short = [((loop[(i + 1) % n][0] - loop[i][0]) ** 2 + (loop[(i + 1) % n][1] - loop[i][1]) ** 2) < (3 * 8) ** 2+ for i in range(n)]+ if all(short): return loop+ keep = [True] * n+ s = next(i for i in range(n) if not short[i]) # (a long edge: the runs start after one)+ i, done = (s + 1) % n, 0+ while done < n:+ run = [i]+ while short[run[-1]]: run.append((run[-1] + 1) % n) # (the run's points: its edges' ends)+ k = len(run)+ for j in range(k):+ keep[run[j]] = min(j, k - 1 - j) % 2 == 0+ done += k+ i = (run[-1] + 1) % n+ return [v for v, kp in zip(loop, keep) if kp]++def split8(part):"""a convex part of more than 8 points as fans of at most 8 (Box2D's polygons hold 8)"""pts = [(part[i], part[i + 1]) for i in range(0, len(part), 2)]@@ -103,13 +167,14 @@ def level_bytes(c):if p.get(name): bits |= 1 << kparts = p['p']is_char = any(p.get(k) for k in ('ki', 'gki', 'hki', 'hgki', 'vi', 'hs'))- if is_char and len(parts) == 1 and len(parts[0]) > 4:- parts = [parts[0][:4]] # (a few have the editor's stray points after feet and head)+ if (is_char or p.get('b')) and len(parts) == 1 and len(parts[0]) > 4:+ parts = [parts[0][:4]] # (a few have the editor's stray points after feet and head, centre and rim)if not is_char and not p.get('f') and not p.get('b') and len(parts) > 1:parts = convex_parts(p)if not is_char and not p.get('b') and (len(parts) > 1 or len(parts[0]) > 4):if p.get('f'):- parts = [] # static: its outline is its shape (a loop of edges, game.c)+ # static: its shape is loops of edges (game.c), its parts' outline (or the drawn one)+ parts = boundary(parts) or []else:parts = [q for part in parts for q in split8(part)]if not parts: kind = 0@@ -126,7 +191,7 @@ def level_bytes(c):else:out += struct.pack('<B', len(parts))for part in parts:- assert 3 <= len(part) // 2 <= 8, len(part)+ assert 3 <= len(part) // 2 <= (255 if p.get('f') else 8), len(part)out += struct.pack('<B', len(part) // 2)pts(out, part)tp = p.get('tp')@@ -141,7 +206,9 @@ def level_bytes(c):for p in pins:cx, cy = p['ce']v = p['v'][2:]- out += struct.pack('<BbbB', p['t'], p.get('pia', -1), p.get('pib', -1), 1 if p.get('m') else 0)+ # (a motor, turning clockwise: mcw)+ out += struct.pack('<BbbB', p['t'], p.get('pia', -1), p.get('pib', -1),+ (1 if p.get('m') else 0) | (2 if p.get('m') and p.get('mcw') else 0))out += struct.pack('<hh', q(cx), q(cy))out += struct.pack('<B', len(v) // 2)pts(out, v)