Compare commits

..

2 Commits

Author SHA1 Message Date
burkkyy 9b1e7d56a3 Updates 2026-09-06 23:40:27 -07:00
burkkyy dc40e973d3 testbed update + triangle example new pattern 2026-09-06 23:39:17 -07:00
9 changed files with 398 additions and 24 deletions
+18 -2
View File
@@ -91,6 +91,19 @@ Shader::Builder& Shader::Builder::fromGLSL(const std::string& path) {
Shader::Builder& Shader::Builder::fromSPIRV(const std::string& path) { Shader::Builder& Shader::Builder::fromSPIRV(const std::string& path) {
this->path = path; this->path = path;
this->precompiled = true; this->precompiled = true;
this->embedded = false;
return *this;
}
Shader::Builder& Shader::Builder::fromSPIRV(std::vector<u32> spirv) {
this->embeddedSpirv = std::move(spirv);
this->embedded = true;
return *this;
}
Shader::Builder& Shader::Builder::fromSPIRV(std::span<const u32> spirv) {
this->embeddedSpirv.assign(spirv.begin(), spirv.end());
this->embedded = true;
return *this; return *this;
} }
@@ -101,7 +114,7 @@ Shader::Builder& Shader::Builder::setStage(ShaderStage shaderStage) {
} }
std::unique_ptr<Shader> Shader::Builder::build() { std::unique_ptr<Shader> Shader::Builder::build() {
if (this->path.empty()) { if (!this->embedded && this->path.empty()) {
log::fatal("failed to build shader: no source path provided"); log::fatal("failed to build shader: no source path provided");
throw std::runtime_error("failed to build shader: no source path provided"); throw std::runtime_error("failed to build shader: no source path provided");
} }
@@ -113,7 +126,10 @@ std::unique_ptr<Shader> Shader::Builder::build() {
auto shader = std::unique_ptr<Shader>(new Shader()); auto shader = std::unique_ptr<Shader>(new Shader());
if (this->precompiled) { if (this->embedded) {
shader->stage = this->stage;
shader->spirv = std::move(this->embeddedSpirv);
} else if (this->precompiled) {
shader->load(this->path, this->stage); shader->load(this->path, this->stage);
} else { } else {
shader->compile(this->path, this->stage); shader->compile(this->path, this->stage);
+5
View File
@@ -2,6 +2,7 @@
#include <memory> #include <memory>
#include <sophia/types.hpp> #include <sophia/types.hpp>
#include <span>
#include <string> #include <string>
#include <vector> #include <vector>
@@ -37,15 +38,19 @@ class Shader::Builder {
Builder& fromGLSL(const std::string& path); Builder& fromGLSL(const std::string& path);
Builder& fromSPIRV(const std::string& path); Builder& fromSPIRV(const std::string& path);
Builder& fromSPIRV(std::vector<u32> spirv);
Builder& fromSPIRV(std::span<const u32> spirv);
Builder& setStage(ShaderStage shaderStage); Builder& setStage(ShaderStage shaderStage);
std::unique_ptr<Shader> build(); std::unique_ptr<Shader> build();
private: private:
std::string path; std::string path;
std::vector<u32> embeddedSpirv;
ShaderStage stage; ShaderStage stage;
bool stageSet = false; bool stageSet = false;
bool precompiled = false; bool precompiled = false;
bool embedded = false;
}; };
} // namespace sophia } // namespace sophia
+18
View File
@@ -0,0 +1,18 @@
#version 450
layout (location = 0) out vec2 uv;
vec2 positions[6] = vec2[](
vec2(-1.0, -1.0),
vec2( 1.0, -1.0),
vec2(-1.0, 1.0),
vec2(-1.0, 1.0),
vec2( 1.0, -1.0),
vec2( 1.0, 1.0)
);
void main() {
vec2 pos = positions[gl_VertexIndex];
gl_Position = vec4(pos, 0.0, 1.0);
uv = pos * 0.5 + 0.5;
}
@@ -0,0 +1,9 @@
#version 450
layout (location = 0) in vec3 fragColor;
layout (location = 0) out vec4 outColor;
void main() {
outColor = vec4(fragColor, 1.0);
}
@@ -0,0 +1,16 @@
#version 450
layout (location = 0) in vec2 position;
layout (location = 1) in vec3 color;
layout (location = 0) out vec3 fragColor;
layout (push_constant) uniform Push {
mat4 transform;
vec4 color;
} push;
void main() {
gl_Position = vec4(push.transform * vec4(position, 0.0, 1.0));
fragColor = color;
}
@@ -0,0 +1,88 @@
#include "model_render_system.hpp"
#include <cassert>
#include "shaders/model_render_system.frag.spv.h"
#include "shaders/model_render_system.vert.spv.h"
namespace sophia {
ModelRenderSystem::ModelRenderSystem(Device& device,
RenderContext& renderContext)
: device{device}, renderContext{renderContext} {
createPipelineLayout();
assert(this->pipelineLayout.get() != nullptr &&
"Cannot create pipeline before pipeline layout");
auto vertexShader = Shader::Builder()
.fromSPIRV(shaders::model_render_system_vert_spv)
.setStage(ShaderStage::VERTEX)
.build();
auto fragmentShader = Shader::Builder()
.fromSPIRV(shaders::model_render_system_frag_spv)
.setStage(ShaderStage::FRAGMENT)
.build();
auto bindingDescriptions = Model::Vertex::getBindingDescriptions();
auto attributeDescriptions = Model::Vertex::getAttributeDescriptions();
this->graphicsPipeline =
GraphicsPipeline::Builder(device)
.setVertexShader(*vertexShader)
.setFragmentShader(*fragmentShader)
.setPipelineLayout(pipelineLayout.get())
.setColorAttachmentFormats({renderContext.getImageFormat()})
.setVertexInput(bindingDescriptions, attributeDescriptions)
.build();
}
ModelRenderSystem::~ModelRenderSystem() {
log::trace("destroyed sophia::ModelRenderSystem");
}
void ModelRenderSystem::render(vk::CommandBuffer commandBuffer,
std::span<const std::unique_ptr<Model>> models,
const FrameInfo& frameInfo) {
glm::mat4 viewProjection = frameInfo.camera.getViewProjection();
this->graphicsPipeline->bind(commandBuffer);
for (const std::unique_ptr<Model>& model : models) {
PushConstantData push{};
push.modelMatrix = viewProjection;
commandBuffer.pushConstants(
this->pipelineLayout.get(),
vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment,
0, sizeof(PushConstantData), &push);
model->bind(commandBuffer);
model->draw(commandBuffer);
}
}
void ModelRenderSystem::createPipelineLayout() {
vk::PushConstantRange pushConstantRange{};
pushConstantRange.stageFlags =
vk::ShaderStageFlagBits::eVertex | vk::ShaderStageFlagBits::eFragment;
pushConstantRange.offset = 0;
pushConstantRange.size = sizeof(PushConstantData);
vk::PipelineLayoutCreateInfo pipelineLayoutInfo = {};
pipelineLayoutInfo.setLayoutCount = 0;
pipelineLayoutInfo.pushConstantRangeCount = 1;
pipelineLayoutInfo.pPushConstantRanges = &pushConstantRange;
try {
this->pipelineLayout =
this->device.get()->createPipelineLayoutUnique(pipelineLayoutInfo);
log::trace("created vk::PipelineLayout");
} catch (const vk::SystemError& err) {
log::fatal("failed to create vk::PipelineLayout");
throw std::runtime_error("failed to create vk::PipelineLayout");
}
}
} // namespace sophia
@@ -0,0 +1,42 @@
#pragma once
#include <memory>
#include <sophia/frame_info.hpp>
#include <span>
#include "device.hpp"
#include "model.hpp"
#include "pipelines/graphics_pipeline.hpp"
#include "render_context.hpp"
namespace sophia {
class ModelRenderSystem {
public:
struct PushConstantData {
glm::mat4 modelMatrix{1.f};
glm::mat4 normalMatrix{1.f};
};
ModelRenderSystem(const ModelRenderSystem&) = delete;
ModelRenderSystem& operator=(const ModelRenderSystem&) = delete;
ModelRenderSystem(Device& device, RenderContext& renderContext);
~ModelRenderSystem();
void render(vk::CommandBuffer commandBuffer,
std::span<const std::unique_ptr<Model>> models,
const FrameInfo& frameInfo);
private:
void createPipelineLayout();
void createPipeline();
Device& device;
RenderContext& renderContext;
std::unique_ptr<sophia::GraphicsPipeline> graphicsPipeline;
vk::UniquePipelineLayout pipelineLayout;
};
} // namespace sophia
+10 -5
View File
@@ -1,9 +1,14 @@
#include <iostream>
#include <sophia/application.hpp> #include <sophia/application.hpp>
int main() { class ExampleTriangle : public sophia::Application {
sophia::Application app{{.width = 800, .height = 600, .name = "Triangle"}}; public:
ExampleTriangle()
: Application{{.width = 800, .height = 600, .name = "ExampleTriangle"}} {}
app.run(); void onCreate() override {
canvas.triangle({0.0f, -200.0f}, {100.0f, 0.0f}, {-100.0f, 0.0f});
return EXIT_SUCCESS;
} }
};
SOPHIA_MAIN(ExampleTriangle)
+191 -16
View File
@@ -1,25 +1,200 @@
#include <cmath>
#include <iostream> #include <iostream>
// #include <sophia/application.hpp> #include <random>
#include <sophia/render_triangle_test.hpp> #include <sophia/application.hpp>
#include <sophia/event.hpp>
#include <sophia/key_event.hpp>
#include <stdexcept> #include <stdexcept>
#include <string>
#include <vector>
int main(int argc, const char** argv) { #define GLM_FORCE_RADIANS
(void)argc; #define GLM_FORCE_DEPTH_ZERO_TO_ONE
(void)argv; #include <glm/glm.hpp>
std::cout << __FILE__ << "::" << __LINE__ << '\n'; #include <glm/gtc/constants.hpp>
try { struct Boid {
sophia::runRenderTriangleTest(TESTBED_SHADER_DIR "/triangle.vert", glm::vec2 position;
TESTBED_SHADER_DIR "/triangle.frag"); glm::vec2 velocity;
} catch (const std::exception& error) { };
std::cerr << "Render triangle test failed: " << error.what() << '\n';
return EXIT_FAILURE; constexpr uint32_t DEFAULT_NUMBER_OF_BOIDS = 25;
class Testbed : public sophia::Application {
public:
static constexpr float SCROLL_SPEED = 200.0f;
// World is a fixed box independent of the camera; boids wrap at its edges.
static constexpr float WORLD_HALF_WIDTH = 375.0f;
static constexpr float WORLD_HALF_HEIGHT = 500.0f;
static constexpr float MAX_SPEED = 120.0f;
static constexpr float MAX_FORCE = 200.0f;
static constexpr float PERCEPTION_RADIUS = 150.0f;
static constexpr float SEPARATION_RADIUS = 40.0f;
static constexpr float ALIGNMENT_WEIGHT = 1.0f;
static constexpr float COHESION_WEIGHT = 1.0f;
static constexpr float SEPARATION_WEIGHT = 1.5f;
Testbed() : Application{{.width = 750, .height = 1000, .name = "Testbed"}} {
uint32_t numberOfBoids = DEFAULT_NUMBER_OF_BOIDS;
if (args.size() > 1) {
numberOfBoids = static_cast<uint32_t>(std::stoul(args[1]));
}
boids.resize(numberOfBoids);
sophia::EventSystem::get().addListener<sophia::KeyPressedEvent>(
[this](sophia::KeyPressedEvent& e) {
setScrollKeyHeld(e.getKeyCode(), true);
});
sophia::EventSystem::get().addListener<sophia::KeyReleasedEvent>(
[this](sophia::KeyReleasedEvent& e) {
setScrollKeyHeld(e.getKeyCode(), false);
});
} }
// sophia::Application app{ void onCreate() override {
// {.width = 750, .height = 1000, .name = "Testbed", .headless = true}}; std::cout << "Testbed created" << std::endl;
// app.run(); std::mt19937 rng{std::random_device{}()};
std::uniform_real_distribution<float> posX{-WORLD_HALF_WIDTH,
WORLD_HALF_WIDTH};
std::uniform_real_distribution<float> posY{-WORLD_HALF_HEIGHT,
WORLD_HALF_HEIGHT};
std::uniform_real_distribution<float> angle{0.0f, glm::two_pi<float>()};
return EXIT_SUCCESS; for (Boid& boid : boids) {
boid.position = {posX(rng), posY(rng)};
float theta = angle(rng);
boid.velocity = glm::vec2{std::cos(theta), std::sin(theta)} * MAX_SPEED;
} }
}
void onUpdate(const sophia::FrameInfo& frameInfo) override {
float scrollDistance =
SCROLL_SPEED * static_cast<float>(frameInfo.deltaTime);
if (scrollLeft) camera.position.x -= scrollDistance;
if (scrollRight) camera.position.x += scrollDistance;
if (scrollUp) camera.position.y -= scrollDistance;
if (scrollDown) camera.position.y += scrollDistance;
updateBoids(static_cast<float>(frameInfo.deltaTime));
canvas.clear();
for (const Boid& boid : boids) {
drawBoid(boid);
}
}
private:
void updateBoids(float deltaTime) {
std::vector<glm::vec2> accelerations(boids.size());
for (size_t i = 0; i < boids.size(); ++i) {
glm::vec2 separation{0.0f};
glm::vec2 averageVelocity{0.0f};
glm::vec2 averagePosition{0.0f};
int neighborCount = 0;
for (size_t j = 0; j < boids.size(); ++j) {
if (i == j) continue;
glm::vec2 offset = boids[i].position - boids[j].position;
float dist = glm::length(offset);
if (dist >= PERCEPTION_RADIUS) continue;
averageVelocity += boids[j].velocity;
averagePosition += boids[j].position;
++neighborCount;
if (dist > 0.0f && dist < SEPARATION_RADIUS) {
separation += offset / (dist * dist);
}
}
glm::vec2 acceleration =
steerTowards(boids[i], separation) * SEPARATION_WEIGHT;
if (neighborCount > 0) {
averageVelocity /= static_cast<float>(neighborCount);
acceleration +=
steerTowards(boids[i], averageVelocity) * ALIGNMENT_WEIGHT;
averagePosition /= static_cast<float>(neighborCount);
glm::vec2 towardsGroup = averagePosition - boids[i].position;
acceleration += steerTowards(boids[i], towardsGroup) * COHESION_WEIGHT;
}
accelerations[i] = acceleration;
}
for (size_t i = 0; i < boids.size(); ++i) {
Boid& boid = boids[i];
boid.velocity += accelerations[i] * deltaTime;
float speed = glm::length(boid.velocity);
if (speed > MAX_SPEED) {
boid.velocity = boid.velocity / speed * MAX_SPEED;
}
boid.position += boid.velocity * deltaTime;
wrapPosition(boid.position);
}
}
// Steers boid towards desiredDirection at up to MAX_SPEED, clamped to
// MAX_FORCE.
glm::vec2 steerTowards(const Boid& boid, glm::vec2 desiredDirection) {
float directionLength = glm::length(desiredDirection);
if (directionLength < 1e-5f) return glm::vec2{0.0f};
glm::vec2 desired = desiredDirection / directionLength * MAX_SPEED;
glm::vec2 steer = desired - boid.velocity;
float steerLength = glm::length(steer);
if (steerLength > MAX_FORCE) {
steer = steer / steerLength * MAX_FORCE;
}
return steer;
}
void wrapPosition(glm::vec2& position) {
if (position.x > WORLD_HALF_WIDTH) position.x = -WORLD_HALF_WIDTH;
if (position.x < -WORLD_HALF_WIDTH) position.x = WORLD_HALF_WIDTH;
if (position.y > WORLD_HALF_HEIGHT) position.y = -WORLD_HALF_HEIGHT;
if (position.y < -WORLD_HALF_HEIGHT) position.y = WORLD_HALF_HEIGHT;
}
void drawBoid(const Boid& boid) {
constexpr float LENGTH = 20.0f;
constexpr float WIDTH = 12.0f;
glm::vec2 direction = boid.velocity;
float speed = glm::length(direction);
direction = speed > 1e-5f ? direction / speed : glm::vec2{0.0f, -1.0f};
glm::vec2 perpendicular{-direction.y, direction.x};
glm::vec2 nose = boid.position + direction * (LENGTH * 0.5f);
glm::vec2 tailLeft = boid.position - direction * (LENGTH * 0.5f) +
perpendicular * (WIDTH * 0.5f);
glm::vec2 tailRight = boid.position - direction * (LENGTH * 0.5f) -
perpendicular * (WIDTH * 0.5f);
canvas.triangle(nose, tailLeft, tailRight, {1.0f, 1.0f, 1.0f});
}
void setScrollKeyHeld(sophia::KeyCode keycode, bool held) {
if (keycode == sophia::Key::Left) scrollLeft = held;
if (keycode == sophia::Key::Right) scrollRight = held;
if (keycode == sophia::Key::Up) scrollUp = held;
if (keycode == sophia::Key::Down) scrollDown = held;
}
std::vector<Boid> boids;
bool scrollLeft = false;
bool scrollRight = false;
bool scrollUp = false;
bool scrollDown = false;
};
SOPHIA_MAIN(Testbed)