Complete Physics Engine Documentation
This document consolidates the entire source code documentation into one place, covering every variable and every method. It is organized by module (Math, Shapes, Body, Collision, Contact, Force, World, Graphics, Application, and Main Entry) to give you a clear reference.
Table of Contents
- Math Module – Vec2
- Shapes Module – Shape, CircleShape, PolygonShape, BoxShape
- Rigid Body – Body
- Collision Handling – CollisionDetection and Contact
- Constants (Constants.h)
- Force Generators – Force
- World Management – World
- Graphics and Rendering – Graphics
- Application Control – Application
- Main Entry Point – Main.cpp
- Use Cases and Examples
- Final Remarks
1. Math Module – Vec2
Files:
Vec2.hVec2.cpp
Overview
- Purpose: Encapsulates 2D vector arithmetic used for positions, velocities, forces, etc.
Data Members
float xfloat y
Constructors / Destructor
-
Vec2()
- Initializes
xandyto 0.
- Initializes
-
Vec2(float x, float y)
- Initializes
xandyto the provided arguments.
- Initializes
-
~Vec2() = default
- Default destructor.
Methods
-
void Add(const Vec2& v)
Addsv.xtothis->xandv.ytothis->y. -
void Sub(const Vec2& v)
Subtractsv.xfromthis->xandv.yfromthis->y. -
void Scale(float n)
Multiplies bothxandybyn. -
Vec2 Rotate(float angle) const
Returns a new vector rotated byangleradians. -
float Magnitude() const
Returns the length of the vector,sqrt(x*x + y*y). -
float MagnitudeSquared() const
Returns the square of the vector length,(x*x + y*y). -
Vec2& Normalize()
Normalizes the vector in-place if its magnitude is not zero. -
Vec2 UnitVector() const
Returns a normalized copy of this vector. -
Vec2 Normal() const
Returns a perpendicular (rotated 90 degrees) version of this vector and normalizes it. -
float Dot(const Vec2& v) const
Returns the dot product of this vector andv. -
float Cross(const Vec2& v) const
Returns a scalar cross product result of this vector andv.
Operators
=(assignment)==(equality) and!=(inequality)+,-,*,/(scalar multiply/divide)+=,-=,*=,/=unary -(negates both components)
These operators enable natural arithmetic syntax with Vec2.
2. Shapes Module – Shape, CircleShape, PolygonShape, BoxShape
Files:
Shape.hShape.cpp
2.1 Shape (Abstract)
Data / Methods
virtual ~Shape() = defaultvirtual ShapeType GetType() const = 0
Returns an enum value:CIRCLE,POLYGON, orBOX.virtual Shape* Clone() const = 0
Creates a copy of the shape on the heap.virtual void UpdateVertices(float angle, const Vec2& position) = 0
Updates shape vertices in world space.virtual float GetMomentOfInertia() const = 0
Returns the shape’s base moment of inertia (before multiplying by mass).
2.2 CircleShape
Data Members
float radius
Constructor / Destructor
CircleShape(const float radius)
Initializesradius.~CircleShape()
Logs destruction.
Methods
ShapeType GetType() const
ReturnsCIRCLE.Shape* Clone() const
Creates a newCircleShapewith the same radius.void UpdateVertices(float angle, const Vec2& position)
No-op for circles (no vertices to update).float GetMomentOfInertia() const
Returns0.5 * radius * radius(before multiplying by mass).
2.3 PolygonShape
Data Members
std::vector<Vec2> localVerticesstd::vector<Vec2> worldVertices
Constructor / Destructor
PolygonShape(const std::vector<Vec2> vertices)
Copies the input vertices into bothlocalVerticesandworldVertices.~PolygonShape()
Logs destruction.
Methods
ShapeType GetType() const
ReturnsPOLYGON.Shape* Clone() const
Copies the polygon by duplicatinglocalVertices.void UpdateVertices(float angle, const Vec2& position)
Rotates each local vertex byangle, then addspositionto produceworldVertices.float GetMomentOfInertia() const
Returns5000.0f(placeholder).Vec2 EdgeAt(int index) const
Returns the vector fromworldVertices[index]toworldVertices[(index+1) % size].float FindMinSeparation(const PolygonShape* other, Vec2& axis, Vec2& point) const
Scans each edge, projects vertices of the other polygon to find minimal separation.
2.4 BoxShape
float widthfloat height
Constructor / Destructor
BoxShape(float width, float height)
FillslocalVerticeswith the four rectangle corners (centered at origin).~BoxShape()
Currently empty, marked as TODO.
Methods
ShapeType GetType() const
ReturnsBOX.Shape* Clone() const
Allocates a newBoxShape(width, height).float GetMomentOfInertia() const
Returns(1/12)*(width^2 + height^2)before mass multiplication, approximated by0.083333*(width^2 + height^2).
3. Rigid Body – Body
Files:
Body.hBody.cpp
Data Members
bool isCollidingVec2 position, velocity, accelerationfloat rotation, angularVelocity, angularAccelerationVec2 sumForcesfloat sumTorquefloat mass, invMassfloat I, invIfloat restitutionfloat frictionShape* shapeSDL_Texture* texture
Constructor / Destructor
-
Body(const Shape& shape, float x, float y, float mass)- Clones
shapeintothis->shape. - Initializes
positionto(x, y), velocity and acceleration to zero. - Sets
rotation,angularVelocity,angularAccelerationto zero. - Sets
restitution= 1.0,friction= 0.7. - Computes
invMass = (mass != 0) ? 1/mass : 0. - Computes moment of inertia
I = shape.GetMomentOfInertia() * mass, andinvI = (I != 0)?1/I:0. - Logs constructor call.
- Clones
-
~Body()- Deletes
shape. - Destroys
texturevia SDL. - Logs destructor call.
- Deletes
Methods
-
bool IsStatic() const
Returns true ifinvMassis near zero. -
void AddForce(const Vec2& force)
Accumulates an external force insumForces. -
void AddTorque(float torque)
AccumulatestorqueinsumTorque. -
void ClearForces()/void ClearTorque()
ResetssumForcesto (0,0) /sumTorqueto 0. -
void ApplyImpulse(const Vec2& j)
If not static, changesvelocitybyj * invMass. -
void ApplyImpulse(const Vec2& j, const Vec2& r)
If not static, changesvelocitybyj * invMassandangularVelocitybyr.Cross(j) * invI. -
void SetTexture(const char* textureFileName)
UsesSDL_imageto load a texture. Logs an error if it fails. -
void IntegrateLinear(float dt)- If the body is not static, updates
acceleration = sumForces * invMass, thenvelocity += acceleration * dt, thenposition += velocity * dt, then clears forces.
- If the body is not static, updates
-
void IntegrateAngular(float dt)- If not static, computes
angularAcceleration = sumTorque * invI, updatesangularVelocity += angularAcceleration * dt, thenrotation += angularVelocity * dt, then clears torque.
- If not static, computes
-
void Update(float dt)- Calls
IntegrateLinear(dt),IntegrateAngular(dt), and updatesshape->UpdateVertices(rotation, position).
- Calls
4. Collision Handling – CollisionDetection and Contact
4.1 CollisionDetection
Files:
CollisionDetection.hCollisionDetection.cpp
Methods
-
static bool IsColliding(Body* a, Body* b, Contact& contact)
Detects shape types and dispatches to appropriate collision function:- circle–circle
- polygon–polygon (including box–box, box–polygon)
- polygon–circle
-
static bool IsCollidingCircleCircle(Body* a, Body* b, Contact& contact)
Checks distance between centers vs. sum of radii. If colliding, sets upcontact.normal,contact.start/endnear circle perimeters, andcontact.depth. -
static bool IsCollidingPolygonPolygon(Body* a, Body* b, Contact& contact)
Uses each polygon’sFindMinSeparationmethod. If either separation is >= 0, no collision. Else, picks whichever side has the greatest overlap for contact data. -
static bool IsCollidingPolygonCircle(Body* polygon, Body* circle, Contact& contact)
Tests edges to see if circle center is outside or inside. Computes collision region (A/B/C). Setscontactwith depth and normal if colliding.
4.2 Contact
Files:
Contact.hContact.cpp
Data Members
Body* a, *bVec2 start, endVec2 normalfloat depth
Methods
-
void ResolvePenetration()- If both
aandbare static, does nothing. - Calculates displacements
da,dbbased on combined inverse mass andcontact.depth. - Adjusts
a->positionandb->positionalongcontact.normalbyda * 0.8anddb * 0.8. - Updates shape vertices accordingly.
- If both
-
void ResolveCollision()- Calls
ResolvePenetration(). - Determines elasticity
e = min(a->restitution, b->restitution)and frictionf = min(a->friction, b->friction). - Computes relative velocity at contact points, calculates normal impulse, then friction impulse, applies them to
aandb.
- Calls
5. Constants (Constants.h)
File:
Constants.h
Defines:
FPS= 60MILLISECS_PER_FRAME= 1000 / FPSPIXELS_PER_METER= 50
Used for frame timing and scaling between meters and pixels.
6. Force Generators – Force
Files:
Force.hForce.cpp
Methods
-
Vec2 GenerateDragForce(const Body& body, float k)
If velocity is nonzero, returns a force opposite to velocity direction, magnitude proportional to|velocity|^2 * k. -
Vec2 GenerateFrictionForce(const Body& body, float k)
Returns a constant-magnitude forcek, opposite to body’s velocity direction. -
Vec2 GenerateSpringForce(const Body& body, const Vec2& anchor, float restLength, float k)
Calculates displacement frombody.positiontoanchor, then magnitudek * (distance - restLength), directed back toward anchor. -
Vec2 GenerateSpringForce(const Body& a, const Body& b, float restLength, float k)
Similar, but uses positions of two bodies as endpoints. -
Vec2 GenerateGravitationalForce(const Body& a, const Body& b, float G, float minDistance, float maxDistance)
Clamps distance-squared betweenminDistanceandmaxDistance. Direction is fromatob. Magnitude isG*(a.mass*b.mass)/(distance^2).
7. World Management – World
Files:
World.hWorld.cpp
Data Members
float Gstd::vector<Body*> bodiesstd::vector<Vec2> forcesstd::vector<float> torques
Constructor / Destructor
World(float gravity)- Sets
G = -gravity(expect negative input to produce a downward force). - Logs creation.
- Sets
~World()- Deletes all
Body*inbodies. - Logs destruction.
- Deletes all
Methods
-
void AddBody(Body* body)
Appends tobodies. -
std::vector<Body*>& GetBodies()
Returns reference tobodies. -
void AddForce(const Vec2& force)
Appendsforceto a list of global forces. -
void AddTorque(float torque)
Appends global torque to a list. -
void Update(float dt)- For each
Body*inbodies, apply gravity asVec2(0, mass * G * PIXELS_PER_METER). - Apply any global forces/torques from
forces/torques. - Call
body->Update(dt)for each. - Perform multiple passes of collision detection/resolution (calls
CheckCollisions()up to 10 times).
- For each
-
void CheckCollisions()
Double loop overbodies. For each pair(i, j), resetsa->isColliding = falseandb->isColliding = false. IfCollisionDetection::IsColliding(...), obtains aContactand callscontact.ResolveCollision().
8. Graphics and Rendering – Graphics
Files:
Graphics.hGraphics.cpp
Data Members
static int windowWidth, windowHeightstatic SDL_Window* windowstatic SDL_Renderer* renderer
Methods
-
static bool OpenWindow()
Initializes SDL, uses full-screen borderless mode, sets uprenderer. Returns false on error. -
static void CloseWindow()
Destroys therendererandwindow, callsSDL_Quit(). -
static int Width(), static int Height()
ReturnwindowWidthandwindowHeight. -
static void ClearScreen(Uint32 color)
Sets draw color and clears the current rendering target. -
static void RenderFrame()
Presents the current frame (SDL double-buffer swap). -
static void DrawLine(int x0, int y0, int x1, int y1, Uint32 color)
Draws a line using SDL2_gfx’slineColor. -
static void DrawCircle(int x, int y, int radius, float angle, Uint32 color)
Renders a circle, plus a line from center in the directionangle. -
static void DrawFillCircle(int x, int y, int radius, Uint32 color)
Renders a filled circle. -
static void DrawRect(int x, int y, int width, int height, Uint32 color)
Renders an unfilled rectangle, using lines. -
static void DrawFillRect(int x, int y, int width, int height, Uint32 color)
Renders a filled rectangle. -
static void DrawPolygon(int x, int y, const std::vector<Vec2>& vertices, Uint32 color)
Connects consecutive vertices with lines, plus a filled circle at(x, y). -
static void DrawFillPolygon(int x, int y, const std::vector<Vec2>& vertices, Uint32 color)
UsesfilledPolygonColorfrom SDL2_gfx. Draws a 1-pixel circle at(x, y)in a darker color. -
static void DrawTexture(int x, int y, int width, int height, float rotation, SDL_Texture* texture)
Copies an SDL_Texture to the renderer, applying rotation (converted to degrees).
9. Application Control – Application
Files:
Application.hApplication.cpp
Data Members
bool debugbool runningWorld* world
Methods
-
bool IsRunning()
Returnsrunning. -
void Setup()- Calls
Graphics::OpenWindow(), assigns result torunning. - Creates
world = new World(-9.8). - Adds floor, walls, a large static box to the world.
- Applies a wind force as a global force.
- Calls
-
void Input()
Polls SDL events.- On
SDL_QUIT, setsrunning = false. - On
SDL_KEYDOWNwithEscape, setsrunning = false, or togglesdebugwithd. - On
SDL_MOUSEBUTTONDOWN, depending on button (left/right/middle), spawns a circle or box body with different textures (basketball, crate, bowling ball).
- On
-
void Update()- Clears the screen with a background color.
- Manages frame timing to target
MILLISECS_PER_FRAME. - Computes
deltaTime. - Calls
world->Update(deltaTime)to step physics.
-
void Render()- Loops over
world->GetBodies(). - Checks shape type. If
debugis false andtextureexists, draws texture; otherwise, draws wireframe or polygon fill. - Calls
Graphics::RenderFrame()at the end.
- Loops over
-
void Destroy()
Deletesworldand closes the SDL window.
10. Main Entry Point – Main.cpp
File:
Main.cpp
Overview
int main(int argc, char* args[]) {
Application app;
app.Setup();
while (app.IsRunning()) {
app.Input();
app.Update();
app.Render();
}
app.Destroy();
return 0;
}