-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
80 lines (68 loc) · 2.38 KB
/
Copy pathmain.cpp
File metadata and controls
80 lines (68 loc) · 2.38 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
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <sstream>
#include <string>
// Helper to read file content
std::string loadShaderSource(const char* filename) {
std::ifstream file(filename);
if (!file.is_open()) {
std::cerr << "ERROR: Could not open shader file: " << filename << std::endl;
return "";
}
std::stringstream buffer;
buffer << file.rdbuf();
return buffer.str();
}
int main() {
// 1. Setup Hidden Window
if (!glfwInit()) return -1;
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
GLFWwindow* window = glfwCreateWindow(640, 480, "Hidden", NULL, NULL);
glfwMakeContextCurrent(window);
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) {
std::cout << "Failed to initialize GLAD" << std::endl;
return -1;
}
// 2. Load Shader from File
std::string sourceStr = loadShaderSource("compute.glsl");
if (sourceStr.empty()) return -1;
const char* sourceCStr = sourceStr.c_str();
// 3. Compile Shader
GLuint shader = glCreateShader(GL_COMPUTE_SHADER);
glShaderSource(shader, 1, &sourceCStr, NULL);
glCompileShader(shader);
// Check Errors
GLint success;
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
char infoLog[512];
glGetShaderInfoLog(shader, 512, NULL, infoLog);
std::cout << "Shader Error: " << infoLog << std::endl;
}
GLuint program = glCreateProgram();
glAttachShader(program, shader);
glLinkProgram(program);
glUseProgram(program);
// 4. Data & Buffers
std::vector<float> inputData = { 1.0f, 2.0f, 3.0f, 4.0f, 5.0f };
size_t dataSize = inputData.size() * sizeof(float);
GLuint ssbo;
glGenBuffers(1, &ssbo);
glBindBuffer(GL_SHADER_STORAGE_BUFFER, ssbo);
glBufferData(GL_SHADER_STORAGE_BUFFER, dataSize, inputData.data(), GL_DYNAMIC_COPY);
glBindBufferBase(GL_SHADER_STORAGE_BUFFER, 0, ssbo);
// 5. Dispatch
glDispatchCompute((GLuint)inputData.size(), 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);
// 6. Read Back
float* ptr = (float*)glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY);
std::cout << "Output: ";
for (int i = 0; i < inputData.size(); i++) std::cout << ptr[i] << " ";
std::cout << std::endl;
glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
glfwTerminate();
return 0;
}