add a safety check for box2d

This commit is contained in:
blueloveTH 2023-11-11 02:51:10 +08:00
parent 5e54967903
commit c2f13e4f03
3 changed files with 19 additions and 10 deletions

View File

@ -67,11 +67,11 @@ struct PyBody{
PK_ALWAYS_PASS_BY_POINTER(PyBody)
b2Body* body;
b2Fixture* fixture;
b2Fixture* _fixture;
PyObject* node_like;
bool _is_destroyed;
PyBody(): body(nullptr), fixture(nullptr), node_like(nullptr), _is_destroyed(false){}
PyBody(): body(nullptr), _fixture(nullptr), node_like(nullptr), _is_destroyed(false){}
void _gc_mark() {
if(node_like != nullptr){
@ -81,7 +81,18 @@ struct PyBody{
PyBody* _() { return this; }
b2Body* _b2Body() { return body; }
b2Fixture* _b2Fixture() { return fixture; }
b2Fixture* _b2Fixture() {
if(_fixture == nullptr) throw std::runtime_error("`_fixture == nullptr` in PyBody::_b2Fixture()");
return _fixture;
}
void _set_b2Fixture(b2Fixture* fixture){
if(_fixture != nullptr){
body->DestroyFixture(_fixture);
}
_fixture = fixture;
}
static void _register(VM* vm, PyObject* mod, PyObject* type);

View File

@ -14,9 +14,7 @@ void PyBody::_register(VM* vm, PyObject* mod, PyObject* type){
// a weak reference to this object
def.userData.pointer = reinterpret_cast<uintptr_t>(obj);
body.body = world.world.CreateBody(&def);
body.fixture = nullptr;
body.node_like = node;
body._is_destroyed = false;
return obj;
});
@ -49,7 +47,7 @@ void PyBody::_register(VM* vm, PyObject* mod, PyObject* type){
float hy = CAST(float, args[2]);
b2PolygonShape shape;
shape.SetAsBox(hx, hy);
body.fixture = body.body->CreateFixture(&shape, 1.0f);
body._set_b2Fixture(body.body->CreateFixture(&shape, 1.0f));
return vm->None;
});
@ -59,7 +57,7 @@ void PyBody::_register(VM* vm, PyObject* mod, PyObject* type){
float radius = CAST(float, args[1]);
b2CircleShape shape;
shape.m_radius = radius;
body.fixture = body.body->CreateFixture(&shape, 1.0f);
body._set_b2Fixture(body.body->CreateFixture(&shape, 1.0f));
return vm->None;
});
@ -77,7 +75,7 @@ void PyBody::_register(VM* vm, PyObject* mod, PyObject* type){
vertices.push_back(b2Vec2(vec.x, vec.y));
}
shape.Set(vertices.data(), vertices.size());
body.fixture = body.body->CreateFixture(&shape, 1.0f);
body._set_b2Fixture(body.body->CreateFixture(&shape, 1.0f));
return vm->None;
});
@ -95,7 +93,7 @@ void PyBody::_register(VM* vm, PyObject* mod, PyObject* type){
vertices.push_back(b2Vec2(vec.x, vec.y));
}
shape.CreateLoop(vertices.data(), vertices.size());
body.fixture = body.body->CreateFixture(&shape, 1.0f);
body._set_b2Fixture(body.body->CreateFixture(&shape, 1.0f));
return vm->None;
});

View File

@ -135,7 +135,7 @@ void PyWorld::_register(VM* vm, PyObject* mod, PyObject* type){
if(body._is_destroyed){
body.body->GetWorld()->DestroyBody(body.body);
body.body = nullptr;
body.fixture = nullptr;
body._fixture = nullptr;
body.node_like = nullptr;
}
p = next;