载入中...
搜索中...
未找到
Body.cpp
浏览该文件的文档.
1#include "physics/Body.h"
2#include "physics/Fixture.h"
3#include "physics/Joint2D.h"
4#include "physics/World.h"
5
6#include "common/Exception.h"
7
8#include <Box2D/Box2D.h>
9
10#include <cmath>
11#include <cstring>
12#include <vector>
13
14namespace eve::physics {
15namespace {
16
17b2BodyType parseBodyType(const std::string &type) {
18 if (type == "static") return b2_staticBody;
19 if (type == "kinematic") return b2_kinematicBody;
20 if (type == "dynamic") return b2_dynamicBody;
21 throw eve::Exception("Body.setType: unknown body type '%s'", type.c_str());
22}
23
24const char *bodyTypeName(b2BodyType t) {
25 switch (t) {
26 case b2_staticBody: return "static";
27 case b2_kinematicBody: return "kinematic";
28 case b2_dynamicBody: return "dynamic";
29 default: return "static";
30 }
31}
32
33} // namespace
34
35Body::Body(World *world, b2Body *body, int id, PhysicsBodyHandle runtimeHandle)
36 : world_(world), body_(body), id_(id), runtimeHandle_(runtimeHandle) {}
37
39 if (body_ && world_ && world_->raw()) {
40 std::vector<Joint2D *> joints(world_->joints_.begin(), world_->joints_.end());
41 for (Joint2D *joint : joints) {
42 if (joint && joint->isValid() && (joint->getBodyAId() == getId() || joint->getBodyBId() == getId()))
43 joint->destroy();
44 }
45 // Invalidate fixture wrappers before DestroyBody frees b2Fixtures.
46 b2Fixture *f = body_->GetFixtureList();
47 while (f) {
48 b2Fixture *next = f->GetNext();
49 auto *wrap = static_cast<Fixture *>(f->GetUserData());
50 if (wrap) {
51 world_->forgetFixture(wrap);
52 wrap->invalidate();
53 }
54 f = next;
55 }
56 body_->SetUserData(nullptr);
57 world_->releaseBodyJoints2D(*this);
58 world_->raw()->DestroyBody(body_);
59 world_->forgetBody(this);
60 }
61 body_ = nullptr;
62 world_ = nullptr;
63 runtimeHandle_ = PhysicsBodyHandle::invalid();
64}
65
67 if (body_) body_->SetUserData(nullptr);
68 body_ = nullptr;
69 world_ = nullptr;
70 runtimeHandle_ = PhysicsBodyHandle::invalid();
71}
72
74 if (!body_ || !world_ || !world_->raw()) {
75 invalidate();
76 return;
77 }
78 std::vector<Joint2D *> joints(world_->joints_.begin(), world_->joints_.end());
79 for (Joint2D *joint : joints) {
80 if (joint && joint->isValid() && (joint->getBodyAId() == getId() || joint->getBodyBId() == getId()))
81 joint->destroy();
82 }
83 b2Fixture *f = body_->GetFixtureList();
84 while (f) {
85 b2Fixture *next = f->GetNext();
86 auto *wrap = static_cast<Fixture *>(f->GetUserData());
87 if (wrap) {
88 world_->forgetFixture(wrap);
89 wrap->invalidate();
90 }
91 f = next;
92 }
93 body_->SetUserData(nullptr);
94 world_->releaseBodyJoints2D(*this);
95 world_->raw()->DestroyBody(body_);
96 world_->forgetBody(this);
97 body_ = nullptr;
98 world_ = nullptr;
99 runtimeHandle_ = PhysicsBodyHandle::invalid();
100}
101
102void Body::setPosition(float x, float y) {
103 if (!body_ || !world_) return;
104 body_->SetTransform(b2Vec2(world_->toMeters(x), world_->toMeters(y)), body_->GetAngle());
105}
106
107float Body::getX() const {
108 if (!body_ || !world_) return 0.f;
109 return world_->toPixels(body_->GetPosition().x);
110}
111
112float Body::getY() const {
113 if (!body_ || !world_) return 0.f;
114 return world_->toPixels(body_->GetPosition().y);
115}
116
117void Body::setAngle(float radians) {
118 if (!body_) return;
119 body_->SetTransform(body_->GetPosition(), radians);
120}
121
122float Body::getAngle() const {
123 if (!body_) return 0.f;
124 return body_->GetAngle();
125}
126
127void Body::setLinearVelocity(float vx, float vy) {
128 if (!body_ || !world_) return;
129 body_->SetLinearVelocity(b2Vec2(world_->toMeters(vx), world_->toMeters(vy)));
130}
131
133 if (!body_ || !world_) return 0.f;
134 return world_->toPixels(body_->GetLinearVelocity().x);
135}
136
138 if (!body_ || !world_) return 0.f;
139 return world_->toPixels(body_->GetLinearVelocity().y);
140}
141
142float Body::getLinearSpeed() const {
143 if (!body_ || !world_) return 0.f;
144 return world_->toPixels(body_->GetLinearVelocity().Length());
145}
146
147float Body::getMass() const { return body_ ? body_->GetMass() : 0.f; }
148
150 if (!body_ || !world_) return 0.f;
151 return world_->toPixels(body_->GetWorldCenter().x);
152}
153
155 if (!body_ || !world_) return 0.f;
156 return world_->toPixels(body_->GetWorldCenter().y);
157}
158
159void Body::setAngularVelocity(float omega) {
160 if (!body_) return;
161 body_->SetAngularVelocity(omega);
162}
163
165 if (!body_) return 0.f;
166 return body_->GetAngularVelocity();
167}
168
169void Body::applyForce(float fx, float fy) {
170 if (!body_ || !world_) return;
171 // Force in Newtons ≈ (pixels/s² * mass) with mass in kg; convert like LÖVE.
172 body_->ApplyForceToCenter(b2Vec2(world_->toMeters(fx), world_->toMeters(fy)), true);
173}
174
175void Body::applyForceAt(float fx, float fy, float x, float y) {
176 if (!body_ || !world_) return;
177 body_->ApplyForce(b2Vec2(world_->toMeters(fx), world_->toMeters(fy)),
178 b2Vec2(world_->toMeters(x), world_->toMeters(y)), true);
179}
180
181void Body::applyLinearImpulse(float ix, float iy) {
182 if (!body_ || !world_) return;
183 body_->ApplyLinearImpulse(b2Vec2(world_->toMeters(ix), world_->toMeters(iy)),
184 body_->GetWorldCenter(), true);
185}
186
188 if (!body_) return;
189 body_->ApplyAngularImpulse(impulse, true);
190}
191
192void Body::setType(const std::string &bodyType) {
193 if (!body_) return;
194 body_->SetType(parseBodyType(bodyType));
195}
196
197std::string Body::getType() const {
198 if (!body_) return "static";
199 return bodyTypeName(body_->GetType());
200}
201
202void Body::setFixedRotation(bool fixed) {
203 if (!body_) return;
204 body_->SetFixedRotation(fixed);
205}
206
207bool Body::isFixedRotation() const { return body_ ? body_->IsFixedRotation() : false; }
208
210 if (!body_) return;
211 body_->SetActive(active);
212}
213
214bool Body::isActive() const { return body_ ? body_->IsActive() : false; }
215
217 if (!body_) return;
218 body_->SetBullet(bullet);
219}
220
221bool Body::isBullet() const { return body_ ? body_->IsBullet() : false; }
222
224 if (!body_) return;
225 body_->SetAwake(awake);
226}
227
228bool Body::isAwake() const { return body_ ? body_->IsAwake() : false; }
229
234
236 float density, float friction, float restitution) {
237 if (!body_ || !world_) throw eve::Exception("Body.newRectangleFixture: body destroyed");
238 if (width <= 0.f || height <= 0.f)
239 throw eve::Exception("Body.newRectangleFixture: width/height must be > 0");
240
241 b2PolygonShape shape;
242 shape.SetAsBox(world_->toMeters(width) * 0.5f, world_->toMeters(height) * 0.5f,
243 b2Vec2(world_->toMeters(offsetX), world_->toMeters(offsetY)), 0.f);
244
245 b2FixtureDef def;
246 def.shape = &shape;
247 def.density = density;
248 def.friction = friction;
249 def.restitution = restitution;
250
251 b2Fixture *raw = body_->CreateFixture(&def);
252 auto *fx = new Fixture(world_, this, raw);
253 raw->SetUserData(fx);
254 world_->fixtures_.insert(fx);
255 return fx;
256}
257
259 if (!body_ || !world_) throw eve::Exception("Body.newCircleFixture: body destroyed");
260 if (radius <= 0.f) throw eve::Exception("Body.newCircleFixture: radius must be > 0");
261
262 b2CircleShape shape;
263 shape.m_radius = world_->toMeters(radius);
264
265 b2FixtureDef def;
266 def.shape = &shape;
267 def.density = density;
268 def.friction = friction;
269 def.restitution = restitution;
270
271 b2Fixture *raw = body_->CreateFixture(&def);
272 auto *fx = new Fixture(world_, this, raw);
273 raw->SetUserData(fx);
274 world_->fixtures_.insert(fx);
275 return fx;
276}
277
278Fixture *Body::newPolygonFixture(const std::vector<float> &vertices, float density,
279 float friction, float restitution) {
280 if (!body_ || !world_) throw eve::Exception("Body.newPolygonFixture: body destroyed");
281 if (vertices.size() < 6 || vertices.size() > 16 || vertices.size() % 2 != 0)
282 throw eve::Exception("Body.newPolygonFixture: expected 3..8 packed XY vertices");
283 std::vector<b2Vec2> points;
284 points.reserve(vertices.size() / 2);
285 for (size_t index = 0; index < vertices.size(); index += 2) {
286 if (!std::isfinite(vertices[index]) || !std::isfinite(vertices[index + 1]))
287 throw eve::Exception("Body.newPolygonFixture: vertices must be finite");
288 points.emplace_back(world_->toMeters(vertices[index]), world_->toMeters(vertices[index + 1]));
289 }
290 b2PolygonShape shape;
291 shape.Set(points.data(), static_cast<int32>(points.size()));
292 if (shape.GetVertexCount() < 3)
293 throw eve::Exception("Body.newPolygonFixture: vertices do not form a convex polygon");
294 b2FixtureDef def;
295 def.shape = &shape;
296 def.density = density;
297 def.friction = friction;
298 def.restitution = restitution;
299 b2Fixture *raw = body_->CreateFixture(&def);
300 if (!raw) throw eve::Exception("Body.newPolygonFixture: Box2D rejected the fixture");
301 auto *fixture = new Fixture(world_, this, raw);
302 raw->SetUserData(fixture);
303 world_->fixtures_.insert(fixture);
304 return fixture;
305}
306
307Fixture *Body::newChainFixture(const std::vector<float> &vertices, bool loop, float friction,
308 float restitution) {
309 if (!body_ || !world_) throw eve::Exception("Body.newChainFixture: body destroyed");
310 const size_t count = vertices.size() / 2;
311 if (vertices.size() % 2 != 0 || count < (loop ? 3U : 2U) || count > 100000U)
312 throw eve::Exception("Body.newChainFixture: invalid packed XY vertex count");
313 std::vector<b2Vec2> points;
314 points.reserve(count);
315 for (size_t index = 0; index < vertices.size(); index += 2) {
316 if (!std::isfinite(vertices[index]) || !std::isfinite(vertices[index + 1]))
317 throw eve::Exception("Body.newChainFixture: vertices must be finite");
318 const b2Vec2 point(world_->toMeters(vertices[index]), world_->toMeters(vertices[index + 1]));
319 if (!points.empty() && point == points.back())
320 throw eve::Exception("Body.newChainFixture: consecutive vertices must be distinct");
321 points.push_back(point);
322 }
323 if (loop && points.front() == points.back())
324 throw eve::Exception("Body.newChainFixture: loop endpoint is implicit and must not be repeated");
325 b2ChainShape shape;
326 if (loop)
327 shape.CreateLoop(points.data(), static_cast<int32>(points.size()));
328 else
329 shape.CreateChain(points.data(), static_cast<int32>(points.size()));
330 b2FixtureDef def;
331 def.shape = &shape;
332 def.friction = friction;
333 def.restitution = restitution;
334 b2Fixture *raw = body_->CreateFixture(&def);
335 if (!raw) throw eve::Exception("Body.newChainFixture: Box2D rejected the fixture");
336 auto *fixture = new Fixture(world_, this, raw);
337 raw->SetUserData(fixture);
338 world_->fixtures_.insert(fixture);
339 return fixture;
340}
341
342} // namespace eve::physics
double y
double x
bool & active
bool awake
float friction
float density
ShaderImageInput shape
std::uint32_t height
std::uint32_t width
std::string id
double radius
Definition MeleeHit.cpp:42
float f
std::shared_ptr< const std::vector< glm::vec2 > > points
std::string body
float t
double restitution
int count
std::array< double, 2 > vertices[3]
float offsetX
float offsetY
uint32_t index
std::array< double, 3 > impulse
glm::vec3 point
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
static constexpr RuntimeHandle invalid() noexcept
Returns the canonical invalid handle.
Fixture * newRectangleFixture(float width, float height, float density=1.f, float friction=0.2f, float restitution=0.f)
Creates a rectangle fixture in pixel-space units.
Definition Body.cpp:230
float getLinearVelocityX() const
Returns the linear velocity x.
Definition Body.cpp:132
void applyForceAt(float fx, float fy, float x, float y)
Force applied at a world pixel position.
Definition Body.cpp:175
void setBullet(bool bullet)
CCD bullet mode (recommended for fast small bodies).
Definition Body.cpp:216
float getX() const
Returns the x.
Definition Body.cpp:107
void setAwake(bool awake)
Wakes / sleeps the body manually.
Definition Body.cpp:223
void setType(const std::string &bodyType)
"static" | "kinematic" | "dynamic".
Definition Body.cpp:192
void setAngle(float radians)
Rotation in radians.
Definition Body.cpp:117
float getLinearVelocityY() const
Returns the linear velocity y.
Definition Body.cpp:137
bool isActive() const
True when active.
Definition Body.cpp:214
void applyLinearImpulse(float ix, float iy)
Instantaneous linear impulse.
Definition Body.cpp:181
Fixture * newPolygonFixture(const std::vector< float > &vertices, float density=1.f, float friction=0.2f, float restitution=0.f)
Create a bounded convex polygon fixture from packed local pixel-space XY vertices.
Definition Body.cpp:278
Fixture * newCircleFixture(float radius, float density=1.f, float friction=0.2f, float restitution=0.f)
Creates a circular fixture in pixel-space units.
Definition Body.cpp:258
void setFixedRotation(bool fixed)
Locks rotation so the body cannot spin.
Definition Body.cpp:202
Fixture * newChainFixture(const std::vector< float > &vertices, bool loop=false, float friction=0.2f, float restitution=0.f)
Create an open chain or closed loop from packed local pixel-space XY vertices.
Definition Body.cpp:307
void applyForce(float fx, float fy)
Force (pixels/s² * kg) applied at the center of mass.
Definition Body.cpp:169
bool isAwake() const
True when awake.
Definition Body.cpp:228
bool isFixedRotation() const
True when fixed rotation.
Definition Body.cpp:207
bool isBullet() const
True when bullet.
Definition Body.cpp:221
friend class Fixture
Definition Body.h:212
void setAngularVelocity(float omega)
Angular velocity in radians/s.
Definition Body.cpp:159
b2Body * raw()
Exposes the underlying Box2D body for tightly-scoped backend integration.
Definition Body.h:194
float getAngularVelocity() const
Returns the angular velocity.
Definition Body.cpp:164
void destroy()
Destroys the body inside its world.
Definition Body.cpp:73
void applyAngularImpulse(float impulse)
Instantaneous angular impulse.
Definition Body.cpp:187
float getWorldCenterY() const
Returns the world center y.
Definition Body.cpp:154
float getLinearSpeed() const
Magnitude of the linear velocity.
Definition Body.cpp:142
float getAngle() const
Returns the angle.
Definition Body.cpp:122
std::string getType() const
Returns the type.
Definition Body.cpp:197
int getId() const
Stable id used by contact/impact events.
Definition Body.h:32
void invalidate()
Internal: marks the wrapper invalid after world destruction.
Definition Body.cpp:66
void setPosition(float x, float y)
Position in pixels.
Definition Body.cpp:102
float getWorldCenterX() const
World center of mass in pixels.
Definition Body.cpp:149
Body(World *world, b2Body *body, int id, PhysicsBodyHandle runtimeHandle)
Internal: wraps a Box2D body (use World::newBody).
Definition Body.cpp:35
Fixture * newRectangleFixtureAt(float width, float height, float offsetX, float offsetY, float density=1.f, float friction=0.2f, float restitution=0.f)
Creates an offset rectangle fixture in pixel-space units.
Definition Body.cpp:235
float getMass() const
Mass in kilograms (Box2D units).
Definition Body.cpp:147
void setActive(bool active)
Disables/enables the body and its fixtures.
Definition Body.cpp:209
void setLinearVelocity(float vx, float vy)
Linear velocity in pixels/s.
Definition Body.cpp:127
float getY() const
Returns the y.
Definition Body.cpp:112
2D fixture: a shape attached to a Body with material + filter settings. Also carries a string tag use...
Definition Fixture.h:18
Owning planar joint wrapper observing World-owned backend state. @ownership Caller/VM owns factory wr...
Definition Joint2D.h:58
Box2D world wrapper (2D physics) with pixel-space coordinates. Handles stepping, gravity,...
Definition World.h:44
void forgetBody(Body *body)
Definition World.cpp:514
void forgetFixture(Fixture *fixture)
Definition World.cpp:527
float toPixels(float meters) const
Converts a meter-space length to pixels.
Definition World.cpp:468
b2World * raw()
Exposes the underlying Box2D world for tightly-scoped backend integration.
Definition World.h:417
float toMeters(float pixels) const
Converts a pixel-space length to meters.
Definition World.cpp:467
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36