Skip to content

Commit 10bb0b2

Browse files
committed
Оптимизация игры. Увеличил производительность примерно на 20-25% небольшие визуальные обновления
1 parent d35a39d commit 10bb0b2

14 files changed

+107
-19
lines changed

.github/preview_image2.png

75.7 KB
Loading

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,8 @@ git push origin v1.0.0
121121
- **./rendering**: Код, связанный с рендерингом
122122
- `Camera.h`, `Camera.cpp` - Управление камерой для 3D вида
123123
- `Renderer.h`, `Renderer.cpp` - Логика рендеринга в OpenGL
124+
- `CellInstance.h` - Структура для хранения инстанса дивых и мертвых клеток для оптимальной отрисовки в OpenGL
125+
- `ICellInstanceProvider.h` - Проводник обеспечивающий обмен данными между разными классами. Это простой интерфейс, паттерн провайдер.
124126

125127
- **./mathematics**: Математические утилиты
126128
- `Matrix4x4.h`, `Matrix4x4.cpp` - Операции с матрицами (на данный момент не используется)

game/GameController.cpp

+15-3
Original file line numberDiff line numberDiff line change
@@ -38,9 +38,11 @@ void GameController::placePattern(int startX, int startY, const Pattern& pattern
3838
grid.setCellState(startX + (patternWidth - 1 - x), startY + (patternHeight - 1 - y), pattern[y][x]);
3939
if (pattern[y][x]) {
4040
grid.getCell(startX + (patternWidth - 1 - x), startY + (patternHeight - 1 - y)).setColor(Vector3d(0.5f, 0.9f, 0.5f));
41+
gameOfLife.SetCellColor(startX + (patternWidth - 1 - x), startY + (patternHeight - 1 - y), Vector3d(0.5f, 0.9f, 0.5f));
4142
}
4243
else {
4344
grid.getCell(startX + (patternWidth - 1 - x), startY + (patternHeight - 1 - y)).setColor(Vector3d(0.1f, 0.1f, 0.1f));
45+
gameOfLife.SetCellColor(startX + (patternWidth - 1 - x), startY + (patternHeight - 1 - y), Vector3d(0.1f, 0.1f, 0.1f));
4446
}
4547

4648
}
@@ -62,10 +64,12 @@ void GameController::randomizeGrid(float density) {
6264
if (dis(gen) < density) {
6365
grid.setCellState(x, y, true);
6466
grid.getCell(x, y).setColor(Vector3d(0.0f, 0.6f, 0.0f));
67+
gameOfLife.SetCellColor(x, y, Vector3d(0.0f, 0.6f, 0.0f));
6568
}
6669
else {
6770
grid.setCellState(x, y, false);
6871
grid.getCell(x, y).setColor(Vector3d(0.0f, 0.0f, 0.0f));
72+
gameOfLife.SetCellColor(x, y, Vector3d(0.0f, 0.0f, 0.0f));
6973
}
7074
//float r = static_cast<float>(rand()) / RAND_MAX;
7175
//float g = static_cast<float>(rand()) / RAND_MAX;
@@ -81,6 +85,7 @@ void GameController::clearGrid() {
8185
for (int x = 0; x < grid.getWidth(); ++x) {
8286
grid.setCellState(x, y, false); // Óñòàíàâëèâàåì êàæäóþ êëåòêó â ìåðòâîå ñîñòîÿíèå
8387
grid.getCell(x, y).setColor(Vector3d(0.0f, 0.0f, 0.0f));
88+
gameOfLife.SetCellColor(x, y, Vector3d(0.0f, 0.0f, 0.0f));
8489
}
8590
}
8691
}
@@ -112,6 +117,7 @@ void GameController::previousGeneration() {
112117
if (isRunning) return;
113118
gameOfLife.previousGeneration();
114119
}
120+
115121
bool GameController::isSimulationRunning() const {
116122
return isRunning;
117123
}
@@ -121,10 +127,12 @@ void GameController::toggleCellState(int x, int y) {
121127
bool currentState = grid.getCellState(x, y);
122128
grid.setCellState(x, y, !currentState);
123129
if (!currentState) {
124-
grid.getCell(x, y).setColor(Vector3d(0.1f, 0.4f, 0.1f));
130+
//grid.getCell(x, y).setColor(Vector3d(0.1f, 0.4f, 0.1f));
131+
gameOfLife.SetCellColor(x, y, Vector3d(0.1f, 0.4f, 0.1f));
125132
}
126133
else {
127-
grid.getCell(x, y).setColor(Vector3d(0.0f, 0.0f, 0.0f));
134+
//grid.getCell(x, y).setColor(Vector3d(0.0f, 0.0f, 0.0f));
135+
gameOfLife.SetCellColor(x, y, Vector3d(0.0f, 0.0f, 0.0f));
128136
}
129137

130138
}
@@ -183,9 +191,11 @@ void GameController::setCurrentPattern(int patternNumber) {
183191
break;
184192
}
185193
}
194+
186195
void GameController::setCurrentPatternRotator(int patternRotator) {
187196
currentPatternRotator = patternRotator;
188197
}
198+
189199
void GameController::PlacePattern(int startX, int startY) {
190200
if (isRunning) return;
191201

@@ -265,4 +275,6 @@ Pattern GameController::rotateOrFlip(const Pattern& pattern, Rotation rotation)
265275
}
266276

267277
return result;
268-
}
278+
}
279+
280+

game/GameController.h

+6-3
Original file line numberDiff line numberDiff line change
@@ -5,15 +5,15 @@
55
#include "GameOfLife.h"
66
#include "Grid.h"
77
#include "GameStateManager.h"
8+
//#include "../rendering/ICellInstanceProvider.h"
9+
810
#include <random> // Äëÿ ãåíåðàöèè ñëó÷àéíûõ ÷èñåë
911
#include <string>
1012
#include <fstream>
1113
#include <sstream>
1214
#include <vector>
1315
#include <array>
1416

15-
16-
1717
// Îïðåäåëèì òèï ôèãóðû êàê äâóìåðíûé ìàññèâ
1818
using Pattern = std::vector<std::vector<bool>>;
1919

@@ -130,7 +130,10 @@ class GameController {
130130
bool saveGameStateCSV(const std::string& filename) const {
131131
return GameStateManager::saveGameStateCSV(grid, filename);
132132
}
133-
134133
Pattern rotateOrFlip(const Pattern& pattern, Rotation rotation);
134+
135+
void SetCellInstanceProvider(ICellInstanceProvider* provider) {
136+
gameOfLife.SetCellProvider(provider); // Ïåðåäàåì ïðîâàéäåðà â GameOfLife
137+
}
135138
};
136139
#endif // GAMECONTROLLER_H_

game/GameOfLife.cpp

+25-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
#include "GameOfLife.h"
22

33
GameOfLife::GameOfLife(Grid& g) : grid(g), nextGrid(g.getWidth(), g.getHeight()),
4-
gpuAutomaton(g.getWidth(), g.getHeight()), isToroidal(true), isGpuSimulated(true)
4+
gpuAutomaton(g.getWidth(), g.getHeight()), isToroidal(true), isGpuSimulated(true),
5+
cellInstances(nullptr),cellProvider(nullptr)
56
{
67
gpuAutomaton.SetToroidal(isToroidal); // Óñòàíîâêà isToroidal
78
}
@@ -129,10 +130,33 @@ void GameOfLife::nextGenerationGPU() {
129130
if (bc < 0) bc = 0.0f;
130131
cell.setColor(Vector3d(rc, bc, gc));
131132
}
133+
134+
SetCellColor(x, y, cell.getColor());
135+
136+
}
137+
}
138+
}
139+
140+
void GameOfLife::SetCellColor(int x, int y, const Vector3d& color) {
141+
if (cellProvider && cellInstances) {
142+
int GW = grid.getWidth();
143+
int index = y * GW + x;
144+
if (index < cellInstances->size()) {
145+
(*cellInstances)[index].color = color;
132146
}
133147
}
134148
}
135149

150+
void GameOfLife::SetCellProvider(const ICellInstanceProvider* provider) {
151+
cellProvider = provider;
152+
if (cellProvider) {
153+
cellInstances = &const_cast<std::vector<CellInstance>&>(cellProvider->GetCellInstances());
154+
}
155+
else {
156+
cellInstances = nullptr;
157+
}
158+
}
159+
136160
void GameOfLife::nextGenerationCPU() {
137161
//saveCurrentState(); // Ñîõðàíÿåì òåêóùåå ñîñòîÿíèå
138162
int neighbors;

game/GameOfLife.h

+9
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@
33
#define GAMEOFLIFE_H
44

55
#include "GPUAutomaton.h"
6+
#include "../rendering/ICellInstanceProvider.h"
7+
68
#include "Grid.h"
79
#include <vector>
810
#include <future>
@@ -17,6 +19,10 @@ class GameOfLife {
1719
bool getWoldToroidal() const { return isToroidal; };
1820

1921
void updateGridReference(Grid& newGrid) { grid = newGrid; } // ìåòîä äëÿ îáíîâëåíèÿ ññûëêè
22+
23+
void SetCellProvider(const ICellInstanceProvider* provider);
24+
25+
void SetCellColor(int x, int y, const Vector3d& color);
2026
private:
2127
Grid& grid;
2228
Grid nextGrid; // Äîáàâëÿåì nextGrid äëÿ äâîéíîãî áóôåðà
@@ -26,6 +32,9 @@ class GameOfLife {
2632
bool isToroidal;
2733
bool isGpuSimulated;
2834

35+
std::vector<CellInstance>* cellInstances;
36+
const ICellInstanceProvider* cellProvider;
37+
2938
void nextGenerationGPU();
3039
void nextGenerationCPU();
3140

life.vcxproj

+2
Original file line numberDiff line numberDiff line change
@@ -184,7 +184,9 @@
184184
<ClInclude Include="mathematics\Matrix4x4.h" />
185185
<ClInclude Include="mathematics\Vector3d.h" />
186186
<ClInclude Include="rendering\Camera.h" />
187+
<ClInclude Include="rendering\CellInstance.h" />
187188
<ClInclude Include="rendering\CubeRenderer.h" />
189+
<ClInclude Include="rendering\ICellInstanceProvider.h" />
188190
<ClInclude Include="rendering\Renderer.h" />
189191
<ClInclude Include="rendering\UIController.h" />
190192
<ClInclude Include="res\resource.h" />

life.vcxproj.filters

+6
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,12 @@
148148
<ClInclude Include="rendering\CubeRenderer.h">
149149
<Filter>rendering</Filter>
150150
</ClInclude>
151+
<ClInclude Include="rendering\ICellInstanceProvider.h">
152+
<Filter>rendering</Filter>
153+
</ClInclude>
154+
<ClInclude Include="rendering\CellInstance.h">
155+
<Filter>rendering</Filter>
156+
</ClInclude>
151157
</ItemGroup>
152158
<ItemGroup>
153159
<Filter Include="game">

main.cpp

+2
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,7 @@ int wWinMain(
178178

179179
Renderer renderer(width, height);
180180
renderer.SetGameController(&gameController);
181+
gameController.SetCellInstanceProvider(&renderer);
181182

182183
// Передаем один и тот же экземпляр gameController в WindowController
183184
WindowController controller(&mainWindow, &renderer, &gameController);
@@ -208,6 +209,7 @@ int wWinMain(
208209

209210
// Здесь вызываем update с deltaTime
210211
gameController.update(deltaTime.count()); // .count() возвращает значение в секундах как float
212+
211213
renderer.Draw();
212214
}
213215

mathematics/Vector3d.h

+8-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,14 @@ class Vector3d {
1616
Vector3d operator-(const Vector3d& other) const;
1717
Vector3d operator*(float scalar) const;
1818
Vector3d operator/(float scalar) const;
19-
19+
//Vector3d& operator=(const Vector3d& other) {
20+
// if (this != &other) { // çàùèòà îò ñàìîïðèñâàèâàíèÿ
21+
// x = other.x;
22+
// y = other.y;
23+
// z = other.z;
24+
// }
25+
// return *this;
26+
//}
2027
// Ìåòîäû
2128
float length() const;
2229
Vector3d normalize() const;

rendering/CellInstance.h

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
#include "../mathematics/Vector3d.h"
2+
3+
struct CellInstance {
4+
float x, y; // Ïîçèöèÿ êëåòêè
5+
Vector3d color; // Öâåò êëåòêè
6+
};

rendering/ICellInstanceProvider.h

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#pragma once
2+
#include <vector>
3+
//#include "Renderer.h"
4+
#include "CellInstance.h" // Включаем определение CellInstance
5+
6+
class ICellInstanceProvider {
7+
public:
8+
virtual ~ICellInstanceProvider() = default;
9+
virtual const std::vector<CellInstance> &GetCellInstances() const = 0;
10+
};

rendering/Renderer.cpp

+6-6
Original file line numberDiff line numberDiff line change
@@ -242,12 +242,12 @@ void Renderer::DrawCells() {
242242
if (!pGameController) return;
243243
int GW = pGameController->getGridWidth();
244244
// Îáíîâëÿåì äàííûå î êëåòêàõ
245-
for (size_t i = 0; i < cellInstances.size(); ++i) {
246-
int x = i % GW;
247-
int y = i / GW;
248-
Cell cell = pGameController->getGrid().getCell(x, y);
249-
cellInstances[i].color = cell.getColor(); // Îáíîâëÿåì òîëüêî öâåò
250-
}
245+
//for (size_t i = 0; i < cellInstances.size(); ++i) {
246+
// int x = i % GW;
247+
// int y = i / GW;
248+
// Cell cell = pGameController->getGrid().getCell(x, y);
249+
// cellInstances[i].color = cell.getColor(); // Îáíîâëÿåì òîëüêî öâåò
250+
//}
251251
// Ïðèâÿçûâàåì VAO ïåðåä íàñòðîéêîé àòðèáóòîâ
252252
GL_CHECK(glBindVertexArray(cellsVAO));
253253

rendering/Renderer.h

+10-5
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
#include "Camera.h"
77
#include "UIController.h"
88
#include "../game/GameController.h"
9+
#include "ICellInstanceProvider.h"
910

1011
#include "CubeRenderer.h"
1112

@@ -16,7 +17,7 @@
1617
#include "imgui_impl_opengl3.h"
1718
#include "imgui_impl_win32.h"
1819

19-
class Renderer {
20+
class Renderer : public ICellInstanceProvider {
2021
public:
2122
Renderer(int width, int height);
2223
~Renderer();
@@ -34,6 +35,14 @@ class Renderer {
3435

3536
void DrawCubes();
3637

38+
// Ãåòòåð äëÿ cellInstances
39+
const std::vector<CellInstance> &GetCellInstances() const override {
40+
return cellInstances;
41+
}
42+
43+
// Ñåòòåð äëÿ cellInstances
44+
void SetCellInstances(const std::vector<CellInstance>& instances) { cellInstances = instances; }
45+
3746
private:
3847
int width, height;
3948
Camera camera;
@@ -53,10 +62,6 @@ class Renderer {
5362
GLuint cellsVAO;
5463

5564
std::vector<GLfloat> gridVertices;
56-
struct CellInstance {
57-
float x, y; // Ïîçèöèÿ êëåòêè
58-
Vector3d color; // Öâåò êëåòêè
59-
};
6065
GLuint cellInstanceVBO;
6166
std::vector<CellInstance> cellInstances;
6267

0 commit comments

Comments
 (0)