SBgl 0.1.0
A graphics framework in C99
Loading...
Searching...
No Matches
sbgl_sort.c
Go to the documentation of this file.
1#include "sbgl_sort.h"
2
9 sbgl_SortKey* keys,
10 uint32_t* values,
11 uint32_t count,
12 sbgl_SortKey* temp_keys,
13 uint32_t* temp_values
14) {
15 if (count <= 1 || !temp_keys || !temp_values) {
16 return;
17 }
18
19 sbgl_SortKey* src_keys = keys;
20 sbgl_SortKey* dst_keys = temp_keys;
21 uint32_t* src_values = values;
22 uint32_t* dst_values = temp_values;
23
24 // The system performs 8 passes, each processing 8 bits of the 64-bit key.
25 // This uses 256 buckets per pass, significantly reducing cache misses and stack zeroing.
26 for (int pass = 0; pass < 8; ++pass) {
27 uint32_t counts[256] = { 0 };
28 uint32_t offsets[256] = { 0 };
29 int shift = pass * 8;
30
31 // Build histogram for the current 8-bit digit.
32 for (uint32_t i = 0; i < count; ++i) {
33 uint8_t bucket = (uint8_t)((src_keys[i] >> shift) & 0xFF);
34 counts[bucket]++;
35 }
36
37 // Compute prefix sums to find starting offsets for each bucket.
38 uint32_t total_offset = 0;
39 for (uint32_t i = 0; i < 256; ++i) {
40 offsets[i] = total_offset;
41 total_offset += counts[i];
42 }
43
44 // Scatter elements into the destination buffer based on the current digit.
45 for (uint32_t i = 0; i < count; ++i) {
46 uint8_t bucket = (uint8_t)((src_keys[i] >> shift) & 0xFF);
47 uint32_t pos = offsets[bucket]++;
48 dst_keys[pos] = src_keys[i];
49 dst_values[pos] = src_values[i];
50 }
51
52 // Swap source and destination pointers for the next pass.
53 sbgl_SortKey* tk = src_keys;
54 src_keys = dst_keys;
55 dst_keys = tk;
56
57 uint32_t* tv = src_values;
58 src_values = dst_values;
59 dst_values = tv;
60 }
61
62 // Since 8 passes are performed, the pointers naturally swap back to the original buffers.
63 // This confirms src_keys points to 'keys' and src_values points to 'values'.
64}
void sbgl_radix_sort(sbgl_SortKey *keys, uint32_t *values, uint32_t count, sbgl_SortKey *temp_keys, uint32_t *temp_values)
Performs a stable radix sort on an array of 64-bit keys and associated 32-bit values.
Definition sbgl_sort.c:8
Sorting utilities for the SBgl batching system.
uint64_t sbgl_SortKey
Bit-packed key used for sorting draw commands to minimize state changes.
Definition sbgl_types.h:57