@@ -248,6 +248,48 @@ static void draw_rect(int x0, int y0, int x1, int y1, int* color, bool fill)
248248 }
249249}
250250
251+ static int utf8_decode (const char * s , int * index )
252+ {
253+ unsigned char c = s [* index ];
254+ int codepoint = 0 ;
255+ int num_bytes = 0 ;
256+
257+ if ((c & 0x80 ) == 0 )
258+ {
259+ // 1-byte (ASCII).
260+ codepoint = c ;
261+ num_bytes = 1 ;
262+ }
263+ else if ((c & 0xE0 ) == 0xC0 )
264+ {
265+ // 2-byte.
266+ codepoint = (s [* index ] & 0x1F ) << 6 | (s [* index + 1 ] & 0x3F );
267+ num_bytes = 2 ;
268+ }
269+ else if ((c & 0xF0 ) == 0xE0 )
270+ {
271+ // 3-byte.
272+ codepoint = (s [* index ] & 0x0F ) << 12 | (s [* index + 1 ] & 0x3F ) << 6 | (s [* index + 2 ] & 0x3F );
273+ num_bytes = 3 ;
274+ }
275+ else if ((c & 0xF8 ) == 0xF0 )
276+ {
277+ // 4-byte.
278+ codepoint = (s [* index ] & 0x07 ) << 18 | (s [* index + 1 ] & 0x3F ) << 12 |
279+ (s [* index + 2 ] & 0x3F ) << 6 | (s [* index + 3 ] & 0x3F );
280+ num_bytes = 4 ;
281+ }
282+ else
283+ {
284+ // Invalid UTF-8.
285+ codepoint = '?' ; // Replace with '?'
286+ num_bytes = 1 ;
287+ }
288+
289+ * index += num_bytes - 1 ; // Move index forward by extra bytes processed.
290+ return codepoint ;
291+ }
292+
251293 /***************************
252294 * Flow-control functions. *
253295 ***************************/
@@ -511,34 +553,39 @@ static int pico8_print(lua_State* L)
511553 cursor_x = fix32_to_uint8 (luaL_checkunsigned (L , 2 ));
512554 }
513555
514- for (int i = 0 ; i < len ; i ++ )
556+ for (int i = 0 ; text [ i ] != '\0' ; i ++ )
515557 {
516- char c = text [ i ] ;
558+ int unicode = utf8_decode ( text , & i ) ;
517559
518- if (c == '\0' )
519- {
520- break ;
521- }
522- else if (c == '\n' )
560+ if (unicode == '\n' )
523561 {
524562 cursor_x = 0 ;
525563 cursor_y += 6 ;
526564 continue ;
527565 }
528- else if (c == '\r' )
566+ else if (unicode == '\r' )
529567 {
530568 cursor_x = 0 ;
531569 continue ;
532570 }
533571
534- if (c < 32 || c > 127 )
572+ int char_index ;
573+ if (unicode < 128 )
535574 {
536- continue ;
575+ // ASCII.
576+ char_index = unicode ;
577+ }
578+ else
579+ {
580+ // Unicode.
581+ char_index = 0 ;//map_unicode_to_pico8(unicode);2
537582 }
538- int char_index = c - 32 ;
539- blit_char_to_screen (char_index , cursor_x , cursor_y , color );
540- cursor_x += 4 ;
583+
584+ uint8_t w , h ;
585+ blit_char_to_screen (char_index , cursor_x , cursor_y , color , & w , & h );
586+ cursor_x += (unicode < 128 ) ? w + 1 : h + 1 ;
541587 }
588+
542589 cursor_y += 6 ;
543590 cursor_x = 0 ;
544591
0 commit comments