raycasting/level.cpp

103 lines
2.2 KiB
C++
Raw Normal View History

#include "level.h"
#include <stdio.h>
#define WIDTH 5
#define HEIGHT 5
static void drawGrid();
2023-04-01 05:56:26 +08:00
static void drawGridLine(unsigned int step, bool isHorizontal);
static sf::Vertex getGridLineVertex(unsigned int n, unsigned int maxDimension, bool isStart, bool isHorizontal);
static sf::RenderWindow* window = nullptr;
static unsigned int level[WIDTH * HEIGHT] = {
1, 1, 1, 1, 1,
1, 0, 0, 0, 0,
1, 0, 1, 0, 1,
1, 0, 0, 0, 0,
1, 0, 1, 0, 1,
};
int level_init(sf::RenderWindow* renderWindow)
{
printf("level_init()\n");
window = renderWindow;
return 1;
}
int level_update()
{
if (!window) return 0;
drawGrid();
return 1;
}
void level_end()
{
printf("level_end()\n");
return;
}
float level_rayCastDistance(sf::Vector2f point, float direction)
{
return 100.f;
}
static void drawGrid()
{
const sf::Vector2u windowSize = window->getSize();
2023-04-01 05:56:26 +08:00
unsigned int stepX = windowSize.x/WIDTH;
unsigned int stepY = windowSize.y/HEIGHT;
for (unsigned int x = 0; x < WIDTH; x++) {
2023-04-01 05:56:26 +08:00
for (unsigned int y = 0; y < HEIGHT; y++) {
if (!level[y * HEIGHT + x]) continue;
2023-04-02 07:41:16 +08:00
sf::RectangleShape rectangle(sf::Vector2f(stepY, stepY));
rectangle.setPosition(x * stepX, y * stepY);
2023-04-01 05:56:26 +08:00
window->draw(rectangle);
}
}
2023-04-02 07:41:16 +08:00
drawGridLine(stepX, true);
drawGridLine(stepY, false);
2023-04-01 05:56:26 +08:00
}
static void drawGridLine(unsigned int step, bool isHorizontal)
{
unsigned int lines = isHorizontal? WIDTH : HEIGHT;
2023-04-01 05:56:26 +08:00
for (unsigned int n = 0; n < lines; n++) {
if (n == 0) continue;
unsigned int offset = n * step;
unsigned int maxDimension = lines * step;
sf::Vertex line[] =
{
2023-04-01 05:56:26 +08:00
getGridLineVertex(offset, maxDimension, true, isHorizontal),
getGridLineVertex(offset, maxDimension, false, isHorizontal)
};
window->draw(line, 2, sf::Lines);
}
2023-04-01 05:56:26 +08:00
}
2023-04-01 05:56:26 +08:00
static sf::Vertex getGridLineVertex(unsigned int offset, unsigned int maxDimension, bool isStart, bool isHorizontal)
{
sf::Vertex start;
sf::Vertex end;
2023-04-01 05:56:26 +08:00
if (isHorizontal) {
start = sf::Vertex(sf::Vector2f(offset, 0));
end = sf::Vertex(sf::Vector2f(offset, maxDimension));
}
2023-04-01 05:56:26 +08:00
else {
start = sf::Vertex(sf::Vector2f(0, offset));
end = sf::Vertex(sf::Vector2f(maxDimension, offset));
}
2023-04-02 07:41:16 +08:00
start.color = sf::Color(100, 100, 100);
end.color = sf::Color(100, 100, 100);
2023-04-01 05:56:26 +08:00
return isStart? start : end;
}