-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimulationview.cpp
343 lines (292 loc) · 12.8 KB
/
simulationview.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
/*
* TEAM S.A.M.B.A.M:
* Adam Liu, Aidan Spendlove, Sam Hill,
* Blake England, Matthew Johnson, Michael Wadley
*
* GitHub: https://github.com/University-of-Utah-CS3505/A9EduApp
* Project: Assignment 9 - Educational App
* File: simulationview.h
*/
#include "simulationview.h"
#include "Box2D/Collision/Shapes/b2CircleShape.h"
#include "Box2D/Collision/Shapes/b2PolygonShape.h"
#include "Box2D/Dynamics/b2Body.h"
#include "Box2D/Dynamics/b2Fixture.h"
#include "qtimer.h"
#include <QKeyEvent>
#include <QOpenGLWidget>
#include <QSurfaceFormat>
SimulationView::SimulationView(QWidget* parent): world(b2Vec2(0.0f, 0.0f)) {
scene = new QGraphicsScene(0, 0, 800, 546);
setScene(scene);
sceneBackground = new QGraphicsPathItem();
QPainterPath path;
path.addRoundedRect(QRectF(0, 0, scene->width(), scene->height()), 10, 10);
sceneBackground->setPath(path);
sceneBackground->setBrush(Qt::black);
scene->addItem(sceneBackground);
setPosition(sceneBackground, scene->width() / 2, scene->height() / 2);
this->installEventFilter(this);
// Define the ground.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(pixelsToMeters(scene->width() / 2), 0.0f);
b2Body* groundBody = world.CreateBody(&groundBodyDef);
b2PolygonShape groundBox;
groundBox.SetAsBox(pixelsToMeters(scene->width() / 2), 0.0f);
groundBody->CreateFixture(&groundBox, 0.0f);
// Define the ceiling.
b2BodyDef ceilingBodyDef;
ceilingBodyDef.position.Set(pixelsToMeters(scene->width() / 2), pixelsToMeters(scene->height()));
b2Body* ceilingBody = world.CreateBody(&ceilingBodyDef);
b2PolygonShape ceilingBox;
ceilingBox.SetAsBox(pixelsToMeters(scene->width() / 2), 0.0f);
ceilingBody->CreateFixture(&ceilingBox, 0.0f);
// Define the left wall.
b2BodyDef leftWallBodyDef;
leftWallBodyDef.position.Set(0.0f, pixelsToMeters(scene->height() / 2));
b2Body* leftWallBody = world.CreateBody(&leftWallBodyDef);
b2PolygonShape leftWallBox;
leftWallBox.SetAsBox(0.0f, pixelsToMeters(scene->height() / 2));
leftWallBody->CreateFixture(&leftWallBox, 0.0f);
// Define the right wall.
b2BodyDef rightWallBodyDef;
rightWallBodyDef.position.Set(pixelsToMeters(scene->width()), pixelsToMeters(scene->height()) / 2);
b2Body* rightWallBody = world.CreateBody(&rightWallBodyDef);
b2PolygonShape rightWallBox;
rightWallBox.SetAsBox(0.0f, pixelsToMeters(scene->height() / 2));
rightWallBody->CreateFixture(&rightWallBox, 0.0f);
// Setup the physics timer
timer = new QTimer();
connect(timer, &QTimer::timeout, this, &SimulationView::updateWorld);
}
void SimulationView::updateWorld() {
// Instruct the world to perform a single step of simulation.
world.Step(1.0f / 300.0f, 6, 2);
if(pressedKeys.contains(Qt::Key_Up))
forces.push_back(b2Vec2(0, 0.1f));
if(pressedKeys.contains(Qt::Key_Down))
forces.push_back(b2Vec2(0, -0.1f));
if(pressedKeys.contains(Qt::Key_Left))
forces.push_back(b2Vec2(-0.1f, 0));
if(pressedKeys.contains(Qt::Key_Right))
forces.push_back(b2Vec2(0.1f, 0));
applyForcesToAllBodies();
for(int i = 0; i < shapeCount; i++) {
b2Vec2 position = shapeBodies.at(i)->GetPosition();
setPosition(shapeImages.at(i), metersToPixels(position.x), metersToPixels(position.y));
float32 angleInDegrees = shapeBodies.at(i)->GetAngle() * (180.0 / M_PI);
shapeImages.at(i)->setRotation(angleInDegrees);
}
}
void SimulationView::setShapeCount(int count) {
shapeCount = count;
}
void SimulationView::setShape(int shape) {
this->shape = shape;
}
void SimulationView::setElasticity(double elasticity) {
this->elasticity = elasticity;
}
void SimulationView::setGravity(double gravity) {
world.SetGravity(b2Vec2(0.0f, gravity));
}
void SimulationView::setFriction(double friction) {
this->friction = friction;
}
void SimulationView::setShapeDensity(double density) {
this->shapeDensity = density;
}
void SimulationView::setShapeWidth(int width) {
this->shapeWidth = width;
}
void SimulationView::setShapeHeight(int height) {
this->shapeHeight = height;
}
void SimulationView::setBackgroundColor(bool override, QColor color) {
if(override)
sceneBackground->setBrush(color);
else
sceneBackground->setBrush(Qt::black);
}
void SimulationView::setShapeColor(bool override, QColor color) {
overrideShapeColor = override;
shapeColor = color;
}
void SimulationView::setPosition(QGraphicsItem* itemToPosition, float x, float y) {
itemToPosition->setPos(x - itemToPosition->boundingRect().width() / 2,
scene->height() - y - itemToPosition->boundingRect().height() / 2);
}
void SimulationView::resizeEvent(QResizeEvent* event) {
fitInView(scene->sceneRect(), Qt::KeepAspectRatio);
}
void SimulationView::runSimulation() {
timer->stop();
std::srand(static_cast<unsigned int>(std::time(nullptr)));
for(QGraphicsItem* shapeImage : shapeImages) {
delete shapeImage;
}
shapeImages.clear();
for(b2Body* shapeBody : shapeBodies) {
world.DestroyBody(shapeBody);
}
shapeBodies.clear();
for(int i = 0; i < shapeCount; i++) {
if(shape == random)
createShape(getRandomNumber(1, 2));
else
createShape(shape);
}
timer->start(3);
emit startLabelTimer(500);
}
void SimulationView::createShape(int shape) {
switch(shape) {
case circle: {
b2CircleShape ballShape;
ballShape.m_radius = pixelsToMeters(shapeWidth / 2);
// Define the car's dynamic body. We set its position and call the body factory.
b2BodyDef ballDef;
ballDef.type = b2_dynamicBody;
ballDef.position.Set(getRandomNumber(pixelsToMeters(60), pixelsToMeters(scene->width() - 60)),
getRandomNumber(pixelsToMeters(60), pixelsToMeters(scene->height() - 60)));
ballDef.angle = 0.0f * b2_pi;
ballDef.allowSleep = true;
ballDef.awake = true;
b2Body* ballBody = world.CreateBody(&ballDef);
// Define the dynamic body fixture.
b2FixtureDef ballFixture;
ballFixture.shape = &ballShape;
ballFixture.density = shapeDensity;
ballFixture.friction = friction;
ballFixture.restitution = elasticity;
// Add the shape to the body.
ballBody->CreateFixture(&ballFixture);
shapeBodies.push_back(ballBody);
QGraphicsEllipseItem* ballImage =
new QGraphicsEllipseItem(0, 0, metersToPixels(ballShape.m_radius * 2), metersToPixels(ballShape.m_radius * 2));
ballImage->setTransformOriginPoint(QPoint(ballImage->boundingRect().width() / 2, ballImage->boundingRect().height() / 2));
if(overrideShapeColor)
ballImage->setBrush(shapeColor);
else
ballImage->setBrush(QColor(getRandomNumber(15, 255), getRandomNumber(15, 255), getRandomNumber(15, 255)));
scene->addItem(ballImage);
shapeImages.push_back(ballImage);
setPosition(ballImage, metersToPixels(ballBody->GetPosition().x), metersToPixels(ballBody->GetPosition().y));
break;
}
case rectangle: {
b2BodyDef rectDef;
rectDef.type = b2_dynamicBody;
rectDef.position.Set(getRandomNumber(pixelsToMeters(60), pixelsToMeters(scene->width() - 60)),
getRandomNumber(pixelsToMeters(60), pixelsToMeters(scene->height() - 60)));
b2Body* rectBody = world.CreateBody(&rectDef);
rectDef.angle = 0.0f * b2_pi;
rectDef.allowSleep = true;
rectDef.awake = true;
b2PolygonShape dynamicBox;
dynamicBox.SetAsBox(pixelsToMeters(shapeWidth / 2), pixelsToMeters(shapeHeight / 2));
// Define the dynamic body fixture.
b2FixtureDef rectFixture;
rectFixture.shape = &dynamicBox;
rectFixture.density = shapeDensity;
rectFixture.friction = friction;
rectFixture.restitution = elasticity;
// Add the shape to the body.
rectBody->CreateFixture(&rectFixture);
shapeBodies.push_back(rectBody);
QGraphicsRectItem* rectImage = new QGraphicsRectItem(0, 0, shapeWidth, shapeHeight);
rectImage->setTransformOriginPoint(QPoint(rectImage->boundingRect().width() / 2, rectImage->boundingRect().height() / 2));
scene->addItem(rectImage);
shapeImages.push_back(rectImage);
if(overrideShapeColor)
rectImage->setBrush(shapeColor);
else
rectImage->setBrush(QColor(getRandomNumber(15, 255), getRandomNumber(15, 255), getRandomNumber(15, 255)));
setPosition(rectImage, metersToPixels(rectBody->GetPosition().x), metersToPixels(rectBody->GetPosition().y));
break;
}
case triangle: {
b2BodyDef triangleDef;
triangleDef.type = b2_dynamicBody;
triangleDef.position.Set(getRandomNumber(pixelsToMeters(60), pixelsToMeters(scene->width() - 60)),
getRandomNumber(pixelsToMeters(60), pixelsToMeters(scene->height() - 60)));
triangleDef.angle = 0.0f * b2_pi;
triangleDef.allowSleep = true;
triangleDef.awake = true;
b2Body* triangleBody = world.CreateBody(&triangleDef);
b2Vec2 vertices[3];
vertices[0].Set(0.0f, 0.0f);
vertices[1].Set(pixelsToMeters(shapeWidth / 2), 0);
vertices[2].Set(pixelsToMeters(shapeWidth / 2), pixelsToMeters(shapeHeight));
b2PolygonShape triangleShape;
triangleShape.Set(vertices, 3);
// Define the dynamic body fixture.
b2FixtureDef triangleFixture;
triangleFixture.shape = &triangleShape;
triangleFixture.density = shapeDensity;
triangleFixture.friction = friction;
triangleFixture.restitution = elasticity;
// Add the shape to the body.
triangleBody->CreateFixture(&triangleFixture);
shapeBodies.push_back(triangleBody);
QPolygonF triangle;
triangle << QPointF(shapeWidth / 2, -shapeHeight) << QPointF(shapeWidth, shapeHeight / 2) << QPointF(0, shapeHeight / 2);
QGraphicsPolygonItem* triangleImage = scene->addPolygon(triangle);
triangleImage->setTransformOriginPoint(
QPoint(triangleImage->boundingRect().width() / 2, triangleImage->boundingRect().height() / 2));
if(overrideShapeColor)
triangleImage->setBrush(shapeColor);
else
triangleImage->setBrush(QColor(getRandomNumber(15, 255), getRandomNumber(15, 255), getRandomNumber(15, 255)));
shapeImages.push_back(triangleImage);
setPosition(triangleImage, metersToPixels(triangleBody->GetPosition().x), metersToPixels(triangleBody->GetPosition().y));
break;
}
}
b2Vec2 impulseForce = b2Vec2((pixelsToMeters((scene->width() / 2)) - shapeBodies.at(shapeBodies.length() - 1)->GetPosition().x) * 6,
(pixelsToMeters((scene->height() / 2)) - shapeBodies.at(shapeBodies.length() - 1)->GetPosition().y) * 6);
shapeBodies.at(shapeBodies.length() - 1)->ApplyForceToCenter(impulseForce, true);
// shapeBodies.at(shapeBodies.length() - 1)->ApplyForceToCenter(b2Vec2(0, -5000), true);
}
double SimulationView::pixelsToMeters(double pixels) {
return pixels / pixelsPerMeter;
}
double SimulationView::metersToPixels(double meters) {
return meters * pixelsPerMeter;
}
int SimulationView::getRandomNumber(int min, int max) {
return min + std::rand() % (max - min + 1);
}
bool SimulationView::eventFilter(QObject* obj, QEvent* event) {
if(event->type() == QEvent::KeyPress)
pressedKeys += ((QKeyEvent*) event)->key();
else if(event->type() == QEvent::KeyRelease)
pressedKeys -= ((QKeyEvent*) event)->key();
return false;
}
void SimulationView::applyForcesToAllBodies() {
for(b2Body* body : shapeBodies) {
for(b2Vec2 force : forces) {
body->ApplyForceToCenter(force, true);
}
}
forces.clear();
}
void SimulationView::stopSimulation() {
timer->stop();
emit stopLabelTimer();
}
SimulationView::~SimulationView() {
timer->stop();
delete timer;
for(b2Body* ballBody : shapeBodies) {
if(ballBody != nullptr) {
world.DestroyBody(ballBody);
}
}
for(QGraphicsItem* ballImage : shapeImages) {
delete ballImage;
}
delete sceneBackground;
delete scene;
}