AI-Assisted UEFI Chinese Bitmap Font Display: Implementation and Verification
This article explains how to implement Chinese bitmap font rendering in a UEFI firmware application with the help of AI-assisted coding tools. Using a vertical scrolling shooter as the practice project, it covers AI-generated INF/DSC build file drafts and their verification points, the full pipeline from UTF-8 decoding to Unicode-to-GB2312 mapping and HZK16 offset calculation, glyph rendering via the Graphics Output Protocol, game module organization (state machine, collision detection, object pools), and a firmware code validation checklist. Readers should verify the code in their own environment before adopting it.
1. Why Build a Vertical Scrolling Shooter on UEFI
UEFI firmware runs on bare metal. After the system boots, the firmware does not provide a standard C library, file system, or debugging tools the way an operating system does. However, UEFI Boot Services offer file protocols, the Graphics Output Protocol (GOP), and memory allocation interfaces, which a program can rely on.
A vertical scrolling shooter is a good practice project because it involves graphics rendering, keyboard input, a state machine, collision detection, and memory management all at once. These are exactly the problems encountered in firmware development, so this project is representative for observing what AI-assisted coding tools can do.
Firmware development typically has three categories of difficulties:
- Complex environment setup. The compiler, linker, and build scripts must match each other, and error messages are often hard to locate.
- Limited Chinese display support. The default UEFI font barely supports non-English characters, so displaying Chinese requires handling a bitmap font library yourself.
- A fragile runtime environment. With no operating system protection, a single out-of-bounds write can hang the system, placing high demands on resource management.
This article does not provide measured timings or runtime statistics. The code and checklists below are organized based on the UEFI specification, common EDK II practices, and the HZK16 font format. Readers should get them working in their own environment before adopting them.
2. Information to Record Before Reproducing
Firmware code is very sensitive to toolchain versions. Before reproducing, write the following information into your experiment log so others can verify your results. The purpose of recording is to determine whether a problem comes from the code or the environment when something goes wrong.
- EDK II source version, e.g.,
edk2-stable202405(use your actual version) - Compiler name and version, e.g., GCC5 or VS2019 / MSVC 19.29
- UEFI specification version and target architecture; this article uses X64 throughout
- The build command and the complete build log, e.g., saved as
build.log - The runtime environment: OVMF virtual machine or real hardware, plus the firmware version
- The font library source (e.g., the URL of the font distribution page) and its license terms, confirming that your use case is permitted
Update this record every time you change a toolchain version.
3. AI-Generated INF/DSC: Minimal Snippets and Verification Points
An AI tool can generate a first draft of the build description files based on the target architecture and module list. Below is a minimal INF snippet for a UEFI application, ShmupPkg/ShmupApp/ShmupApp.inf:
[Defines]INF_VERSION = 0x00010005BASE_NAME = ShmupAppFILE_GUID = 6F1B2C3D-4E5F-4A6B-8C7D-9E0F1A2B3C4DMODULE_TYPE = UEFI_APPLICATIONVERSION_STRING = 1.0[Sources]Main.cFont.cGame.c[Packages]MdePkg/MdePkg.dec[LibraryClasses]UefiApplicationEntryPointUefiLib[Protocols]gEfiGraphicsOutputProtocolGuid
In the platform DSC, you need to map the library instances for the X64 architecture and declare the module:
[LibraryClasses.X64]UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.infUefiLib|MdePkg/Library/UefiLib/UefiLib.inf[Components.X64]ShmupPkg/ShmupApp/ShmupApp.inf
The generated draft must be verified item by item:
- Is
FILE_GUIDunique? Regenerate it withuuidgento avoid duplicates with other modules. - Does
MODULE_TYPEmatch the purpose? Applications useUEFI_APPLICATION; drivers useUEFI_DRIVER. - Does every library listed in
[LibraryClasses]have a corresponding implementation path in the DSC? - Do the GUID names in
[Protocols]match the EDK II header files exactly? - Does the file name casing in
[Sources]match the files on disk? Linux is case-sensitive and Windows is not; migrating the same project between the two systems easily causes errors. - Does the build log contain warnings about unresolved symbols or missing libraries?
4. Bitmap-Based Chinese Display
The UEFI graphics interface has no built-in complete Chinese font. Displaying a Chinese character usually takes three steps:
- Decode the UTF-8 byte sequence into a Unicode code point. UTF-8 is a variable-length encoding; the font library itself does not store UTF-8 bytes.
- Convert the Unicode code point to a GB2312 zone-position code. The HZK16 font library is arranged by GB2312 zone and position, so Unicode code points cannot index it directly.
- Use the zone-position code to compute the offset, read out the 32-byte bitmap, expand it into pixels, and write it to the screen.
The conversion formula for step 2 is:
- Zone code = GB2312 high byte − 0xA0
- Position code = GB2312 low byte − 0xA0
- Offset = ((Zone − 1) × 94 + (Position − 1)) × 32
Each Chinese character in HZK16 occupies 32 bytes: 16 rows, 2 bytes per row, with the left 8 pixels in the first byte, the right 8 pixels in the second byte, and the most significant bit on the left.
Example: The Character “汉”
The UTF-8 encoding of “汉” is E6 B1 89, which decodes to U+6C49. Looking up the mapping table gives the GB2312 encoding 0xBA 0xBA, so the zone code is 26 and the position code is 26. The offset is ((26 − 1) × 94 + (26 − 1)) × 32 = 76000, or 0x128E0 in hexadecimal. Open the HZK16 file in a font editing tool, jump to that offset, and you should see the bitmap for “汉”.
Code: UTF-8 Decoding (Three-Byte Sequences)
CJK unified ideographs lie between U+4E00 and U+9FFF, all of which are three-byte UTF-8 sequences. The function below only handles the three-byte case, which is sufficient for commonly used Chinese characters:
// Handles only three-byte UTF-8 sequences (U+0800 to U+FFFF)EFI_STATUSUtf8ToCodePoint3 (IN CONST UINT8 *Utf8,OUT UINT32 *CodePoint){if (Utf8 == NULL || CodePoint == NULL) {return EFI_INVALID_PARAMETER;}// First byte must be 1110xxxx; the next two must be 10xxxxxxif (((Utf8[0] & 0xF0) != 0xE0) ||((Utf8[1] & 0xC0) != 0x80) ||((Utf8[2] & 0xC0) != 0x80)) {return EFI_INVALID_PARAMETER;}*CodePoint = ((UINT32)(Utf8[0] & 0x0F) << 12) |((UINT32)(Utf8[1] & 0x3F) << 6) |((UINT32)(Utf8[2] & 0x3F));return EFI_SUCCESS;}
Mapping Code Points to GB2312
GB2312 contains roughly 7,000 Chinese characters and symbols, and the mapping requires a table. The recommended approach is to use a script on the development machine to export the mapping from the official Unicode GB2312 mapping file or from iconv, sort it by Unicode code point in ascending order, and embed it in the firmware as a read-only array. At runtime, use binary search:
typedef struct {UINT16 Unicode; // Sorted in ascending orderUINT16 Gb2312; // High byte first, e.g., 0xBABA} UNI_GB_PAIR;// gUniGbTable and gUniGbTableCount are generated by an offline scriptEFI_STATUSUnicodeToGb2312 (IN UINT16 Cp,OUT UINT8 *Hi,OUT UINT8 *Lo){UINTN Left = 0;UINTN Right = gUniGbTableCount;UINTN Mid;while (Left < Right) {Mid = Left + (Right - Left) / 2;if (gUniGbTable[Mid].Unicode == Cp) {*Hi = (UINT8)(gUniGbTable[Mid].Gb2312 >> 8);*Lo = (UINT8)(gUniGbTable[Mid].Gb2312 & 0xFF);return EFI_SUCCESS;} else if (gUniGbTable[Mid].Unicode < Cp) {Left = Mid + 1;} else {Right = Mid;}}return EFI_NOT_FOUND;}
The source and license of the table must also be recorded. If the mapping data comes from a third party, verify its license terms.
Offset Calculation
#define FONT_WIDTH 16#define FONT_HEIGHT 16#define FONT_BYTES 32 // 16 rows x 2 bytes per rowEFI_STATUSGetHzk16Offset (IN UINT8 Hi,IN UINT8 Lo,OUT UINTN *Offset){UINTN Area;UINTN Pos;if (Hi < 0xA1 || Hi > 0xF7 || Lo < 0xA1 || Lo > 0xFE) {return EFI_NOT_FOUND;}Area = Hi - 0xA0;Pos = Lo - 0xA0;*Offset = ((Area - 1) * 94 + (Pos - 1)) * FONT_BYTES;return EFI_SUCCESS;}
Rendering a Single Glyph
The function below expands the 32-byte bitmap into a pixel buffer, then writes it to the screen in one call to GOP’s Blt. The function first checks whether the coordinates are out of bounds to avoid writing to memory outside the screen.
EFI_STATUSDrawGlyph16 (IN EFI_GRAPHICS_OUTPUT_PROTOCOL *Gop,IN CONST UINT8 *Bitmap, // 32-byte bitmapIN UINTN X,IN UINTN Y,IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL FgColor,IN EFI_GRAPHICS_OUTPUT_BLT_PIXEL BgColor){EFI_GRAPHICS_OUTPUT_BLT_PIXEL Buffer[FONT_WIDTH * FONT_HEIGHT];UINTN Row;UINTN Col;UINT8 Byte;UINT8 On;if (Gop == NULL || Bitmap == NULL) {return EFI_INVALID_PARAMETER;}// Bounds check: the written region must fit within the current display modeif (X + FONT_WIDTH > Gop->Mode->Info->HorizontalResolution ||Y + FONT_HEIGHT > Gop->Mode->Info->VerticalResolution) {return EFI_INVALID_PARAMETER;}// Bit expansion: row Row, column Col is at bit (7 - Col%8)// of Bitmap[Row*2 + Col/8]for (Row = 0; Row < FONT_HEIGHT; Row++) {for (Col = 0; Col < FONT_WIDTH; Col++) {Byte = Bitmap[Row * 2 + (Col >> 3)];On = (UINT8)((Byte >> (7 - (Col & 7))) & 1);Buffer[Row * FONT_WIDTH + Col] = (On != 0) ? FgColor : BgColor;}}// When Delta is 0, GOP computes the per-row byte count from Widthreturn Gop->Blt (Gop,Buffer,EfiBltBufferToVideo,0, 0,X, Y,FONT_WIDTH, FONT_HEIGHT,0);}
The call chain is: read three UTF-8 bytes, decode them into a code point, map it to GB2312, compute the offset, read 32 bytes from the font library file, then call DrawGlyph16. The font reading part requires file protocols or a font image loaded into memory, and each error branch should return its own status code.
5. Game Module Breakdown and Project Organization
The design below comes from common small-game structures; this article has not measured its performance.
Module Breakdown
Split the code by responsibility into the following files:
Main.c: the entry pointUefiMain, GOP initialization, and the main loop.Font.c: font loading, UTF-8 decoding, code point mapping, and glyph rendering.Game.c: the state machine and updates for the player, bullets, and enemies.Collision.c: rectangle collision checks.Pool.c: fixed-size object pools, replacing frequent dynamic allocation.
State Machine
typedef enum {StateTitle,StatePlaying,StatePaused,StateGameOver} GAME_STATE;typedef struct {GAME_STATE State;INT32 PlayerX;INT32 PlayerY;UINT32 Score;UINT32 PlayerHp;} GAME_CONTEXT;VOIDUpdateGame (IN OUT GAME_CONTEXT *Ctx,IN UINT16 Key){switch (Ctx->State) {case StateTitle:if (Key == KEY_ENTER) {Ctx->State = StatePlaying;}break;case StatePlaying:if (Key == KEY_P) {Ctx->State = StatePaused;break;}MovePlayer (Ctx, Key);UpdateBullets (Ctx);UpdateEnemies (Ctx);ResolveCollisions (Ctx);if (Ctx->PlayerHp == 0) {Ctx->State = StateGameOver;}break;case StatePaused:if (Key == KEY_P) {Ctx->State = StatePlaying;}break;case StateGameOver:if (Key == KEY_ENTER) {ResetGame (Ctx);Ctx->State = StateTitle;}break;}}
Collision Detection
Rectangle overlap testing is the most common method. Two rectangles collide only when they overlap on both axes:
typedef struct {INT32 X;INT32 Y;INT32 W;INT32 H;} RECT_I32;BOOLEANRectOverlap (IN CONST RECT_I32 *A,IN CONST RECT_I32 *B){return (A->X < B->X + B->W) &&(B->X < A->X + A->W) &&(A->Y < B->Y + B->H) &&(B->Y < A->Y + A->H);}
Memory Management
The number of bullets and enemies in the game has an upper bound, which makes fixed-size object pools a good fit: allocate once during initialization. At runtime you only take and return indices, avoiding calls to AllocatePool in the main loop. This also reduces the failure branches that allocation failures would require.
#define MAX_BULLETS 64typedef struct {RECT_I32 Bullets[MAX_BULLETS];UINT8 Active[MAX_BULLETS];} BULLET_POOL;INTNPoolAlloc (IN OUT BULLET_POOL *Pool){UINTN i;for (i = 0; i < MAX_BULLETS; i++) {if (Pool->Active[i] == 0) {Pool->Active[i] = 1;return (INTN)i;}}return -1; // Pool is full; the caller must handle this}
Build and Run
Run the following commands in the EDK II root directory and save the complete log. Use edksetup.sh on Linux and edksetup.bat on Windows:
source edksetup.shbuild -a X64 -t GCC5 -p ShmupPkg/ShmupPkg.dsc -b DEBUG 2>&1 | tee build.log
Copy the resulting ShmupApp.efi into the OVMF ESP directory at the path EFI/BOOT/BOOTX64.EFI, then boot in OVMF.
6. Firmware Code Validation Checklist
Every item should have a corresponding record. An item without a record cannot be considered passed.
- Compilation passes: the build log contains no errors and no unresolved symbols.
- Version records are complete: the EDK II version, compiler version, and other environment details listed in Section 2 are documented.
- Further checks (font file integrity, display correctness on the target environment, and resource cleanup) should each be verified and recorded in the same manner before the code is adopted.
