-
Notifications
You must be signed in to change notification settings - Fork 94
/
BulletExample.cpp
370 lines (307 loc) · 14.3 KB
/
BulletExample.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
/*
This file is part of Magnum.
Original authors — credit is appreciated but not required:
2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022, 2023, 2024 — Vladimír Vondruš <[email protected]>
2013 — Jan Dupal <[email protected]>
2019 — Max Schwarz <[email protected]>
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of
this software dedicate any and all copyright interest in the software to
the public domain. We make this dedication for the benefit of the public
at large and to the detriment of our heirs and successors. We intend this
dedication to be an overt act of relinquishment in perpetuity of all
present and future rights to this software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <btBulletDynamicsCommon.h>
#include <Corrade/Containers/GrowableArray.h>
#include <Corrade/Containers/Optional.h>
#include <Corrade/Containers/Pointer.h>
#include <Magnum/Timeline.h>
#include <Magnum/BulletIntegration/Integration.h>
#include <Magnum/BulletIntegration/MotionState.h>
#include <Magnum/BulletIntegration/DebugDraw.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Mesh.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Constants.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Math/Time.h>
#include <Magnum/MeshTools/Compile.h>
#include <Magnum/MeshTools/Transform.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Primitives/Cube.h>
#include <Magnum/Primitives/UVSphere.h>
#include <Magnum/SceneGraph/Camera.h>
#include <Magnum/SceneGraph/Drawable.h>
#include <Magnum/SceneGraph/MatrixTransformation3D.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/Shaders/PhongGL.h>
#include <Magnum/Trade/MeshData.h>
#ifdef BT_USE_DOUBLE_PRECISION
#error sorry, this example does not support Bullet with double precision enabled
#endif
namespace Magnum { namespace Examples {
using namespace Math::Literals;
typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D;
typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D;
struct InstanceData {
Matrix4 transformationMatrix;
Matrix3x3 normalMatrix;
Color3 color;
};
class BulletExample: public Platform::Application {
public:
explicit BulletExample(const Arguments& arguments);
private:
void drawEvent() override;
void keyPressEvent(KeyEvent& event) override;
void pointerPressEvent(PointerEvent& event) override;
GL::Mesh _box{NoCreate}, _sphere{NoCreate};
GL::Buffer _boxInstanceBuffer{NoCreate}, _sphereInstanceBuffer{NoCreate};
Shaders::PhongGL _shader{NoCreate};
BulletIntegration::DebugDraw _debugDraw{NoCreate};
Containers::Array<InstanceData> _boxInstanceData, _sphereInstanceData;
btDbvtBroadphase _bBroadphase;
btDefaultCollisionConfiguration _bCollisionConfig;
btCollisionDispatcher _bDispatcher{&_bCollisionConfig};
btSequentialImpulseConstraintSolver _bSolver;
/* The world has to live longer than the scene because RigidBody
instances have to remove themselves from it on destruction */
btDiscreteDynamicsWorld _bWorld{&_bDispatcher, &_bBroadphase, &_bSolver, &_bCollisionConfig};
Scene3D _scene;
SceneGraph::Camera3D* _camera;
SceneGraph::DrawableGroup3D _drawables;
Timeline _timeline;
Object3D *_cameraRig, *_cameraObject;
btBoxShape _bBoxShape{{0.5f, 0.5f, 0.5f}};
btSphereShape _bSphereShape{0.25f};
btBoxShape _bGroundShape{{4.0f, 0.5f, 4.0f}};
bool _drawCubes{true}, _drawDebug{true}, _shootBox{true};
};
class ColoredDrawable: public SceneGraph::Drawable3D {
public:
explicit ColoredDrawable(Object3D& object, Containers::Array<InstanceData>& instanceData, const Color3& color, const Matrix4& primitiveTransformation, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _instanceData(instanceData), _color{color}, _primitiveTransformation{primitiveTransformation} {}
private:
void draw(const Matrix4& transformation, SceneGraph::Camera3D&) override {
const Matrix4 t = transformation*_primitiveTransformation;
arrayAppend(_instanceData, InPlaceInit, t, t.normalMatrix(), _color);
}
Containers::Array<InstanceData>& _instanceData;
Color3 _color;
Matrix4 _primitiveTransformation;
};
class RigidBody: public Object3D {
public:
RigidBody(Object3D* parent, Float mass, btCollisionShape* bShape, btDynamicsWorld& bWorld): Object3D{parent}, _bWorld(bWorld) {
/* Calculate inertia so the object reacts as it should with
rotation and everything */
btVector3 bInertia(0.0f, 0.0f, 0.0f);
if(!Math::TypeTraits<Float>::equals(mass, 0.0f))
bShape->calculateLocalInertia(mass, bInertia);
/* Bullet rigid body setup */
auto* motionState = new BulletIntegration::MotionState{*this};
_bRigidBody.emplace(btRigidBody::btRigidBodyConstructionInfo{
mass, &motionState->btMotionState(), bShape, bInertia});
_bRigidBody->forceActivationState(DISABLE_DEACTIVATION);
bWorld.addRigidBody(_bRigidBody.get());
}
~RigidBody() {
_bWorld.removeRigidBody(_bRigidBody.get());
}
btRigidBody& rigidBody() { return *_bRigidBody; }
/* needed after changing the pose from Magnum side */
void syncPose() {
_bRigidBody->setWorldTransform(btTransform(transformationMatrix()));
}
private:
btDynamicsWorld& _bWorld;
Containers::Pointer<btRigidBody> _bRigidBody;
};
BulletExample::BulletExample(const Arguments& arguments): Platform::Application(arguments, NoCreate) {
/* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x
MSAA if we have enough DPI. */
{
const Vector2 dpiScaling = this->dpiScaling({});
Configuration conf;
conf.setTitle("Magnum Bullet Integration Example")
.setSize(conf.size(), dpiScaling);
GLConfiguration glConf;
glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2);
if(!tryCreate(conf, glConf))
create(conf, glConf.setSampleCount(0));
}
/* Camera setup */
(*(_cameraRig = new Object3D{&_scene}))
.translate(Vector3::yAxis(3.0f))
.rotateY(40.0_degf);
(*(_cameraObject = new Object3D{_cameraRig}))
.translate(Vector3::zAxis(20.0f))
.rotateX(-25.0_degf);
(_camera = new SceneGraph::Camera3D(*_cameraObject))
->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend)
.setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 1.0f, 0.001f, 100.0f))
.setViewport(GL::defaultFramebuffer.viewport().size());
/* Create an instanced shader */
_shader = Shaders::PhongGL{Shaders::PhongGL::Configuration{}
.setFlags(Shaders::PhongGL::Flag::VertexColor|
Shaders::PhongGL::Flag::InstancedTransformation)};
_shader.setAmbientColor(0x111111_rgbf)
.setSpecularColor(0x330000_rgbf)
.setLightPositions({{10.0f, 15.0f, 5.0f, 0.0f}});
/* Box and sphere mesh, with an (initially empty) instance buffer */
_box = MeshTools::compile(Primitives::cubeSolid());
_sphere = MeshTools::compile(Primitives::uvSphereSolid(16, 32));
_boxInstanceBuffer = GL::Buffer{};
_sphereInstanceBuffer = GL::Buffer{};
_box.addVertexBufferInstanced(_boxInstanceBuffer, 1, 0,
Shaders::PhongGL::TransformationMatrix{},
Shaders::PhongGL::NormalMatrix{},
Shaders::PhongGL::Color3{});
_sphere.addVertexBufferInstanced(_sphereInstanceBuffer, 1, 0,
Shaders::PhongGL::TransformationMatrix{},
Shaders::PhongGL::NormalMatrix{},
Shaders::PhongGL::Color3{});
/* Setup the renderer so we can draw the debug lines on top */
GL::Renderer::enable(GL::Renderer::Feature::DepthTest);
GL::Renderer::enable(GL::Renderer::Feature::FaceCulling);
GL::Renderer::enable(GL::Renderer::Feature::PolygonOffsetFill);
GL::Renderer::setPolygonOffset(2.0f, 0.5f);
/* Bullet setup */
_debugDraw = BulletIntegration::DebugDraw{};
_debugDraw.setMode(BulletIntegration::DebugDraw::Mode::DrawWireframe);
_bWorld.setGravity({0.0f, -10.0f, 0.0f});
_bWorld.setDebugDrawer(&_debugDraw);
/* Create the ground */
auto* ground = new RigidBody{&_scene, 0.0f, &_bGroundShape, _bWorld};
new ColoredDrawable{*ground, _boxInstanceData, 0xffffff_rgbf,
Matrix4::scaling({4.0f, 0.5f, 4.0f}), _drawables};
/* Create boxes with random colors */
Deg hue = 42.0_degf;
for(Int i = 0; i != 5; ++i) {
for(Int j = 0; j != 5; ++j) {
for(Int k = 0; k != 5; ++k) {
auto* o = new RigidBody{&_scene, 1.0f, &_bBoxShape, _bWorld};
o->translate({i - 2.0f, j + 4.0f, k - 2.0f});
o->syncPose();
new ColoredDrawable{*o, _boxInstanceData,
Color3::fromHsv({hue += 137.5_degf, 0.75f, 0.9f}),
Matrix4::scaling(Vector3{0.5f}), _drawables};
}
}
}
/* Loop at 60 Hz max */
setSwapInterval(1);
setMinimalLoopPeriod(16.0_msec);
_timeline.start();
}
void BulletExample::drawEvent() {
GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth);
/* Housekeeping: remove any objects which are far away from the origin */
for(Object3D* obj = _scene.children().first(); obj; )
{
Object3D* next = obj->nextSibling();
if(obj->transformation().translation().dot() > 100*100)
delete obj;
obj = next;
}
/* Step bullet simulation */
_bWorld.stepSimulation(_timeline.previousFrameDuration(), 5);
if(_drawCubes) {
/* Populate instance data with transformations and colors */
arrayResize(_boxInstanceData, 0);
arrayResize(_sphereInstanceData, 0);
_camera->draw(_drawables);
_shader.setProjectionMatrix(_camera->projectionMatrix());
/* Upload instance data to the GPU (orphaning the previous buffer
contents) and draw all cubes in one call, and all spheres (if any)
in another call */
_boxInstanceBuffer.setData(_boxInstanceData, GL::BufferUsage::DynamicDraw);
_box.setInstanceCount(_boxInstanceData.size());
_shader.draw(_box);
_sphereInstanceBuffer.setData(_sphereInstanceData, GL::BufferUsage::DynamicDraw);
_sphere.setInstanceCount(_sphereInstanceData.size());
_shader.draw(_sphere);
}
/* Debug draw. If drawing on top of cubes, avoid flickering by setting
depth function to <= instead of just <. */
if(_drawDebug) {
if(_drawCubes)
GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::LessOrEqual);
_debugDraw.setTransformationProjectionMatrix(
_camera->projectionMatrix()*_camera->cameraMatrix());
_bWorld.debugDrawWorld();
if(_drawCubes)
GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::Less);
}
swapBuffers();
_timeline.nextFrame();
redraw();
}
void BulletExample::keyPressEvent(KeyEvent& event) {
/* Movement */
if(event.key() == Key::Down) {
_cameraObject->rotateX(5.0_degf);
} else if(event.key() == Key::Up) {
_cameraObject->rotateX(-5.0_degf);
} else if(event.key() == Key::Left) {
_cameraRig->rotateY(-5.0_degf);
} else if(event.key() == Key::Right) {
_cameraRig->rotateY(5.0_degf);
/* Toggling draw modes */
} else if(event.key() == Key::D) {
if(_drawCubes && _drawDebug) {
_drawDebug = false;
} else if(_drawCubes && !_drawDebug) {
_drawCubes = false;
_drawDebug = true;
} else if(!_drawCubes && _drawDebug) {
_drawCubes = true;
_drawDebug = true;
}
/* What to shoot */
} else if(event.key() == Key::S) {
_shootBox ^= true;
} else return;
event.setAccepted();
}
void BulletExample::pointerPressEvent(PointerEvent& event) {
/* Shoot an object on click */
if(!event.isPrimary() ||
!(event.pointer() & (Pointer::MouseLeft|Pointer::Finger)))
return;
/* First scale the position from being relative to window size to being
relative to framebuffer size as those two can be different on HiDPI
systems */
const Vector2 position = event.position()*Vector2{framebufferSize()}/Vector2{windowSize()};
const Vector2 clickPoint = Vector2::yScale(-1.0f)*(position/Vector2{framebufferSize()} - Vector2{0.5f})*_camera->projectionSize();
const Vector3 direction = (_cameraObject->absoluteTransformation().rotationScaling()*Vector3{clickPoint, -1.0f}).normalized();
auto* object = new RigidBody{
&_scene,
_shootBox ? 1.0f : 5.0f,
_shootBox ? static_cast<btCollisionShape*>(&_bBoxShape) : &_bSphereShape,
_bWorld};
object->translate(_cameraObject->absoluteTransformation().translation());
/* Has to be done explicitly after the translate() above, as Magnum ->
Bullet updates are implicitly done only for kinematic bodies */
object->syncPose();
/* Create either a box or a sphere */
new ColoredDrawable{*object,
_shootBox ? _boxInstanceData : _sphereInstanceData,
_shootBox ? 0x880000_rgbf : 0x220000_rgbf,
Matrix4::scaling(Vector3{_shootBox ? 0.5f : 0.25f}), _drawables};
/* Give it an initial velocity */
object->rigidBody().setLinearVelocity(btVector3{direction*25.f});
event.setAccepted();
}
}}
MAGNUM_APPLICATION_MAIN(Magnum::Examples::BulletExample)