Skip to content

Commit 1d123a6

Browse files
committed
Automated interpreter shader creation
1 parent 48d08fc commit 1d123a6

10 files changed

Lines changed: 112 additions & 567 deletions

File tree

‎devlog.md‎

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,22 @@
1-
Shorter devlog - nothing too fancy going on here!
1+
Unfortunately, it's time to do our laundry.
22

3-
Most of the plotter-related features are already implemented, the only "math-y" thing missing being a few elementary functions, and some non-elementary functions that are convenient (like Lambert-W and the Zeta function). This means that we steer into the bane of every project's existence: making it usable!
3+
With 3D rendering complete, all of the essential features of the _plotter_ are done. This means that, had we wanted to, we could ship this as a fully-fledged math engine and leave the job of actually turning it into an application to someone else. But we can't be doing that! Therefore, it's time for us to start making way to shipping the project.
44

5-
I plan on shipping this project as a single executable rather than a zipped folder, and later compiling it into web assembly for a demo. In either case, we can't work with files, because browsers don't have file systems in the traditional sense. Virtual file systems _do_ exist, but there is a much simpler solution: turning files into strings!
6-
Now, this could be done by simply embedding a string like `const std::string vertex_source = R"({our code})"`, but if we wrote code this way, we lose our syntax highlighting and linting! The only solution is to create these strings dynamically at build-time.
5+
First of all, I wanted this plotter to be complete, meaning that it implements _every_ elementary function (those being, in simple terms, a set of well-behaved functions that mathematicians use). This is simply a manner of writing the already existing real and imaginary components of these functions (and their derivatives), which are well-known and defined.
6+
Is this essentially just writing boilerplate? Yes! Thankfully, this is not my first rodeo implementing these functions, so I could port a good amount of code from an old project. This is all done now: all elementary functions and their derivatives have been implemented!
77

8-
And that's pretty much it! We just now refactor any file access we wanted to use our `get_source` function, that secretely fetches the built string in compile-time if it's known.
8+
Now, for the engine-specific things: so far we have been writing shaders into files and reading them at runtime. This works, but adds unnecesary file I/O operations, and makes it impossible to port our entire project as one .exe file. So we had to remove that!
9+
One way to do this would be by writing our GLSL code in strings, but this removes linting. Instead, I implemented a dynamic source string builder at build time.
10+
11+
Attached, the new functions!
12+
13+
14+
**Related Commits**
15+
16+
[Commit 7923ee3](https://url.jam06452.uk/1vzsu0m): File conversion to strings at build-time
17+
[Commit 5ba94c0](https://url.jam06452.uk/7erthk): Complete removal of file reading logic
18+
[Commit 0a56357](https://url.jam06452.uk/1g1lfwm): Finished implementing elementary functions
19+
[Commit 48d08fc](https://url.jam06452.uk/15x1axn): Derivatives of elementary functions
20+
21+
**Related Issues**
22+
[Issue #30](https://url.jam06452.uk/fvwf6y): Switch from shader files to strings

‎src/CMakeLists.txt‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
set(SOURCE_FILES
22
"graphics/graphics.cpp"
33
"graphics/graphics.h"
4-
"types/types.h" "parser/tokenizer.h" "parser/checker.h" "parser/rpn.h" "parser/parser.h" "parser/checker.cpp" "parser/parser.cpp" "parser/rpn.cpp" "parser/tokenizer.cpp" "parser/simplifier.h" "parser/simplifier.cpp" "transformer/constant.h" "transformer/constant.cpp" "preprocessor/preprocessor.h" "preprocessor/string_builder.h" "transformer/operator.h" "transformer/operator.cpp" "transformer/transformer.h" "transformer/transformer.cpp" "preprocessor/string_builder.cpp" "preprocessor/preprocessor.cpp" "interactions/interactions.h" "interactions/interactions.cpp" "parser/validator.cpp" "parser/validator.h" "graphics/ui_init.h" "graphics/ui_init.cpp" "graphics/ui.h" "graphics/ui.cpp" "types/type_mapper.h" "types/type_mapper.cpp" "compiler/compiler_shader.h" "compiler/compiler_shader.cpp" "transformer/tree.h" "transformer/tree.cpp" "higher_order/derivative.h" "higher_order/higher_order.h" "higher_order/derivative.cpp" "higher_order/higher_order.cpp" "graphics/3d/mesh.h" "graphics/3d/mesh.cpp" "graphics/3d/camera_state.h" "graphics/3d/camera_state.cpp" "shaders/embedded_shaders.h")
4+
"types/types.h" "parser/tokenizer.h" "parser/checker.h" "parser/rpn.h" "parser/parser.h" "parser/checker.cpp" "parser/parser.cpp" "parser/rpn.cpp" "parser/tokenizer.cpp" "parser/simplifier.h" "parser/simplifier.cpp" "transformer/constant.h" "transformer/constant.cpp" "preprocessor/preprocessor.h" "preprocessor/string_builder.h" "transformer/operator.h" "transformer/operator.cpp" "transformer/transformer.h" "transformer/transformer.cpp" "preprocessor/string_builder.cpp" "preprocessor/preprocessor.cpp" "interactions/interactions.h" "interactions/interactions.cpp" "parser/validator.cpp" "parser/validator.h" "graphics/ui_init.h" "graphics/ui_init.cpp" "graphics/ui.h" "graphics/ui.cpp" "types/type_mapper.h" "types/type_mapper.cpp" "compiler/compiler_shader.h" "compiler/compiler_shader.cpp" "transformer/tree.h" "transformer/tree.cpp" "higher_order/derivative.h" "higher_order/higher_order.h" "higher_order/derivative.cpp" "higher_order/higher_order.cpp" "graphics/3d/mesh.h" "graphics/3d/mesh.cpp" "graphics/3d/camera_state.h" "graphics/3d/camera_state.cpp")
55
set(SHADERS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/shaders")
66
set(HEADER_BUILD "${CMAKE_CURRENT_BINARY_DIR}/shaders/embedded_shaders.h")
77
set(HEADER_SRC "${CMAKE_CURRENT_SOURCE_DIR}/shaders/embedded_shaders.h")
@@ -46,4 +46,4 @@ add_custom_target(copy-additional-folders ALL
4646
)
4747

4848
add_dependencies(complex-plotter copy-additional-folders)
49-
target_include_directories(complex-plotter PRIVATE ".")
49+
target_include_directories(complex-plotter PRIVATE ${CMAKE_CURRENT_BINARY_DIR} ".")

‎src/main.cpp‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ int main() {
8585
FunctionState function_state;
8686
function_state.current_shader = &shader_program;
8787

88-
Mesh grid_mesh = generate_grid_mesh(256);
88+
Mesh grid_mesh = generate_grid_mesh(350);
8989

9090
render(function_state, stack_tbo_texture, constants_tbo_texture,shader_program);
9191
update_camera_vectors(camera_state);

‎src/preprocessor/preprocessor.cpp‎

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,9 @@ void preprocess_string(const string& filename, const vector<TokenOperator>& oper
3232
string raw_source = get_source(filename);
3333
initialize_map_id();
3434
const string marker = "START_WRITING_HERE HERE";
35-
size_t start_pos = raw_source.find(marker) + marker.length();
36-
if (start_pos == string::npos) {
37-
std::cerr << "Marker does not exist";
38-
return;
39-
}
40-
raw_source.insert(start_pos, "\n" + preprocessed_string + "\n");
35+
const string interpreter = write_interpreter();
36+
inject_at(raw_source, "START_WRITING_HERE HERE", "\n" + preprocessed_string + "\n");
37+
inject_at(raw_source, "INTERPRETER_DEFINITION HERE", "\n" + interpreter + "\n");
4138
if (filename == "shaders/plotter.frag") {
4239
SRC_PLOTTER_FRAG = raw_source;
4340
}
@@ -53,28 +50,15 @@ void preprocess_file(const string& filename, const vector<TokenOperator>& operat
5350
initialize_map_id();
5451
string raw_source = get_source(filename);
5552
const string marker = "START_WRITING_HERE HERE";
56-
size_t start_pos = raw_source.find(marker) + marker.length();
57-
// Let this exception be an exception! While I don't like the exception handling paradigm
58-
//, it is a necessary evil for file handling. [added some days after]: If only I knew...
59-
60-
try {
61-
raw_source = get_source(filename);
62-
}
63-
catch (const std::exception& e) {
64-
std::cerr << e.what() << std::endl;
65-
return;
66-
}
67-
if (start_pos == string::npos) {
68-
std::cerr << "Marker does not exist";
69-
return;
70-
}
71-
raw_source.insert(start_pos, "\n" + preprocessed_string + "\n");
53+
const string interpreter = write_interpreter();
54+
inject_at(raw_source, "START_WRITING_HERE HERE", "\n" + preprocessed_string + "\n");
55+
inject_at(raw_source, "INTERPRETER_DEFINITION HERE", "\n" + interpreter + "\n");
7256
std::ofstream out(filename);
7357
if (!out.is_open()) {
7458
std::cerr << "Could not open output file";
7559
return;
7660
}
77-
out << raw_source;
61+
out << interpreter;
7862
out.close();
7963
}
8064

@@ -89,6 +73,7 @@ string build_shader_string(const string& new_shader, const string& origin) {
8973
return out;
9074
}
9175

76+
9277
static bool found_bounds(const string& source, const string& tag, size_t& out_start, size_t& out_length) {
9378
string start_marker = "#define " + tag;
9479
string end_marker = "#define END_" + tag;
@@ -129,6 +114,13 @@ string erase_block(const string& source, const string& tag) {
129114
return copy;
130115
}
131116

117+
void erase_block(string& source, const string& tag) {
118+
size_t start, length;
119+
while (found_bounds(source, tag, start, length)) {
120+
source.erase(start, length);
121+
}
122+
}
123+
132124
string inject_at(const string& source, const string& tag, const string& payload) {
133125
string copy = source;
134126
const string marker = "#define " + tag;
@@ -147,6 +139,7 @@ void inject_at(string& source, const string& tag, const string& payload) {
147139
const string marker = "#define " + tag;
148140
size_t pos = source.find(marker);
149141
if (pos == string::npos) {
142+
std::cout << tag;
150143
throw std::runtime_error("Injection marker '" + tag + "' not found");
151144
}
152145
size_t end = source.find('\n', pos);

‎src/preprocessor/string_builder.cpp‎

Lines changed: 52 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@ string get_operator_name(const Operator op) {
1616
}
1717

1818
void define_const(std::stringstream& ss, const Operator op) {
19-
ss << "#define SHADER_" << get_operator_name(op) << " " << static_cast<unsigned int>(op) << "u\n";
19+
ss << "#define " << get_operator_name(op) << " " << static_cast<unsigned int>(op) << "u\n";
2020
}
2121

2222
void define_const(std::stringstream& ss, const string& name, const unsigned int val) {
23-
ss << "#define SHADER_" << name << " " << val << "u\n";
23+
ss << "#define " << name << " " << val << "u\n";
2424
}
2525

2626
void register_op(std::stringstream& ss, Operator op, unsigned int& count) {
27+
if (get_operator_name(op) == "") return;
2728
if (!operator_to_id_mapper.contains(op)) {
2829
operator_to_id_mapper[op] = count;
2930
}
@@ -63,6 +64,54 @@ void set_binary(const vector<TokenOperator>& binary, std::stringstream& ss, unsi
6364
define_const(ss, "BINARY_BOUNDARY", count++);
6465
}
6566

67+
string write_case(const FullOperator& op) {
68+
string arity_str = "";
69+
if (op.gl_define_name.empty()) return "";
70+
switch (op.token_operator.arity) {
71+
case NULLARY:
72+
if (op.token_operator.op == CONSTANT)
73+
arity_str = "stack[sp++] = texelFetch(constants,cp++).xy;";
74+
else
75+
arity_str = "stack[sp++] = " + op.gl_name;
76+
break;
77+
case UNARY:
78+
arity_str = "stack[sp-1] = " + op.gl_name + "(stack[sp-1]);"; break;
79+
case BINARY:
80+
arity_str = "stack[sp-1] = " + op.gl_name + "(stack[sp-1], b);"; ;
81+
}
82+
return "case " + op.gl_define_name + ": " + arity_str + "; break;\n";
83+
}
84+
85+
string write_interpreter() {
86+
string out = R"(
87+
const uint stack_size = 1024u;
88+
vec2 run_stack(in usamplerBuffer operators, in samplerBuffer constants, in vec2 z){
89+
vec2 stack[16];
90+
int sp = 0;
91+
int cp = 0;
92+
for(int i=0;i<1024;++i){
93+
uint op = texelFetch(operators,i).x;
94+
if (op == END) break;
95+
if (op == NULL_SYMBOL) continue;
96+
)";
97+
string arity_op[10];
98+
for (const FullOperator& fp : full_operators) {
99+
arity_op[fp.token_operator.arity] += write_case(fp);
100+
}
101+
out += "\n if (op < VALUE_BOUNDARY) {\n switch(op) {\n" + arity_op[0] + " }\n }";
102+
103+
out += "\n else if (op < BINARY_BOUNDARY) {\n vec2 b = stack[--sp];\n switch(op) {\n" + arity_op[2] + " }\n }";
104+
105+
out += "\n else {\n switch(op) {\n" + arity_op[1] + " }\n }";
106+
107+
out += R"(
108+
}
109+
return stack[sp-1];
110+
}
111+
)";
112+
return out;
113+
}
114+
66115
string get_preprocessor_string(const vector<TokenOperator>& operators) {
67116
std::map<Arity, vector<TokenOperator>> arity_expressions;
68117
for (const TokenOperator& op : operators) {
@@ -77,6 +126,7 @@ string get_preprocessor_string(const vector<TokenOperator>& operators) {
77126
set_values(arity_expressions.at(Arity::NULLARY), ss, count);
78127
set_binary(arity_expressions.at(Arity::BINARY), ss, count);
79128
set_unary(arity_expressions.at(Arity::UNARY), ss, count);
129+
80130
define_const(ss, "END", 255u);
81131
std::cout << ss.str();
82132

‎src/preprocessor/string_builder.h‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,6 @@ string get_operator_name(const Operator op);
88

99
unsigned char get_opcode(Operator op);
1010

11-
string get_preprocessor_string(const vector<TokenOperator>& operators);
11+
string get_preprocessor_string(const vector<TokenOperator>& operators);
12+
13+
string write_interpreter();

‎src/scripts/embed_shaders.cmake‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
file(GLOB SHADER_FILES "${SHADER_SOURCE_DIR}/*")
1+
file(GLOB SHADER_FILES
2+
"${SHADER_SOURCE_DIR}/*.vert"
3+
"${SHADER_SOURCE_DIR}/*.frag"
4+
"${SHADER_SOURCE_DIR}/*.geom"
5+
"${SHADER_SOURCE_DIR}/*.glsl")
26

37
set(FILE_CONTENT "#pragma once\n#include <string>\n\n")
48

0 commit comments

Comments
 (0)