Box2D is a 2D physics engine for games

Related tags

Game box2d
Overview

Box2D Logo

Build Status

Build Status

Box2D

Box2D is a 2D physics engine for games.

Contributing

Please do not submit pull requests with new features or core library changes. Instead, please file an issue first for discussion. For bugs, I prefer detailed bug reports over pull requests.

Features

Collision

  • Continuous collision detection
  • Contact callbacks: begin, end, pre-solve, post-solve
  • Convex polygons and circles
  • Multiple shapes per body
  • One-shot contact manifolds
  • Dynamic tree broadphase
  • Efficient pair management
  • Fast broadphase AABB queries
  • Collision groups and categories

Physics

  • Continuous physics with time of impact solver
  • Persistent body-joint-contact graph
  • Island solution and sleep management
  • Contact, friction, and restitution
  • Stable stacking with a linear-time solver
  • Revolute, prismatic, distance, pulley, gear, mouse joint, and other joint types
  • Joint limits, motors, and friction
  • Momentum decoupled position correction
  • Fairly accurate reaction forces/impulses

System

  • Small block and stack allocators
  • Centralized tuning parameters
  • Highly portable C++ with no use of STL containers

Testbed

  • OpenGL with GLFW
  • Graphical user interface with imgui
  • Extensible test framework
  • Support for loading world dumps

Building

  • Install CMake
  • Ensure CMake is in the user PATH
  • Visual Studio: run build.bat from the command prompt
  • Otherwise: run build.sh from a bash shell
  • Results are in the build sub-folder
  • On Windows you can open box2d.sln

Building Box2D - Using vcpkg

You can download and install Box2D using the vcpkg dependency manager:

The Box2D port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please create an issue or pull request on the vcpkg repository.

Note: vcpkg support is not provided by the Box2D project

Building for Xcode

  • Install CMake
  • Add Cmake to the path in .zprofile (the default Terminal shell is zsh)
    • export PATH="/Applications/CMake.app/Contents/bin:$PATH"
  • mkdir build
  • cd build
  • cmake -G Xcode ..
  • open box2d.xcodeproj
  • Select the testbed scheme
  • Edit the scheme to set a custom working directory, make this be in box2d/testbed
  • You can now build and run the testbed

Installing using CMake

You can build and install the library and docs using this command sequence (requires Doxygen):

mkdir build
cd build
cmake -DBOX2D_BUILD_DOCS=ON ..
cmake --build .
cmake --build . --target INSTALL

On Windows this tries to install in Program Files and thus requires admin privileges. Alternatively you can target another directory using something like this:

mkdir build
cd build
cmake -DBOX2D_BUILD_DOCS=ON -DCMAKE_INSTALL_PREFIX="C:/packages" ..
cmake --build .
cmake --build . --target INSTALL

Documentation

License

Box2D is developed by Erin Catto, and uses the MIT license.

Sponsorship

Support development of Box2D through Github Sponsors

Comments
  • Major random bug causes the engine to quickly go on a downward spiral until it crashes

    Major random bug causes the engine to quickly go on a downward spiral until it crashes

    I'm using Box2d through the gdx-box2d java library, which makes use of the c code through JNI. I've used it without problems in my other games, serverside as they are multiplayer MMO games, but on my newest game, after a random amount of time (usually 1 or 2 days) it suddendly gets really slow until it crashes.

    The game is this one (you can try it without download)

    After trying to solve it java-side, I decided to start touching the c code, basically adding some printf in world.step and related functions.

    b2World.cpp: https://pastebin.com/d6fn0mLd (I added printfs at the end of step displaying m_profiler times, and at different places in SolveTOI)

    b2BroadPhase.h: https://pastebin.com/WTihivb1 (added prints at updatepairs showing moveCount and pairCount)


    After it crashes, I analyse the log, and this is what I see:

    Everything works right until suddendly it slows down, and the pairCount increases substantially.

    {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{}{K}{E1}{F}{G}{E2} {PR|5.61|1.56|3.11|0.25|0.21|0.16|0.55|1.08} (milliseconds of m_profile.step|collide|solve|solveInit|solveVelocity|solvePosition|solveTOI|broadphase) {94||194}{*} (moveCount||pairCount) {A}{B}{C}{D}{E2} {PR|5.05|0.99|3.60|0.21|0.18|0.20|0.42|1.10} {13||44}{*} {86||115}{*} {A}{B}{C}{D}{E2} {PR|4.71|1.07|2.95|0.19|0.18|0.20|0.40|0.97} {14||46}{*} {87||133}{*} {A}{B}{C}{D}{E2} {PR|5.92|1.17|3.82|0.23|0.24|0.24|0.59|1.31} {110||228}{*} {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{}{K}{E1}{F}{G}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|7.20|1.43|4.75|0.32|0.24|0.27|0.90|2.05} {13||48}{*} {81||115}{*} {A}{B}{C}{D}{E1}{F}{G}{E2} {PR|6.46|1.05|4.34|0.27|0.20|0.25|0.68|1.20} {16||45}{*} {97||123}{*} {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|7.12|1.63|4.48|0.14|0.21|0.15|0.82|1.79} {99||250}{*} {A}{B}{C}{D}{E2} {PR|7.19|1.09|5.29|0.28|0.39|0.23|0.73|1.97} {14||49}{*} {90||104}{*} {A}{B}{C}{D}{E1}{F}{G}{E1}{F}{G}{E2} {PR|5.50|1.55|3.13|0.23|0.16|0.23|0.50|1.02} {96||138}{*} {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|6.18|1.20|4.18|0.25|0.18|0.23|0.73|1.72} {16||48}{*} {95||166}{*} {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|5.97|0.99|4.13|0.19|0.19|0.20|0.54|1.40} (milliseconds of m_profile.step|collide|solve|solveInit|solveVelocity|solvePosition|solveTOI|broadphase) {13||42}{*} {90||24011}{*} (moveCount||pairCount) {A}{B}{C}{D}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E1}{F}{G}{H}{I}{J} {0||0}{*}{K}{E2} {PR|18446744949882880.00|0.97|88.95|0.16|0.24|2.48|18446744949882880.00|84.54} {11||12}{*} {96||24120}{*} {A}{B}{C}{D}{E2} {PR|247.14|16.28|94.44|0.44|0.27|0.21|136.07|90.47} {7||26}{*} {441||951895}

    ...a few seconds...

    {*} {A}{B}{C}{D}

    ...minutes...

    {E2} {PR|18446744949882880.00|7.51|18446744949882880.00|0.38|0.16|0.13|136043.02|18446744949882880.00}

    ...minutes... at this time I see a lot of STUCK at colliding that come from here:

    ` gameServer.getWorld().getBox2dWorld().QueryAABB(

    				new QueryCallback() {
    
    					@Override
    
    					public boolean reportFixture(Fixture fixture) {
    
    						if(tries.incrementAndGet() > 20){
    
    							System.out.println("STUCK AT COLLIDING");
    
    							return false;
    
    						}`
    

    then

    {*} {A}{B}{C}{D}

    ...minutes...

    {E2} {PR|18446744949882880.00|1133.92|18446744949882880.00|290.91|95.83|69.26|185694.27|18446744949882880.00}

    CRASH Sometimes it crashes showing some error at memmove (or something like that) method, and sometimes it doesn't show anything

    A second before that this were the world stats (normal):

    06-21 08:19:34 - 79 persons - 2400 entities - 1 preStep - 2401 bodies - 30 joints - ##### Physics: 6.83 (4.08/5.67/8.7) - Players: 0.08 (0.04/0.1/0.65) - Entities: 2.2 (1.97/2.84/5.7) - AI: 0.09 (0.07/0.13/0.27) - Data: 14.23 (10.79/14.6/22.03) - TOTAL: 8.74/23.34 #####

    Any kind of help, even about where to continue looking for the cause is welcome. I'm hopeless right now, and the game is stuck as I don't want to continue updating or advertising it because it crashes every 1 or 2 days.

    I've already checked if there were any updates on related code in current box2d master that weren't in box2d version, but there aren't.

    Thanks in advance.

    help wanted 
    opened by soylomass 24
  • CMake enhancements

    CMake enhancements

    First of all, thanks for finally providing CMake as the official build 
    system. It makes stuff a lot easier for me. I made a patch to enhance it. 
    Sorry I didn't break the patch down into smaller chunks, it has to be 
    patched in a single go in order to work properly. 
    
    Modications are as follows (relative to trunk/Box2D/):
    1) Testbed/Tests/VerticalStack.h: include stdio.h so that printf is defined
    2) Testbed/CMakeLists.txt: rename freeglut to glut because that is the 
    actual default name of the library
    3) freeglut/CMakeLists.txt: change freeglut to glut in library output name 
    to match with 2)
    4) CMakeLists.txt: add options for shared/static/examples building
    5) CMakeLists.txt: compile freeglut only if on Windows, use system 
    libraries on Linux (no experience with Mac, sorry)
    6) CMakeLists.txt: install documentation
    7) CMakeLists.txt: add VERSION
    8) Box2D/CMakeLists.txt: add support for shared/static building
    9) Box2D/CMakeLists.txt: respect VERSION
    10) Box2D/CMakeLists.txt: make MSVC stuff optional (only if compiler 
    actually is MSVC)
    11) Box2D/CMakeLists.txt: install libraries and headers
    

    Original issue reported on code.google.com by [email protected] on 1 Feb 2010 at 8:02

    Attachments:

    Type-Defect Priority-Medium auto-migrated 
    opened by GoogleCodeExporter 23
  • Shared library

    Shared library

    This pull request add support for building Box2D as a shared library. It fixes #621. By default, the library is built as a static library, you have to add -DBUILD_SHARED_LIBS=ON to the cmake invocation to build the shared library.

    If you merge #630 at the same time, you will have to uncomment some lines in src/CMakeLists.txt so that the library can work properly once installed. Anyway, merging both should result in conflicts. If you plan to merge both, merge #630 first, and I will make the necessary modifications to this PR so that it can be merged smoothly.

    opened by jube 21
  • Body not slowing down with friction for static body (Bug)

    Body not slowing down with friction for static body (Bug)

    It seems like there's a bug in the following set-up, reproducible by with the default settings and Step(1/60f, 8, 8) (not the test-bed settings):

    b2Vec2 gravity;
    gravity.Set(0.0f, -10.0f);
    m_world = new b2World(gravity);
    b2ChainShape chainShape;
    b2Vec2 vertices[] = {b2Vec2(-5,0), b2Vec2(5,0), b2Vec2(5,5), b2Vec2(4,1), b2Vec2(-4,1), b2Vec2(-5,5)};
    chainShape.CreateLoop(vertices, 6);
    
    b2FixtureDef groundFixtureDef;
    groundFixtureDef.density = 0;
    groundFixtureDef.shape = &chainShape;
    
    b2BodyDef groundBodyDef;
    groundBodyDef.type = b2_staticBody;
    
    b2Body *groundBody = m_world->CreateBody(&groundBodyDef);
    b2Fixture *groundBodyFixture = groundBody->CreateFixture(&groundFixtureDef);
    
    b2CircleShape ballShape;
    ballShape.m_radius = 1;
    
    b2FixtureDef ballFixtureDef;
    ballFixtureDef.restitution = 0.75f;
    ballFixtureDef.density = 1;
    ballFixtureDef.shape = &ballShape;
    
    b2BodyDef ballBodyDef;
    ballBodyDef.type = b2BodyType::b2_dynamicBody;
    ballBodyDef.position = b2Vec2(0, 10);
    
    b2Body *ball = m_world->CreateBody(&ballBodyDef);
    b2Fixture *ballFixture = ball->CreateFixture(&ballFixtureDef);
    ball->ApplyForceToCenter(b2Vec2(-1000, -400), true);
    

    As you'll see the ball at the end is meant to stop and in fact, if you choose the ground to be dynamic body instead of static, the ball will stop, but when it's dynamic and the ball is supposed to stop it will pick up speed. Doesn't seem related to the recent changes with density zero improvement. I was able to repro it even in previous commits to that.

    bug 
    opened by grimaldini 16
  • Box2D is dead?

    Box2D is dead?

    From the latest commit (as of 1/26/2016): The main Box2D library is open source, but not open contribution. Please do not submit pull requests. Exceptions may be considered for build files and other items that are not part of the main library source. Thank you for your understanding.

    Does this mean Box2D is dead?

    opened by hcorion 16
  • changes in r186 create problems in b2RevoluteJoints with limits 0,0

    changes in r186 create problems in b2RevoluteJoints with limits 0,0

    What steps will reproduce the problem?
    1. Create a pole made up of rectangles linked by b2Revolute joints with default 
    limits on
    2. Try to bend the pole
    
    What is the expected output? What do you see instead?
    - Expected: pole returns to straight (all joints return to reference angle) 
    after being bent
    - What I see: after large bends, pole returns to original shape ridiculously 
    slowly (like, 10 seconds). 
    
    What version of the product are you using? On what operating system?
    - C++ Box2d 2.2.1 latest
    
    Please provide any additional information below.
    - Have narrowed this down to r186 changes 
    - specifically: in 2.1.2, if I remove the "Handle large detachment" segment 
    from b2RevoluteJoint.cpp, it exactly reproduces the behaviour from 2.2.1
    - I'd suggest that the optimization that involved removing this code from the 
    new version has generated a bug.
    
    

    Original issue reported on code.google.com by [email protected] on 31 May 2013 at 11:13

    Type-Defect Priority-Medium auto-migrated 
    opened by GoogleCodeExporter 16
  • 2.4.1: build fails with BOX2D_BUILD_UNIT_TESTS=ON

    2.4.1: build fails with BOX2D_BUILD_UNIT_TESTS=ON

    [ 33%] Building CXX object unit-test/CMakeFiles/unit_test.dir/hello_world.cpp.o
    cd /home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/x86_64-redhat-linux-gnu/unit-test && /usr/bin/g++ -DB2_SHARED -I/home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/src/../include -O2 -g -grecord-gcc-switches -pipe -Wall -Werror=format-security -Wp,-D_FORTIFY_SOURCE=2 -Wp,-D_GLIBCXX_ASSERTIONS -specs=/usr/lib/rpm/redhat/redhat-hardened-cc1 -fstack-protector-strong -specs=/usr/lib/rpm/redhat/redhat-annobin-cc1 -m64 -mtune=generic -fasynchronous-unwind-tables -fstack-clash-protection -fcf-protection -fdata-sections -ffunction-sections -flto=auto -flto-partition=none -O2 -g -DNDEBUG -fvisibility=hidden -fvisibility-inlines-hidden -std=c++11 -o CMakeFiles/unit_test.dir/hello_world.cpp.o -c /home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/unit-test/hello_world.cpp
    In file included from /home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/unit-test/hello_world.cpp:25:
    /home/tkloczko/rpmbuild/BUILD/box2d-2.4.1/unit-test/doctest.h:4021:47: error: size of array ‘altStackMem’ is not an integral constant-expression
     4021 |         static char             altStackMem[4 * SIGSTKSZ];
          |                                               ^
    
    • [x] Ask for help on discord and/or reddit
    • [x] Consider providing a dump file using b2World::Dump
    opened by kloczek 15
  • Shared libraries?

    Shared libraries?

    Hi! I maintain the Fedora package for Box2D. I'm looking at upgrading from 2.3.1 to 2.4.0, but I can't get the new cmake build system to build shared libraries, only static. Is this by design, or have I missed something? Thank you!

    building 
    opened by limburgher 14
  • How to render an object with render scaling? Thus simulating objects smaller, and rendering them thus bigger?

    How to render an object with render scaling? Thus simulating objects smaller, and rendering them thus bigger?

    Hi,

    So I just got Box2D working, now I have another problem: Currently, I simulate a object by supplying it with pixel sizes, so: Image of 64x64 gets drawn, and the size in Box2D will also be set a 64x64(Meters). This renders fine by getting the position and applying it, but now i want to have a 4x4meter object, render as an 64x64 sprite on the screen. The problem is, that I don't know how I would scale it properly. Can someone explain me how I would properly set the positions of the sprite accordingly to the b2Body positions? The only options my graphics renderer provide are these:

    SetPosition(x,y);
    SetScale(x,y);
    SetAngle(A);
    

    So no vertex modifying and such(may it be nescesery). Can someone teach me how I would probably convert the sizes to achieve what I want?

    Thanks!

    opened by mario-132 14
  • cannot compile in linux

    cannot compile in linux

    even after adding defines for linux in config.h and correcting the path of "glext.h" in "egl_platform.h" i cannot compile this on linux In file included from /home/debajyoti/Downloads/Box2D-master/Box2D/glfw/x11_platform.h:52:0, from /home/debajyoti/Downloads/Box2D-master/Box2D/glfw/internal.h:69, from /home/debajyoti/Downloads/Box2D-master/Box2D/glfw/clipboard.c:27: /home/debajyoti/Downloads/Box2D-master/Box2D/glfw/glx_platform.h:57:3: error: #error "No OpenGL entry point retrieval mechanism was enabled" #error "No OpenGL entry point retrieval mechanism was enabled" ^ make[2]: *** [glfw/CMakeFiles/glfw.dir/clipboard.c.o] Error 1 make[1]: *** [glfw/CMakeFiles/glfw.dir/all] Error 2 make: *** [all] Error 2

    Linux 
    opened by dchatterjee172 14
  • b2Query doesn't always return a valid fixture

    b2Query doesn't always return a valid fixture

    What steps will reproduce the problem?
    --------------------------------------
    
    I have been unable to generate a test that consistently fails. However, for 
    this reason I tend to think the bug is somewhere in the new broadphase balanced 
    tree. I can usually get b2Query to fail if I have 10+ overlapping bodies, and I 
    query a small bounding box at an overlapping location. This does not always 
    fail, and requires multiple test runs, but it will almost definitely fail 1/5 
    times.
    
    What is the expected output? What do you see instead?
    -----------------------------------------------------
    
    I expect Box2D to always report a valid pointer to 
    b2QueryCallback->ReportFixture(proxy->fixture). Instead, occasionally I get an 
    invalid pointer such as 0xdfdfdfdf.
    
    What version of the product are you using? On what operating system?
    I am using the very latest google code version, however, this seems to have 
    been an issue since I updated the new balanced tree code.
    
    Please provide any additional information below.
    ------------------------------------------------
    
    The attached patch to b2World.cpp fixes this bug, but I consider it a hack 
    workaround. Perhaps it can give more insight. Platforms I have tested this 
    error and solution on include Win32 with the microsoft compiler and G++, and 
    ARM cross-compile with G++. I feel the root cause is deeper than this function, 
    and I am only patching a problem produced by broadphase. I'm coding Box2D every 
    day if you have any questions, I'm available within 12 hours.
    
    
    

    Original issue reported on code.google.com by [email protected] on 29 Aug 2011 at 2:57

    Attachments:

    Type-Defect Priority-Medium auto-migrated 
    opened by GoogleCodeExporter 14
  • Warmstart GJK fails

    Warmstart GJK fails

    Make sure these boxes are checked before submitting your issue - thank you!

    • [ ] Ask for help on discord and/or reddit
    • [ ] Consider providing a dump file using b2World::Dump
    opened by NStenum 1
  • Read/Write dependencies on constraints in contact solvers impacting out of order processors

    Read/Write dependencies on constraints in contact solvers impacting out of order processors

    The contact solver creates constraints between Object A and Object B. When processing these we read values from A and B, and write results to A/B. However, constraints can be created such that the continuous orders have a shared object with the previous constraints that were just processed.

    On an out of order processor like Apple silicon, this creates a read after write dependency that forces all constraints to be processed serially, even if other constraints related to other objects could be processed in parallel. If we randomize the order of constraints after they are generated (or the order which the contacts are processed when generating the constraints) it reduces the chances of two continuous constraints array elements being processed by a shared object. As a result we could see a performance improvement of more than 25% in several cases.

    We are opening an issue to discuss this topic further per the readme!

    opened by Developer-Ecosystem-Engineering 5
  • DrawSegment is not called

    DrawSegment is not called

    I already have created three simple examples in: Qt6, PyQt6, and SDL2. I thought that a problem in Qt6 but it the same for three cases. It looks like a bug. These examples try to print hello in the console from DrawSegment().

    I expect to see hello in the console:

    DebugDrawer.cpp

    #include "DebugDrawer.h"
    #include <iostream>
    
    DebugDrawer::DebugDrawer()
    {
    
    }
    
    void DebugDrawer::DrawSegment(const b2Vec2 &p1, const b2Vec2 &p2, const b2Color &color)
    {
        std::cout << "hello" << std::endl;
    }
    
    void DebugDrawer::DrawSolidPolygon(const b2Vec2 *vertices, int32 vertexCount, const b2Color &color) { }
    void DebugDrawer::DrawPolygon(const b2Vec2 *vertices, int32 vertexCount, const b2Color &color) { }
    void DebugDrawer::DrawPoint(const b2Vec2 &p, float size, const b2Color &color) { }
    void DebugDrawer::DrawCircle(const b2Vec2 &center, float radius, const b2Color &color) { }
    void DebugDrawer::DrawSolidCircle(const b2Vec2 &center, float radius, const b2Vec2 &axis, const b2Color &color) { }
    void DebugDrawer::DrawTransform(const b2Transform &xf) { }
    

    I inherited from the b2Draw and overloaded the methods:

    DebugDrawer.h

    #ifndef DEBUGDRAWER_H
    #define DEBUGDRAWER_H
    
    #include "box2d/b2_draw.h"
    
    class DebugDrawer : public b2Draw
    {
    public:
        DebugDrawer();
    
    private:
        void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
        void DrawPoint (const b2Vec2 &p, float size, const b2Color &color);
        void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
        void DrawCircle(const b2Vec2& center, float radius, const b2Color& color);
        void DrawSolidCircle(const b2Vec2& center, float radius, const b2Vec2& axis, const b2Color& color);
        void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
        void DrawTransform(const b2Transform& xf);
    };
    
    #endif // DEBUGDRAWER_H
    

    I created an object with the box shape:

        b2PolygonShape shape;
        shape.SetAsBox(50.f / WORLD_SCALE, 50.f / WORLD_SCALE);
    
        b2BodyDef bdef;
        bdef.type = b2_staticBody;
    
        pBody = pWorld->CreateBody(&bdef);
        pBody->CreateFixture(&shape, 2.f);
    

    I set the debug draw in the main.cpp file:

        pDebugDrawer = new DebugDrawer();
        pWorld->SetDebugDraw(pDebugDrawer);
    

    I set flags:

       uint32 flags = 0;
        flags += b2Draw::e_shapeBit;
        flags += b2Draw::e_jointBit;
        flags += b2Draw::e_centerOfMassBit;
        flags += b2Draw::e_aabbBit;
        flags += b2Draw::e_pairBit;
        pDebugDrawer->SetFlags(flags);
    

    I call pWorld.Step() and pWorld->DebugDraw():

            pWorld->Step(0.016f, 8, 3);
            pWorld->DebugDraw();
    

    main.cpp

    #ifdef _WIN32
    #include <windows.h>
    extern "C" __declspec(dllexport) DWORD NvOptimusEnablement = 0x00000001;
    extern "C" __declspec(dllexport) DWORD AmdPowerXpressRequestHighPerformance = 0x00000001;
    #endif
    
    #define SDL_MAIN_HANDLED
    
    #include <glad/glad.h>
    #include <SDL.h>
    #include <box2d/box2d.h>
    #include <iostream>
    #include "DebugDrawer.h"
    
    const float WORLD_SCALE = 30.f;
    b2World* pWorld;
    DebugDrawer* pDebugDrawer;
    b2Body* pBody;
    
    int main()
    {
        // Initialize the SDL2 library
        if (SDL_Init(SDL_INIT_VIDEO) != 0)
        {
            SDL_Log("Failed to initialize the SDL2 library: %s", SDL_GetError());
            return 1;
        }
    
        // Create a SDL window
        const int WIN_WIDTH = 500;
        const int WIN_HEIGHT = 500;
        SDL_Window* window = SDL_CreateWindow(
            "Empty Window",
            SDL_WINDOWPOS_CENTERED,
            SDL_WINDOWPOS_CENTERED,
            WIN_WIDTH, WIN_HEIGHT,
            SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
    
        // Create a SDL renderer
        SDL_Renderer* renderer = SDL_CreateRenderer(
            window, -1, SDL_RENDERER_ACCELERATED);
        if (!renderer)
        {
            SDL_Log("Failed to create a SDL renderer %s", SDL_GetError());
            return 1;
        }
    
        SDL_GLContext context = SDL_GL_CreateContext(window);
    
        // Initialize the GLAD library
        if (!gladLoadGL())
        {
            SDL_Log("Failed to initialize the GLAD library");
            return 1;
        }
    
        glViewport(0, 0, WIN_WIDTH, WIN_HEIGHT);
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
    
        b2Vec2 gravity(0.f, 9.8f);
        pWorld = new b2World(gravity);
    
        pDebugDrawer = new DebugDrawer();
        pWorld->SetDebugDraw(pDebugDrawer);
    
        uint32 flags = 0;
        flags += b2Draw::e_shapeBit;
        flags += b2Draw::e_jointBit;
        flags += b2Draw::e_centerOfMassBit;
        flags += b2Draw::e_aabbBit;
        flags += b2Draw::e_pairBit;
        pDebugDrawer->SetFlags(flags);
    
        b2PolygonShape shape;
        shape.SetAsBox(50.f / WORLD_SCALE, 50.f / WORLD_SCALE);
    
        b2BodyDef bdef;
        bdef.type = b2_staticBody;
    
        pBody = pWorld->CreateBody(&bdef);
        pBody->CreateFixture(&shape, 2.f);
    
        SDL_Event event;
        bool running = true;
        SDL_PollEvent(&event);
    
        while (running)
        {
            switch (event.type)
            {
            case SDL_QUIT:
                running = false;
                break;
            case SDL_KEYDOWN:
                switch (event.key.keysym.sym)
                {
                case SDLK_ESCAPE:
                    running = false;
                    break;
                }
                break;
            }
    
            glClear(GL_COLOR_BUFFER_BIT);
    
            pWorld->Step(0.016f, 8, 3);
            pWorld->DebugDraw();
    
            SDL_GL_SwapWindow(window);
            SDL_PollEvent(&event);
        }
    
        delete pWorld;
        delete pDebugDrawer;
    
        SDL_GL_DeleteContext(context);
        SDL_DestroyRenderer(renderer);
        SDL_DestroyWindow(window);
        SDL_Quit();
        return 0;
    }
    
    opened by 8Observer8 3
  • Corner Collision

    Corner Collision

    The slop level should not prevent re-entry on corners.

    https://user-images.githubusercontent.com/7284063/175177111-bc7c7fe4-08b6-45b6-86ba-ab66e55c5030.mp4

    opened by erincatto 0
  • Question about islands

    Question about islands

    When building islands, a graph is created where the vertices are bodies. There is an edge between the bodies if there is a contact or a joint between them. As a result, we get several graphs that are added to the island one by one and island.Solve() is executed for them.

    Question: Can I add graphs not one by one, but all at once for the islands that are used in b2World::Solve? Will the behavior of the bodies change after that?

    Why I think so: As I understand it, only contacts and joints with this body can change the position and speed for it. This can be done only by those bodies that are with him in the same graph. This means that bodies from another graph do not affect it. So nothing should change if I add all the graph at once. I don't worry about additional memoty allocation when expanding the islands.

    Thank you.

    opened by chanscredi 0
Releases(v2.4.1)
  • v2.4.1(Oct 18, 2020)

    Changes for version 2.4.1

    API Changes

    • Extended distance joint to have a minimum and maximum limit.
    • Removed rope joint. Use the distance joint instead.
    • B2_USER_SETTINGS and b2_user_settings.h can control user data, length units, and maximum polygon vertices.
    • Default user data is now uintptr_t instead of void*
    • b2FixtureDef::restitutionThreshold lets you set the restitution velocity threshold per fixture.

    BREAKING Changes

    • BREAKING: distance joint 0 stiffness now means the spring is turned off rather than making the joint rigid.
    • BREAKING: distance joint minimum and maximum must be set correctly to get old behavior.

    Infrastructure

    • Library installation function available in CMake.
    • Shared library (DLL) option available.
    • Bug fixes
    Source code(tar.gz)
    Source code(zip)
  • v2.4.0(Jul 27, 2020)

    Changes for version 2.4.0

    Infrastructure

    • Documentation in Doxygen format
    • CMake build system
    • Unit test support
    • Continuous integration testing using Travis CI
    • Limited use of C++11 (nullptr and override)
    • Restructured folders and renamed files to better match open-source standards
    • MIT License
    • Removed float32 and float64
    • Linked the Box2D project to GitHub Sponsors

    Collision

    • Chain and edge shape must now be one-sided to eliminate ghost collisions
    • Broad-phase optimizations
    • Added b2ShapeCast for linear shape casting

    Dynamics

    • Joint limits are now predictive and not stateful
    • Experimental 2D cloth (rope)
    • b2Body::SetActive -> b2Body::SetEnabled
    • Better support for running multiple worlds
    • Handle zero density better
      • The body behaves like a static body
      • The body is drawn with a red color
    • Added translation limit to wheel joint
    • World dump now writes to box2d_dump.inl
    • Static bodies are never awake
    • All joints with spring-dampers now use stiffness and damping
    • Added utility functions to convert frequency and damping ratio to stiffness and damping

    Testbed

    • Testbed uses dear imgui
    • glad OpenGL loader
    • OpenGL 3.3 required
    Source code(tar.gz)
    Source code(zip)
A multi core friendly rigid body physics and collision detection library suitable for games and VR applications.

Jolt Physics Library A multi core friendly rigid body physics and collision detection library suitable for games and VR applications. A YouTube video

null 2.5k Dec 31, 2022
This repository is about a school project about games with physics, written in C++.

Eight Ball Pool ?? A game about playing physics-based eight ball pool. ?? Table of Contents About Getting Started Usage Built Using About the creators

Valeri Ivanov 17 Sep 3, 2022
Godot bindings for the Rapier3D physics engine

Godot bindings for the Rapier3D physics library How to use There are two parts: A Godot module which must be compiled with the engine.

David Hoppenbrouwers 28 Dec 26, 2022
SKR_Physics is a lightweight and easy to use 2D physics engine which is written in C++.

SKR_Physics SKR_Physics is a lightweight and easy to use 2D physics engine which is written in C++. Features Rectangle based collision system Very sim

Şükrü 0 Mar 8, 2022
Sequential impulses physics engine made for learning purposes

A 3D physics engine that uses Separating Axis Test for collision detection, the clipping method for generating contact manifold, contact point reducti

Ahmad Saleh 1 Nov 24, 2021
This is a list of different open-source video games and commercial video games open-source remakes.

This is a list of different open-source video games and commercial video games open-source remakes.

Ivan Bobev 173 Jan 2, 2023
Open-source, cross-platform, C++ game engine for creating 2D/3D games.

GamePlay v3.0.0 GamePlay is an open-source, cross-platform, C++ game framework/engine for creating 2D/3D mobile and desktop games. Website Wiki API De

gameplay3d 3.9k Jan 8, 2023
Game engine behind Sea Dogs, Pirates of the Caribbean and Age of Pirates games.

Game engine behind Sea Dogs, Pirates of the Caribbean and Age of Pirates games.

Storm Devs 693 Dec 29, 2022
OGRE is a scene-oriented, flexible 3D engine written in C++ designed to make it easier and more intuitive for developers to produce games and demos utilising 3D hardware.

OGRE (Object-Oriented Graphics Rendering Engine) is a scene-oriented, flexible 3D engine written in C++ designed to make it easier and more intuitive for developers to produce games and demos utilising 3D hardware. The class library abstracts all the details of using the underlying system libraries like Direct3D and OpenGL and provides an interface based on world objects and other intuitive classes.

null 3.1k Jan 3, 2023
Project DELTA - An open-source trainer built on the Void Engine for Toby Fox's games and their spin-offs.

Project DELTA v3 Project DELTA - An open-source, modular mod menu for Toby Fox's games and their spin-offs. Important note to Grossley: Yes, it is out

Archie 8 Oct 15, 2022
Speedrun plugin for Source engine games.

Features Automatic demo recording Accurate session timing Speedrun timer with complex custom rule system Tools for segmented and tool-assisted speedru

Portal 2 Speedrunning 65 Jan 6, 2023
TrenchBroom is a modern cross-platform level editor for Quake-engine based games.

TrenchBroom is a modern cross-platform level editor for Quake-engine based games.

TrenchBroom 1.3k Jan 8, 2023
An Unreal Engine 4 silent aim method, not usable on all games. Tested on Fortnite, Rogue Company, Bloodhunt, and Splitgate.

UE4-Silent-Aim An Unreal Engine 4 silent aim method, not usable on all games. Only tested on Fortnite, Rogue Company, Bloodhunt, and Splitgate. Done t

null 50 Dec 25, 2022
Engine being created for homeworks in UPC Master's Degree in Advanced Programming for AAA Video Games.

Strawhat Engine Strawhat Engine is a game engine under construction that has model loading and camera movement features along with an editor. Reposito

I. Baran Surucu 12 May 18, 2022
This is netvars, interfaces and class ids dump from Valve's Source2 Engine games

About this This is netvars, interfaces and class ids dump from Valve's Source2 Engine games: Artifact Classic Artifact Foundry Dota 2 Dota Underlords

Dmitry 11 Nov 20, 2022
Unreal Engine 4 plugin for Yodo1 MAS (Managed Ad Services) integration. Used for ad monetization of games.

Unofficial Yodo MAS SDK for Unreal Engine 4 Disclaimer: this plugin is in no way associated with Yodo1, this is just a wrapper on top of their officia

Nineva Studios 3 Apr 9, 2022
C++ library for multi-physics simulation

Project Chrono represents a community effort aimed at producing a physics-based modelling and simulation infrastructure based on a platform-independent, open-source design.

null 1.6k Dec 29, 2022
A game with basic physics and platforming.

Physgun A simple game with basic physics and platforming. Planned features Work in progress: Physics engine. Swept AABB collision algorithm. Elastic a

Bad Games Studio 24 Dec 17, 2021
Source code for Game Physics Cookbook

Game Physics Cookbook Website Facebook Twitter This book is a comprehensive guide to the linear algebra and collision detection games commonly use, bu

Gabor Szauer 647 Dec 30, 2022