src/helpers.c
1#include "alba.h"
2
3#include <stdio.h>
4
5void alba_color_print(const AlbaColor* color)
6{
7 printf("AlbaColor{%f, %f, %f, %f}\n", color->r, color->g, color->b, color->a);
8}
9
10void alba_vector_print(const AlbaVector* vector)
11{
12 printf("AlbaVector{%f, %f}\n", vector->x, vector->y);
13}
14
15void alba_attribute_print(const AlbaAttribute* attribute)
16{
17 printf("AlbaAttribute{\n ");
18 alba_color_print(&attribute->color);
19 printf(" ");
20 alba_vector_print(&attribute->uv);
21 printf("}\n");
22}
23
24WGPUBuffer create_buffer(
25 const AlbaWindow* window,
26 const uint64_t size, const void* data,
27 const WGPUBufferUsageFlags flags
28)
29{
30 WGPUBufferDescriptor buffer_options = {0};
31 buffer_options.usage = WGPUBufferUsage_CopyDst | flags;
32 buffer_options.size = size;
33 const WGPUBuffer buffer = wgpuDeviceCreateBuffer(window->device, &buffer_options);
34 wgpuQueueWriteBuffer(window->queue, buffer, 0, data, size);
35 return buffer;
36}
37
38void release_buffer(const WGPUBuffer buffer)
39{
40 if (buffer != NULL)
41 {
42 wgpuBufferDestroy(buffer);
43 wgpuBufferRelease(buffer);
44 }
45}
46
47WGPUBuffer update_buffer(
48 const AlbaWindow* window, WGPUBuffer buffer, const WGPUBufferUsage usage, AlbaArray data
49)
50{
51 // Deallocate old buffer if any
52 release_buffer(buffer);
53 // Copy data to new buffer
54 buffer = create_buffer(window, data.length * data.element_size, data.data, usage);
55 // Clear local copy for next frame
56 alba_array_clear(&data);
57 return buffer;
58}
59
60WGPUTexture create_texture(
61 const AlbaWindow* window,
62 const WGPUTextureUsage usage,
63 const AlbaVector size,
64 const WGPUTextureFormat format, const uint8_t samples,
65 const void* data
66)
67{
68 WGPUTextureDescriptor texture_options = {0};
69 texture_options.usage = usage;
70 texture_options.format = format;
71 texture_options.dimension = WGPUTextureDimension_2D;
72 texture_options.size.width = size.x;
73 texture_options.size.height = size.y;
74 texture_options.size.depthOrArrayLayers = 1;
75 texture_options.sampleCount = samples;
76 texture_options.mipLevelCount = 1;
77
78 const WGPUTexture texture = wgpuDeviceCreateTexture(window->device, &texture_options);
79
80 if (data != NULL)
81 {
82 const uint64_t bpp = format == WGPUTextureFormat_R8Unorm ? 1 : 4;
83
84 WGPUImageCopyTexture destination = {0};
85 destination.texture = texture;
86 destination.aspect = WGPUTextureAspect_All;
87
88 WGPUTextureDataLayout source = {0};
89 source.bytesPerRow = size.x * bpp;
90 source.rowsPerImage = size.y;
91
92 wgpuQueueWriteTexture(
93 window->queue,
94 &destination, data,
95 size.x * size.y * bpp,
96 &source,
97 &texture_options.size
98 );
99 }
100
101 return texture;
102}
103
104void release_texture(const WGPUTexture texture)
105{
106 wgpuTextureDestroy(texture);
107 wgpuTextureRelease(texture);
108}