VM_CALL_NATIVE
is a GBVM instruction that allows you to execute raw Game Boy CPU assembly code (native code) directly from your GBVM script. This is a powerful, low-level instruction used for highly optimized operations or direct hardware manipulation that cannot be achieved efficiently or at all with standard GBVM instructions.
Purpose:
While GBVM provides a high-level abstraction for game logic, there are scenarios where direct access to the Game Boy’s hardware or extreme performance is required. VM_CALL_NATIVE
is used for:
It allows developers to drop down to the machine level when the GBVM’s capabilities are insufficient, bridging the gap between high-level scripting and low-level hardware control.
Syntax:
VM_CALL_NATIVE BANK, PTR
BANK
: The memory bank number where the native assembly routine (PTR
) is located. Similar to VM_CALL_FAR
, this handles bank switching for the native code.PTR
: The address (label) of the native assembly routine to be executed.Usage Example: Highly Optimized Pixel Manipulation
Imagine you want to implement a custom screen effect, like a unique fade or a pixel-by-pixel distortion, that requires direct manipulation of the Game Boy’s VRAM (Video RAM). You would write this routine in Game Boy assembly language and then call it using VM_CALL_NATIVE
.
; In your GBVM script:
; Call a native assembly routine for a custom screen fade effect
VM_CALL_NATIVE BANK(CUSTOM_FADE_ASM), CUSTOM_FADE_ASM
; ... continue with GBVM script after the native routine completes ...
; In a separate assembly file (e.g., custom_effects.s):
SECTION "Custom Fade ASM", ROMX
CUSTOM_FADE_ASM:
; --- Game Boy Assembly Code for custom fade effect ---
; This would involve direct manipulation of LCD registers, VRAM, etc.
; Example (simplified, not functional assembly):
ld hl, $8000 ; Load VRAM address
ld b, $20 ; Loop 32 times
.fade_loop:
ld a, [hl] ; Read pixel data
xor $FF ; Invert colors (example effect)
ld [hl+], a ; Write back and increment
dec b
jr nz, .fade_loop
; -----------------------------------------------------
ret ; Return from native routine
In this example, VM_CALL_NATIVE
jumps execution to the CUSTOM_FADE_ASM
label, which contains hand-optimized Game Boy assembly code. This assembly code directly manipulates the Game Boy’s hardware to achieve the desired effect. Once the ret
instruction in the assembly routine is hit, control returns to the GBVM script.
Analogy to other programming languages:
This is analogous to calling assembly language functions from a C program, or using inline assembly
within C/C++. In higher-level languages, it’s like using a FFI (Foreign Function Interface) to call functions written in a lower-level language (like C or Rust) for performance-critical tasks or to interact with system APIs not directly exposed by the high-level language.