-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimulationViewWidget.cpp
More file actions
343 lines (298 loc) · 12.2 KB
/
SimulationViewWidget.cpp
File metadata and controls
343 lines (298 loc) · 12.2 KB
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
#include "SimulationViewWidget.h"
#include "GeneFactory.h"
#include <RollingStatistics.h>
#include <QPainter>
#include <QLocale>
#include <QScrollBar>
#include <QCoreApplication>
#include <QWheelEvent>
#include <QTime>
SimulationViewWidget::SimulationViewWidget(QWidget* parent)
: QAbstractScrollArea(parent)
, simulationDriver(this)
, repaintDriver(this)
, infoModel(this)
, viewLight(false)
, leftMouseButtonAction(MouseButtonAction::AddPlantSeed)
, rightMouseButtonAction(MouseButtonAction::SelectPlant)
, selectedPlant(nullptr)
{
verticalScrollBar()->setInvertedAppearance(true);
setVerticalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAsNeeded);
setHorizontalScrollBarPolicy(Qt::ScrollBarPolicy::ScrollBarAsNeeded);
repaintDriver.setSingleShot(false);
repaintDriver.setInterval(1000 / 60);
connect(&repaintDriver, &QTimer::timeout, viewport(), static_cast<void(QWidget::*)()>(&QWidget::update));
simulationDriver.setSingleShot(false);
simulationDriver.setInterval(0);
connect(&simulationDriver, &QTimer::timeout, this, &SimulationViewWidget::Tick);
infoUpdateDriver.setSingleShot(false);
infoUpdateDriver.setInterval(1000 / 1);
connect(&infoUpdateDriver, &QTimer::timeout, this, &SimulationViewWidget::UpdateInfoModel);
}
void SimulationViewWidget::SetSimulation(std::shared_ptr<Simulation> sim)
{
this->sim = sim;
UpdateScrollBars();
}
void SimulationViewWidget::UpdateScrollBars()
{
if (sim) {
QSize areaSize = viewport()->size();
QSize widgetSize = sim->GetLightMap().GetRect().size();
verticalScrollBar()->setPageStep(areaSize.height());
horizontalScrollBar()->setPageStep(areaSize.width());
verticalScrollBar()->setSingleStep(areaSize.height() / 100);
horizontalScrollBar()->setSingleStep(areaSize.width() / 100);
verticalScrollBar()->setRange(0, widgetSize.height() - areaSize.height());
horizontalScrollBar()->setRange(0, widgetSize.width() - areaSize.width());
viewport()->update();
}
}
void SimulationViewWidget::SetShowLight(bool showLight)
{
viewLight = showLight;
}
void SimulationViewWidget::SetPaused(bool paused)
{
if (paused) {
simulationDriver.stop();
} else {
simulationDriver.start();
}
}
void SimulationViewWidget::SetTargetFramesPerSecond(unsigned targetFps)
{
repaintDriver.setInterval(1000 / std::max(1u, targetFps));
}
void SimulationViewWidget::SetTargetTicksPerSecond(unsigned targetTps)
{
simulationDriver.setInterval(1000 / std::max(1u, targetTps));
}
void SimulationViewWidget::SetUnlimitedTicksPerSecond()
{
simulationDriver.setInterval(0);
}
void SimulationViewWidget::SetLeftMouseButtonAction(MouseButtonAction action)
{
leftMouseButtonAction = action;
}
void SimulationViewWidget::SetRightMouseButtonAction(MouseButtonAction action)
{
rightMouseButtonAction = action;
}
SimulationInfoTableModel& SimulationViewWidget::GetSimulationInfoModel()
{
return infoModel;
}
std::shared_ptr<Plant> SimulationViewWidget::GetSelectedPlant() const
{
return selectedPlant;
}
void SimulationViewWidget::mousePressEvent(QMouseEvent* event)
{
if (sim) {
if (event->button() == Qt::MouseButton::LeftButton) {
PerformMouseButtonAction(leftMouseButtonAction, event->position());
} else if (event->button() == Qt::MouseButton::RightButton) {
PerformMouseButtonAction(rightMouseButtonAction, event->position());
}
}
}
void SimulationViewWidget::mouseMoveEvent(QMouseEvent* event)
{
if (sim) {
if (event->buttons() & Qt::MouseButton::LeftButton) {
PerformMouseButtonAction(leftMouseButtonAction, event->position());
} else if (event->buttons() & Qt::MouseButton::RightButton) {
PerformMouseButtonAction(rightMouseButtonAction, event->position());
}
}
}
void SimulationViewWidget::wheelEvent(QWheelEvent* event)
{
QCoreApplication::sendEvent(horizontalScrollBar(), event);
}
void SimulationViewWidget::paintEvent(QPaintEvent* /*event*/)
{
QPainter paint(viewport());
// Paint the sky
paint.fillRect(viewport()->rect(), QGradient(QGradient::SkyGlider));
// Flip painter vertically so x=0 is at bottom of the screen
paint.translate(0, viewport()->height());
paint.scale(1, -1);
// Paint the ground
paint.fillRect(QRect(0, 0, viewport()->width(), groundHeight), Qt::green);
// Move the painter so x=0 is at groundHeght
paint.translate(0, groundHeight);
QRect viewportArea = viewport()->rect().translated(horizontalScrollBar()->value(), verticalScrollBar()->value());
paint.translate(-viewportArea.topLeft());
if (viewLight) {
paint.drawImage(viewportArea.topLeft(), sim->GetLightMap().GetLightImage(viewportArea));
}
// Paint the plants, shortest last so they aren't hidden by taller plant's stems
std::vector<const Plant*> sortedPlants;
for (const auto& plant : sim->GetPlants()) {
if (viewportArea.intersects(plant->GetBounds().toRect())) {
sortedPlants.push_back(plant.get());
}
}
std::stable_sort(std::begin(sortedPlants), std::end(sortedPlants), [](const Plant* a, const Plant* b)
{
return a->GetBounds().height() > b->GetBounds().height();
});
paint.setRenderHint(QPainter::RenderHint::Antialiasing, true);
for (const Plant* plantPtr : sortedPlants) {
const Plant& plant = *plantPtr;
PaintPlant(paint, plant, false);
}
if (selectedPlant && selectedPlant->IsAlive()) {
PaintPlant(paint, *selectedPlant, true);
}
}
void SimulationViewWidget::showEvent(QShowEvent*)
{
simulationDriver.start();
repaintDriver.start();
infoUpdateDriver.start();
UpdateScrollBars();
}
void SimulationViewWidget::resizeEvent(QResizeEvent* /*event*/)
{
UpdateScrollBars();
}
QString SimulationViewWidget::ElapsedTimeString(qint64 elapsedMsecs)
{
constexpr qint64 milliSecondsInDay = 1000 * 60 * 60 * 24;
qint64 elapsedDays = elapsedMsecs / milliSecondsInDay;
QTime elapsedTime = QTime::fromMSecsSinceStartOfDay(elapsedMsecs % milliSecondsInDay);
if (elapsedDays > 1) {
return QString("%1 days, %2:%3:%4").arg(elapsedDays).arg(elapsedTime.hour(), 2, 10, QLatin1Char('0')).arg(elapsedTime.minute(), 2, 10, QLatin1Char('0')).arg(elapsedTime.second(), 2, 10, QLatin1Char('0'));
} else if (elapsedDays == 1) {
return QString("%1 day, %2:%3:%4").arg(elapsedDays).arg(elapsedTime.hour(), 2, 10, QLatin1Char('0')).arg(elapsedTime.minute(), 2, 10, QLatin1Char('0')).arg(elapsedTime.second(), 2, 10, QLatin1Char('0'));
} else {
return QString("%1:%2:%3").arg(elapsedTime.hour(), 2, 10, QLatin1Char('0')).arg(elapsedTime.minute(), 2, 10, QLatin1Char('0')).arg(elapsedTime.second(), 2, 10, QLatin1Char('0'));
}
}
void SimulationViewWidget::Tick()
{
if (sim) {
sim->Tick();
}
}
void SimulationViewWidget::PaintPlant(QPainter& paint, const Plant& plant, bool selected)
{
plant.ForEachStem([&](const QLineF& stem, double thickness, bool hasLeaf, double leafSize)
{
QPen pen(selected ? Qt::white : QColor::fromRgb(73, 39, 14));
pen.setWidthF(std::max(1.0, selected ? (thickness * 1.5) : thickness));
paint.setPen(pen);
paint.drawLine(stem);
if (hasLeaf) {
paint.setPen(selected ? Qt::white : Qt::black);
paint.setBrush(plant.GetLeafColour());
double radius = (leafSize / 2) * plant.GetProportionGrown();
paint.drawEllipse(stem.p2(), radius, radius * 0.66);
}
});
}
void SimulationViewWidget::UpdateInfoModel()
{
QVector<SimulationInfoTableModel::TableRow> items;
if (sim) {
items.push_back({ "Simulation:",
"",
"",
});
items.push_back({ "Run Time",
ElapsedTimeString(sim->GetRuntime().elapsed()),
"The number of times the simulation loop has been run since it was created or reset.",
});
items.push_back({ "Tick Count",
QLocale::system().toString(sim->GetTickCount()),
"The number of times the simulation loop has been run since it was created or reset.",
});
items.push_back({ "Living Plants",
QLocale::system().toString(sim->GetLivingPlantCount()),
"The number of living plants currently being siumlated.",
});
items.push_back({ "Total Plants",
QLocale::system().toString(sim->GetTotalPlantCount()),
"The total number of plants to have lived in this simulation.",
});
util::RollingStatistics ageStats;
util::RollingStatistics heightStats;
for (const auto& plant : sim->GetPlants()) {
ageStats.AddValue(plant->GetAge());
heightStats.AddValue(plant->GetBounds().height());
}
items.push_back({ "Average Age",
QLocale::system().toString(ageStats.Mean(), 'f', 2),
"The average age of all plants in the simulation, where age is counted in simulation ticks.",
});
items.push_back({ "Average Height",
QLocale::system().toString(heightStats.Mean(), 'f', 2),
"The average height of all plants in the simulation.",
});
}
if (selectedPlant) {
if (sim) {
items.push_back({ "",
"",
"",
});
}
items.push_back({ "Selected Plant:",
"",
"",
});
items.push_back({ "Age",
QLocale::system().toString(selectedPlant->GetAge()),
"The number of simulation ticks this plant has lived for.",
});
items.push_back({ "Height",
QLocale::system().toString(selectedPlant->GetBounds().height(), 'f', 2),
"The height of the plant in the simulation.",
});
items.push_back({ "Energy",
QLocale::system().toString(selectedPlant->GetEnergy(), 'f', 2) + "j",
"The ammount of energy the plant currently has, it will die if this falls to zero.",
});
items.push_back({ "Metabolism",
QLocale::system().toString(selectedPlant->GetMetabolism(), 'f', 2) + "j",
"The ammount of energy the plant spends each tick to survive. A larger and more complex plant will have a larger metabolism when it germinates, and it will increase each tick.",
});
items.push_back({ "Percent Grown",
QLocale::system().toString(selectedPlant->GetProportionGrown() * 100, 'f', 1) + "%",
"When a plant germinates it is 0% grown, and will reach its full size at 100% grown.",
});
for (auto& gene : selectedPlant->GetGenetics()) {
items.push_back({ QString::fromStdString(gene->TypeName()),
gene->ToString(),
gene->Description(),
});
}
}
infoModel.UpdateAll(std::move(items));
}
void SimulationViewWidget::PerformMouseButtonAction(MouseButtonAction action, const QPointF& location)
{
switch (action) {
case MouseButtonAction::SelectPlant:
selectedPlant = sim->GetPlantAt(LocalToSimulation(location));
break;
case MouseButtonAction::AddPlantSeed:
emit onPlacePlantSeedRequested(LocalToSimulation(location).x());
break;
case MouseButtonAction::RemovePlants:
sim->RemovePlantsAt(LocalToSimulation(location));
break;
}
}
QPointF SimulationViewWidget::LocalToSimulation(const QPointF& localPoint) const
{
QPointF simPoint = localPoint;
simPoint.rx() += horizontalScrollBar()->value();
simPoint.setY(viewport()->height() - simPoint.y() - groundHeight);
return simPoint;
}