brewery
notashelf /
e72da82b32d46daf27c4ff663e5f918058b65fd7

chroma

public

Lightweight wallpaper daemon for Wayland

Star0tarball
clone
ssh://git@git.notashelf.dev:33/notashelf/chroma.git
src/render.cC550 lines16.3 KB
1
#include <stdio.h>
2
#include <stdlib.h>
3
#include <string.h>
4
5
#include <EGL/egl.h>
6
#include <GLES2/gl2.h>
7
8
#include "../include/chroma.h"
9
#include "../include/stb_image.h"
10
11
// Vertex shader for simple texture rendering
12
static const char *vertex_shader_source =
13
    "#version 120\n"
14
    "attribute vec2 position;\n"
15
    "attribute vec2 texcoord;\n"
16
    "varying vec2 v_texcoord;\n"
17
    "void main() {\n"
18
    "    gl_Position = vec4(position, 0.0, 1.0);\n"
19
    "    v_texcoord = texcoord;\n"
20
    "}\n";
21
22
// Fragment shader for simple texture rendering
23
static const char *fragment_shader_source =
24
    "#version 120\n"
25
    "varying vec2 v_texcoord;\n"
26
    "uniform sampler2D texture;\n"
27
    "void main() {\n"
28
    "    gl_FragColor = texture2D(texture, v_texcoord);\n"
29
    "}\n";
30
31
// Vertices for a fullscreen quad
32
static const float vertices[] = {
33
    // Position  Texcoord
34
    -1.0f, -1.0f, 0.0f, 1.0f, // bottom left
35
    1.0f,  -1.0f, 1.0f, 1.0f, // bottom right
36
    1.0f,  1.0f,  1.0f, 0.0f, // top right
37
    -1.0f, 1.0f,  0.0f, 0.0f, // top left
38
};
39
40
static const unsigned int indices[] = {
41
    0, 1, 2, // first triangle
42
    2, 3, 0  // second triangle
43
};
44
45
static GLuint compile_shader(GLenum type, const char *source) {
46
  GLuint shader = glCreateShader(type);
47
  if (!shader) {
48
    chroma_log("ERROR", "Failed to create shader");
49
    return 0;
50
  }
51
52
  glShaderSource(shader, 1, &source, NULL);
53
  glCompileShader(shader);
54
55
  GLint status;
56
  glGetShaderiv(shader, GL_COMPILE_STATUS, &status);
57
  if (status != GL_TRUE) {
58
    char log[512];
59
    glGetShaderInfoLog(shader, sizeof(log), NULL, log);
60
    chroma_log("ERROR", "Shader compilation failed: %s", log);
61
    glDeleteShader(shader);
62
    return 0;
63
  }
64
65
  return shader;
66
}
67
68
static GLuint create_shader_program(void) {
69
  GLuint vertex_shader = compile_shader(GL_VERTEX_SHADER, vertex_shader_source);
70
  if (!vertex_shader) {
71
    return 0;
72
  }
73
74
  GLuint fragment_shader =
75
      compile_shader(GL_FRAGMENT_SHADER, fragment_shader_source);
76
  if (!fragment_shader) {
77
    glDeleteShader(vertex_shader);
78
    return 0;
79
  }
80
81
  GLuint program = glCreateProgram();
82
  if (!program) {
83
    chroma_log("ERROR", "Failed to create shader program");
84
    glDeleteShader(vertex_shader);
85
    glDeleteShader(fragment_shader);
86
    return 0;
87
  }
88
89
  glAttachShader(program, vertex_shader);
90
  glAttachShader(program, fragment_shader);
91
  glLinkProgram(program);
92
93
  GLint status;
94
  glGetProgramiv(program, GL_LINK_STATUS, &status);
95
  if (status != GL_TRUE) {
96
    char log[512];
97
    glGetProgramInfoLog(program, sizeof(log), NULL, log);
98
    chroma_log("ERROR", "Shader program linking failed: %s", log);
99
    glDeleteProgram(program);
100
    program = 0;
101
  }
102
103
  glDeleteShader(vertex_shader);
104
  glDeleteShader(fragment_shader);
105
106
  return program;
107
}
108
109
// Initialize OpenGL resources for output
110
static int init_gl_resources(chroma_output_t *output) {
111
  if (!output || output->gl_resources_initialized) {
112
    return CHROMA_OK;
113
  }
114
115
  // Create shader prog
116
  output->shader_program = create_shader_program();
117
  if (!output->shader_program) {
118
    chroma_log("ERROR", "Failed to create shader program for output %u",
119
               output->id);
120
    return CHROMA_ERROR_EGL;
121
  }
122
123
  // Create and setup VBO/EBO
124
  glGenBuffers(1, &output->vbo);
125
  glGenBuffers(1, &output->ebo);
126
127
  glBindBuffer(GL_ARRAY_BUFFER, output->vbo);
128
  glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
129
130
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, output->ebo);
131
  glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices,
132
               GL_STATIC_DRAW);
133
134
  output->texture_id = 0; // will be created when image is assigned
135
  output->gl_resources_initialized = true;
136
137
  chroma_log("DEBUG", "Initialized GL resources for output %u", output->id);
138
  return CHROMA_OK;
139
}
140
141
// Create or update texture from image data
142
static int update_texture_from_image(chroma_output_t *output,
143
                                     chroma_image_t *image) {
144
  if (!output || !image || !image->loaded) {
145
    return CHROMA_ERROR_INIT;
146
  }
147
148
  // If image data was already freed after previous GPU upload, we can't upload
149
  // again
150
  if (!image->data) {
151
    chroma_log("ERROR",
152
               "Cannot create texture: image data already freed for %s",
153
               image->path);
154
    return CHROMA_ERROR_IMAGE;
155
  }
156
157
  // Delete existing texture if it exists
158
  if (output->texture_id != 0) {
159
    glDeleteTextures(1, &output->texture_id);
160
    output->texture_id = 0;
161
  }
162
163
  // Create new texture
164
  glGenTextures(1, &output->texture_id);
165
  glBindTexture(GL_TEXTURE_2D, output->texture_id);
166
167
  // Set texture parameters
168
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
169
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
170
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
171
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
172
173
  // Upload texture data (always RGBA now)
174
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image->width, image->height, 0,
175
               GL_RGBA, GL_UNSIGNED_BYTE, image->data);
176
177
  glBindTexture(GL_TEXTURE_2D, 0);
178
179
  // Mark this output as having uploaded its texture
180
  output->texture_uploaded = true;
181
182
  // Free system RAM copy only when ALL outputs using this image have uploaded
183
  // to GPU
184
  if (image->data) {
185
    // Count total outputs using this image and how many have uploaded
186
    int total_using = 0;
187
    int uploaded_count = 0;
188
189
    chroma_state_t *state = output->state;
190
    for (int i = 0; i < state->output_count; i++) {
191
      if (state->outputs[i].active && state->outputs[i].image == image) {
192
        total_using++;
193
        if (state->outputs[i].texture_uploaded) {
194
          uploaded_count++;
195
        }
196
      }
197
    }
198
199
    // Only free image data when ALL outputs using it have uploaded
200
    if (total_using > 0 && uploaded_count >= total_using) {
201
      size_t freed_bytes =
202
          (size_t)image->width * image->height * image->channels;
203
      stbi_image_free(image->data);
204
      image->data = NULL;
205
      chroma_log("INFO",
206
                 "Freed %.2f MB of image data after all %d outputs uploaded to "
207
                 "GPU: %s",
208
                 (double)freed_bytes / (1024.0 * 1024.0), total_using,
209
                 image->path);
210
    }
211
  }
212
213
  chroma_log("DEBUG", "Updated texture for output %u (%dx%d)", output->id,
214
             image->width, image->height);
215
  return CHROMA_OK;
216
}
217
218
// Cleanup OpenGL resources for output
219
static void cleanup_gl_resources(chroma_output_t *output) {
220
  if (!output || !output->gl_resources_initialized) {
221
    return;
222
  }
223
224
  if (output->texture_id != 0) {
225
    glDeleteTextures(1, &output->texture_id);
226
    output->texture_id = 0;
227
  }
228
229
  if (output->shader_program != 0) {
230
    glDeleteProgram(output->shader_program);
231
    output->shader_program = 0;
232
  }
233
234
  if (output->vbo != 0) {
235
    glDeleteBuffers(1, &output->vbo);
236
    output->vbo = 0;
237
  }
238
239
  if (output->ebo != 0) {
240
    glDeleteBuffers(1, &output->ebo);
241
    output->ebo = 0;
242
  }
243
244
  output->gl_resources_initialized = false;
245
  chroma_log("DEBUG", "Cleaned up GL resources for output %u", output->id);
246
}
247
248
// EGL configuration selection
249
static int choose_egl_config(EGLDisplay display, EGLConfig *config) {
250
  EGLint attributes[] = {EGL_SURFACE_TYPE,
251
                         EGL_WINDOW_BIT,
252
                         EGL_RED_SIZE,
253
                         8,
254
                         EGL_GREEN_SIZE,
255
                         8,
256
                         EGL_BLUE_SIZE,
257
                         8,
258
                         EGL_ALPHA_SIZE,
259
                         8,
260
                         EGL_RENDERABLE_TYPE,
261
                         EGL_OPENGL_BIT,
262
                         EGL_NONE};
263
264
  EGLint num_configs;
265
  if (!eglChooseConfig(display, attributes, config, 1, &num_configs)) {
266
    chroma_log("ERROR", "Failed to choose EGL config: 0x%04x", eglGetError());
267
    return -1;
268
  }
269
270
  if (num_configs == 0) {
271
    chroma_log("ERROR", "No suitable EGL configs found");
272
    return -1;
273
  }
274
275
  return 0;
276
}
277
278
// EGL initialization
279
int chroma_egl_init(chroma_state_t *state) {
280
  if (!state || !state->display) {
281
    return CHROMA_ERROR_INIT;
282
  }
283
284
  // Get EGL display
285
  state->egl_display = eglGetDisplay((EGLNativeDisplayType)state->display);
286
  if (state->egl_display == EGL_NO_DISPLAY) {
287
    chroma_log("ERROR", "Failed to get EGL display: 0x%04x", eglGetError());
288
    return CHROMA_ERROR_EGL;
289
  }
290
291
  // Initialize EGL
292
  EGLint major, minor;
293
  if (!eglInitialize(state->egl_display, &major, &minor)) {
294
    chroma_log("ERROR", "Failed to initialize EGL: 0x%04x", eglGetError());
295
    return CHROMA_ERROR_EGL;
296
  }
297
298
  chroma_log("INFO", "EGL initialized: version %d.%d", major, minor);
299
300
  // Bind OpenGL API
301
  if (!eglBindAPI(EGL_OPENGL_API)) {
302
    chroma_log("ERROR", "Failed to bind OpenGL API: 0x%04x", eglGetError());
303
    chroma_egl_cleanup(state);
304
    return CHROMA_ERROR_EGL;
305
  }
306
307
  // Choose EGL config
308
  if (choose_egl_config(state->egl_display, &state->egl_config) != 0) {
309
    chroma_egl_cleanup(state);
310
    return CHROMA_ERROR_EGL;
311
  }
312
313
  // Create EGL context
314
  EGLint context_attributes[] = {EGL_CONTEXT_MAJOR_VERSION, 2,
315
                                 EGL_CONTEXT_MINOR_VERSION, 1, EGL_NONE};
316
317
  state->egl_context = eglCreateContext(state->egl_display, state->egl_config,
318
                                        EGL_NO_CONTEXT, context_attributes);
319
  if (state->egl_context == EGL_NO_CONTEXT) {
320
    chroma_log("ERROR", "Failed to create EGL context: 0x%04x", eglGetError());
321
    chroma_egl_cleanup(state);
322
    return CHROMA_ERROR_EGL;
323
  }
324
325
  chroma_log("INFO", "EGL context created successfully");
326
  return CHROMA_OK;
327
}
328
329
// EGL cleanup
330
void chroma_egl_cleanup(chroma_state_t *state) {
331
  if (!state) {
332
    return;
333
  }
334
335
  if (state->egl_display != EGL_NO_DISPLAY) {
336
    eglMakeCurrent(state->egl_display, EGL_NO_SURFACE, EGL_NO_SURFACE,
337
                   EGL_NO_CONTEXT);
338
339
    if (state->egl_context != EGL_NO_CONTEXT) {
340
      eglDestroyContext(state->egl_display, state->egl_context);
341
      state->egl_context = EGL_NO_CONTEXT;
342
    }
343
344
    eglTerminate(state->egl_display);
345
    state->egl_display = EGL_NO_DISPLAY;
346
  }
347
348
  chroma_log("INFO", "EGL cleaned up");
349
}
350
351
// Create surface for output
352
int chroma_surface_create(chroma_state_t *state, chroma_output_t *output) {
353
  if (!state || !output || !state->compositor || !state->layer_shell) {
354
    return CHROMA_ERROR_INIT;
355
  }
356
357
  // Create Wayland surface
358
  output->surface = wl_compositor_create_surface(state->compositor);
359
  if (!output->surface) {
360
    chroma_log("ERROR", "Failed to create Wayland surface for output %u",
361
               output->id);
362
    return CHROMA_ERROR_WAYLAND;
363
  }
364
365
  // Create layer surface for wallpaper
366
  output->layer_surface = zwlr_layer_shell_v1_get_layer_surface(
367
      state->layer_shell, output->surface, output->wl_output,
368
      ZWLR_LAYER_SHELL_V1_LAYER_BACKGROUND, "chroma-wallpaper");
369
370
  if (!output->layer_surface) {
371
    chroma_log("ERROR", "Failed to create layer surface for output %u",
372
               output->id);
373
    chroma_surface_destroy(output);
374
    return CHROMA_ERROR_WAYLAND;
375
  }
376
377
  // Configure layer surface
378
  zwlr_layer_surface_v1_set_size(output->layer_surface, output->width,
379
                                 output->height);
380
  zwlr_layer_surface_v1_set_anchor(output->layer_surface,
381
                                   ZWLR_LAYER_SURFACE_V1_ANCHOR_TOP |
382
                                       ZWLR_LAYER_SURFACE_V1_ANCHOR_RIGHT |
383
                                       ZWLR_LAYER_SURFACE_V1_ANCHOR_BOTTOM |
384
                                       ZWLR_LAYER_SURFACE_V1_ANCHOR_LEFT);
385
  zwlr_layer_surface_v1_set_exclusive_zone(output->layer_surface, -1);
386
  zwlr_layer_surface_v1_set_keyboard_interactivity(
387
      output->layer_surface, ZWLR_LAYER_SURFACE_V1_KEYBOARD_INTERACTIVITY_NONE);
388
389
  // Add layer surface listener
390
  zwlr_layer_surface_v1_add_listener(
391
      output->layer_surface, &chroma_layer_surface_listener_impl, output);
392
393
  // Commit surface to trigger configure event
394
  wl_surface_commit(output->surface);
395
396
  // Wait for configure event
397
  wl_display_roundtrip(state->display);
398
399
  // Create EGL window
400
  output->egl_window =
401
      wl_egl_window_create(output->surface, output->width, output->height);
402
  if (!output->egl_window) {
403
    chroma_log("ERROR", "Failed to create EGL window for output %u",
404
               output->id);
405
    chroma_surface_destroy(output);
406
    return CHROMA_ERROR_EGL;
407
  }
408
409
  // Create EGL surface
410
  output->egl_surface =
411
      eglCreateWindowSurface(state->egl_display, state->egl_config,
412
                             (EGLNativeWindowType)output->egl_window, NULL);
413
  if (output->egl_surface == EGL_NO_SURFACE) {
414
    chroma_log("ERROR", "Failed to create EGL surface for output %u: 0x%04x",
415
               output->id, eglGetError());
416
    chroma_surface_destroy(output);
417
    return CHROMA_ERROR_EGL;
418
  }
419
420
  chroma_log("INFO", "Created surface for output %u (%dx%d)", output->id,
421
             output->width, output->height);
422
423
  return CHROMA_OK;
424
}
425
426
// Destroy surface
427
void chroma_surface_destroy(chroma_output_t *output) {
428
  if (!output) {
429
    return;
430
  }
431
432
  // Clean up OpenGL resources first
433
  cleanup_gl_resources(output);
434
435
  if (output->egl_surface != EGL_NO_SURFACE) {
436
    eglDestroySurface(eglGetCurrentDisplay(), output->egl_surface);
437
    output->egl_surface = EGL_NO_SURFACE;
438
  }
439
440
  if (output->egl_window) {
441
    wl_egl_window_destroy(output->egl_window);
442
    output->egl_window = NULL;
443
  }
444
445
  if (output->layer_surface) {
446
    zwlr_layer_surface_v1_destroy(output->layer_surface);
447
    output->layer_surface = NULL;
448
  }
449
450
  if (output->surface) {
451
    wl_surface_destroy(output->surface);
452
    output->surface = NULL;
453
  }
454
455
  chroma_log("DEBUG", "Destroyed surface for output %u", output->id);
456
}
457
458
// Render wallpaper to output using cached resources
459
int chroma_render_wallpaper(chroma_state_t *state, chroma_output_t *output) {
460
  if (!state || !output || !output->image || !output->image->loaded) {
461
    return CHROMA_ERROR_INIT;
462
  }
463
464
  // Make context current
465
  if (!eglMakeCurrent(state->egl_display, output->egl_surface,
466
                      output->egl_surface, state->egl_context)) {
467
    chroma_log("ERROR", "Failed to make EGL context current: 0x%04x",
468
               eglGetError());
469
    return CHROMA_ERROR_EGL;
470
  }
471
472
  if (init_gl_resources(output) != CHROMA_OK) {
473
    return CHROMA_ERROR_EGL;
474
  }
475
476
  if (output->texture_id == 0) {
477
    if (update_texture_from_image(output, output->image) != CHROMA_OK) {
478
      chroma_log("ERROR", "Failed to update texture for output %u", output->id);
479
      return CHROMA_ERROR_EGL;
480
    }
481
  }
482
483
  // Set viewport
484
  glViewport(0, 0, output->width, output->height);
485
486
  // Clear screen
487
  glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
488
  glClear(GL_COLOR_BUFFER_BIT);
489
490
  // Use cached shader program
491
  glUseProgram(output->shader_program);
492
493
  // Bind cached texture
494
  glActiveTexture(GL_TEXTURE0);
495
  glBindTexture(GL_TEXTURE_2D, output->texture_id);
496
  glUniform1i(glGetUniformLocation(output->shader_program, "texture"), 0);
497
498
  // Use cached VBO/EBO
499
  glBindBuffer(GL_ARRAY_BUFFER, output->vbo);
500
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, output->ebo);
501
502
  // Set vertex attributes
503
  GLint position_attr = glGetAttribLocation(output->shader_program, "position");
504
  GLint texcoord_attr = glGetAttribLocation(output->shader_program, "texcoord");
505
506
  glEnableVertexAttribArray(position_attr);
507
  glVertexAttribPointer(position_attr, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
508
                        (void *)0);
509
510
  glEnableVertexAttribArray(texcoord_attr);
511
  glVertexAttribPointer(texcoord_attr, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float),
512
                        (void *)(2 * sizeof(float)));
513
514
  // Draw
515
  glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
516
517
  // Unbind resources
518
  glBindBuffer(GL_ARRAY_BUFFER, 0);
519
  glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
520
  glBindTexture(GL_TEXTURE_2D, 0);
521
  glUseProgram(0);
522
523
  // Swap buffers
524
  if (!eglSwapBuffers(state->egl_display, output->egl_surface)) {
525
    chroma_log("ERROR", "Failed to swap buffers for output %u: 0x%04x",
526
               output->id, eglGetError());
527
    return CHROMA_ERROR_EGL;
528
  }
529
530
  // Commit surface
531
  wl_surface_commit(output->surface);
532
533
  chroma_log("DEBUG", "Rendered wallpaper to output %u (cached resources)",
534
             output->id);
535
  return CHROMA_OK;
536
}
537
538
// Invalidate texture cache for output
539
void chroma_output_invalidate_texture(chroma_output_t *output) {
540
  if (!output || !output->gl_resources_initialized) {
541
    return;
542
  }
543
544
  if (output->texture_id != 0) {
545
    glDeleteTextures(1, &output->texture_id);
546
    output->texture_id = 0;
547
    output->texture_uploaded = false; // reset upload flag
548
    chroma_log("DEBUG", "Invalidated texture cache for output %u", output->id);
549
  }
550
}