Skip to content

Commit 1ea93b8

Browse files
committed
[Bindings/Odin] Separate ASCII and Unicode text measurement functions
1 parent f5d431b commit 1ea93b8

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

bindings/odin/examples/clay-official-website/clay_renderer_raylib.odin

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,10 @@ clay_color_to_rl_color :: proc(color: clay.Color) -> rl.Color {
1818

1919
raylib_fonts := [dynamic]Raylib_Font{}
2020

21-
measure_text :: proc "c" (text: clay.StringSlice, config: ^clay.TextElementConfig, userData: rawptr) -> clay.Dimensions {
21+
// Alias for compatibility, default to ascii support
22+
measure_text :: measure_text_ascii
23+
24+
measure_text_unicode :: proc "c" (text: clay.StringSlice, config: ^clay.TextElementConfig, userData: rawptr) -> clay.Dimensions {
2225
// Needed for grapheme_count
2326
context = runtime.default_context()
2427

@@ -30,6 +33,7 @@ measure_text :: proc "c" (text: clay.StringSlice, config: ^clay.TextElementConfi
3033
// This function seems somewhat expensive, if you notice performance issues, you could assume
3134
// - 1 codepoint per visual character (no grapheme clusters), where you can get the length from the loop
3235
// - 1 byte per visual character (ascii), where you can get the length with `text.length`
36+
// see `measure_text_ascii`
3337
grapheme_count, _, _ := utf8.grapheme_count(text_str)
3438

3539
for letter, byte_idx in text_str {
@@ -55,6 +59,35 @@ measure_text :: proc "c" (text: clay.StringSlice, config: ^clay.TextElementConfi
5559
return {width = line_width * scaleFactor + total_spacing, height = f32(config.fontSize)}
5660
}
5761

62+
measure_text_ascii :: proc "c" (text: clay.StringSlice, config: ^clay.TextElementConfig, userData: rawptr) -> clay.Dimensions {
63+
line_width: f32 = 0
64+
65+
font := raylib_fonts[config.fontId].font
66+
text_str := string(text.chars[:text.length])
67+
68+
for i in 0..<len(text_str) {
69+
glyph_index := text_str[i] - 32
70+
71+
glyph := font.glyphs[glyph_index]
72+
73+
if glyph.advanceX != 0 {
74+
line_width += f32(glyph.advanceX)
75+
} else {
76+
line_width += font.recs[glyph_index].width + f32(font.glyphs[glyph_index].offsetX)
77+
}
78+
}
79+
80+
scaleFactor := f32(config.fontSize) / f32(font.baseSize)
81+
82+
// Note:
83+
// I'd expect this to be `len(text_str) - 1`,
84+
// but that seems to be one letterSpacing too small
85+
// maybe that's a raylib bug, maybe that's Clay?
86+
total_spacing := f32(len(text_str)) * f32(config.letterSpacing)
87+
88+
return {width = line_width * scaleFactor + total_spacing, height = f32(config.fontSize)}
89+
}
90+
5891
clay_raylib_render :: proc(render_commands: ^clay.ClayArray(clay.RenderCommand), allocator := context.temp_allocator) {
5992
for i in 0 ..< render_commands.length {
6093
render_command := clay.RenderCommandArray_Get(render_commands, i)

0 commit comments

Comments
 (0)