-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_exporter.cpp
More file actions
305 lines (255 loc) · 10.6 KB
/
plot_exporter.cpp
File metadata and controls
305 lines (255 loc) · 10.6 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/**
* @file plot_exporter.cpp
* @brief PlotExporter implementation - offscreen rendering to PNG/JPEG
*/
#include "splot/plot_exporter.h"
#include "sokol_gfx.h"
// Include OpenGL headers based on backend for pixel readback
#if defined(__EMSCRIPTEN__)
#include <GLES3/gl3.h>
#elif defined(SOKOL_GLCORE) || defined(SOKOL_GLCORE33)
#include <glad/glad.h>
#endif
// stb_image_write (implementation is in screenshot.cpp)
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4996)
#endif
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wold-style-cast"
#pragma GCC diagnostic ignored "-Wsign-conversion"
#pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#pragma GCC diagnostic ignored "-Wconversion"
#pragma GCC diagnostic ignored "-Wcast-align"
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#ifdef __GNUC__
#ifndef __clang__
#pragma GCC diagnostic ignored "-Wuseless-cast"
#endif
#endif
#endif
#include "stb_image_write.h"
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
#include <algorithm>
#include <cstdio>
#include <vector>
namespace splot {
struct PlotExporter::Impl {
Color background_color = Color::white();
static void flipVertically(std::vector<uint8_t>& pixels, int width, int height) {
const size_t row_size = static_cast<size_t>(width) * 4;
std::vector<uint8_t> temp(row_size);
for (int y = 0; y < height / 2; ++y) {
uint8_t* row1 = pixels.data() + static_cast<size_t>(y) * row_size;
uint8_t* row2 = pixels.data() + static_cast<size_t>(height - 1 - y) * row_size;
std::copy(row1, row1 + row_size, temp.data());
std::copy(row2, row2 + row_size, row1);
std::copy(temp.data(), temp.data() + row_size, row2);
}
}
bool doExport(const std::string& filename, int width, int height,
const PlotExporter::RenderCallback& render,
bool is_jpeg, int quality) {
if (width <= 0 || height <= 0) {
std::fprintf(stderr, "PlotExporter: Invalid dimensions %dx%d\n", width, height);
return false;
}
if (!render) {
std::fprintf(stderr, "PlotExporter: No render callback provided\n");
return false;
}
#if defined(SOKOL_GLCORE) || defined(SOKOL_GLCORE33)
// Initialize GLAD if not already done (desktop OpenGL only)
static bool glad_initialized = false;
if (!glad_initialized) {
if (!gladLoadGL()) {
std::fprintf(stderr, "PlotExporter: Failed to initialize GLAD\n");
return false;
}
glad_initialized = true;
}
#endif
#if defined(SOKOL_GLCORE) || defined(SOKOL_GLCORE33) || defined(SOKOL_GLES3)
// Create offscreen color image (render target)
sg_image_desc color_img_desc = {};
color_img_desc.type = SG_IMAGETYPE_2D;
color_img_desc.usage.color_attachment = true;
color_img_desc.width = width;
color_img_desc.height = height;
color_img_desc.pixel_format = SG_PIXELFORMAT_RGBA8;
color_img_desc.sample_count = 1;
color_img_desc.label = "export-color";
sg_image color_img = sg_make_image(&color_img_desc);
if (sg_query_image_state(color_img) != SG_RESOURCESTATE_VALID) {
std::fprintf(stderr, "PlotExporter: Failed to create offscreen color image\n");
return false;
}
// Create offscreen depth image
sg_image_desc depth_img_desc = {};
depth_img_desc.type = SG_IMAGETYPE_2D;
depth_img_desc.usage.depth_stencil_attachment = true;
depth_img_desc.width = width;
depth_img_desc.height = height;
depth_img_desc.pixel_format = SG_PIXELFORMAT_DEPTH;
depth_img_desc.sample_count = 1;
depth_img_desc.label = "export-depth";
sg_image depth_img = sg_make_image(&depth_img_desc);
if (sg_query_image_state(depth_img) != SG_RESOURCESTATE_VALID) {
std::fprintf(stderr, "PlotExporter: Failed to create offscreen depth image\n");
sg_destroy_image(color_img);
return false;
}
// Create view objects for attachments
sg_view_desc color_view_desc = {};
color_view_desc.color_attachment.image = color_img;
color_view_desc.label = "export-color-view";
sg_view color_view = sg_make_view(&color_view_desc);
if (sg_query_view_state(color_view) != SG_RESOURCESTATE_VALID) {
std::fprintf(stderr, "PlotExporter: Failed to create color view\n");
sg_destroy_image(depth_img);
sg_destroy_image(color_img);
return false;
}
sg_view_desc depth_view_desc = {};
depth_view_desc.depth_stencil_attachment.image = depth_img;
depth_view_desc.label = "export-depth-view";
sg_view depth_view = sg_make_view(&depth_view_desc);
if (sg_query_view_state(depth_view) != SG_RESOURCESTATE_VALID) {
std::fprintf(stderr, "PlotExporter: Failed to create depth view\n");
sg_destroy_view(color_view);
sg_destroy_image(depth_img);
sg_destroy_image(color_img);
return false;
}
// Setup pass action with background color
sg_pass_action pass_action = {};
pass_action.colors[0].load_action = SG_LOADACTION_CLEAR;
pass_action.colors[0].store_action = SG_STOREACTION_STORE;
pass_action.colors[0].clear_value = {
background_color.r,
background_color.g,
background_color.b,
background_color.a
};
pass_action.depth.load_action = SG_LOADACTION_CLEAR;
pass_action.depth.store_action = SG_STOREACTION_DONTCARE;
pass_action.depth.clear_value = 1.0F;
// Begin offscreen render pass
sg_pass pass = {};
pass.action = pass_action;
pass.attachments.colors[0] = color_view;
pass.attachments.depth_stencil = depth_view;
sg_begin_pass(&pass);
// Set viewport to match export dimensions
sg_apply_viewport(0, 0, width, height, true);
// Call user's render callback
render(width, height);
sg_end_pass();
sg_commit();
// Wait for GPU to finish
glFinish();
// Get GL texture handle from Sokol image
sg_gl_image_info gl_info = sg_gl_query_image_info(color_img);
GLuint texture_id = gl_info.tex[0];
// Create FBO to read pixels from texture
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture_id, 0);
GLenum fb_status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (fb_status != GL_FRAMEBUFFER_COMPLETE) {
std::fprintf(stderr, "PlotExporter: Framebuffer incomplete: 0x%x\n", fb_status);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
sg_destroy_view(depth_view);
sg_destroy_view(color_view);
sg_destroy_image(depth_img);
sg_destroy_image(color_img);
return false;
}
// Read pixels
std::vector<uint8_t> pixels(static_cast<size_t>(width) * static_cast<size_t>(height) * 4);
glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data());
GLenum error = glGetError();
if (error != GL_NO_ERROR) {
std::fprintf(stderr, "PlotExporter: glReadPixels error: 0x%x\n", error);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
sg_destroy_view(depth_view);
sg_destroy_view(color_view);
sg_destroy_image(depth_img);
sg_destroy_image(color_img);
return false;
}
// Cleanup GL FBO
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glDeleteFramebuffers(1, &fbo);
// Cleanup Sokol resources
sg_destroy_view(depth_view);
sg_destroy_view(color_view);
sg_destroy_image(depth_img);
sg_destroy_image(color_img);
// Flip pixels vertically (OpenGL origin is bottom-left)
flipVertically(pixels, width, height);
// Write to file
int result = 0;
if (is_jpeg) {
// For JPEG, composite alpha against white background
for (size_t i = 0; i < pixels.size(); i += 4) {
float alpha = static_cast<float>(pixels[i + 3]) / 255.0F;
pixels[i + 0] = static_cast<uint8_t>(
static_cast<float>(pixels[i + 0]) * alpha + 255.0F * (1.0F - alpha));
pixels[i + 1] = static_cast<uint8_t>(
static_cast<float>(pixels[i + 1]) * alpha + 255.0F * (1.0F - alpha));
pixels[i + 2] = static_cast<uint8_t>(
static_cast<float>(pixels[i + 2]) * alpha + 255.0F * (1.0F - alpha));
}
result = stbi_write_jpg(filename.c_str(), width, height, 4, pixels.data(), quality);
} else {
const int stride = width * 4;
result = stbi_write_png(filename.c_str(), width, height, 4, pixels.data(), stride);
}
if (result == 0) {
std::fprintf(stderr, "PlotExporter: Failed to write %s\n", filename.c_str());
return false;
}
return true;
#else
// Silence unused parameter warnings for non-GL backends
(void)filename;
(void)is_jpeg;
(void)quality;
std::fprintf(stderr, "PlotExporter: Not implemented for this graphics backend\n");
return false;
#endif
}
};
PlotExporter::PlotExporter()
: impl_(std::make_unique<Impl>()) {}
PlotExporter::~PlotExporter() = default;
PlotExporter::PlotExporter(PlotExporter&&) noexcept = default;
PlotExporter& PlotExporter::operator=(PlotExporter&&) noexcept = default;
bool PlotExporter::exportPNG(const std::string& filename,
int width, int height,
RenderCallback render) {
return impl_->doExport(filename, width, height, render, false, 0);
}
bool PlotExporter::exportJPEG(const std::string& filename,
int width, int height,
RenderCallback render,
int quality) {
return impl_->doExport(filename, width, height, render, true, quality);
}
void PlotExporter::setBackgroundColor(const Color& color) {
impl_->background_color = color;
}
Color PlotExporter::backgroundColor() const {
return impl_->background_color;
}
} // namespace splot