mvbg

VM_CALL_FAR

VM_CALL_FAR is a GBVM instruction used to call a routine (function) that resides in a different memory bank than the currently executing code. This is crucial for Game Boy development due to the console’s banked memory architecture.

Purpose: On the Game Boy, the total ROM (Read-Only Memory) size can be much larger than the amount of memory directly accessible by the CPU at any given time. This larger memory is divided into “banks.” To access code or data in a different bank, you need to explicitly switch to that bank. VM_CALL_FAR handles this bank switching automatically, allowing your script to execute code located anywhere in the ROM.

This is essential for organizing large game logic, separating different game states (e.g., title screen, world map, battle), or accessing shared utility functions that might be stored in a common bank.

Syntax:

VM_CALL_FAR BANK, ADDR

Usage Example: Calling a Scene Initialization Routine

Imagine your game has different scenes (e.g., a town, a dungeon, a shop). Each scene might have its own initialization routine that sets up actors, loads backgrounds, and defines event triggers. These routines might be spread across different memory banks to optimize memory usage.

; In Bank 1 (e.g., main game logic bank)

; Call the initialization routine for the Town Scene, located in Bank 2
VM_CALL_FAR BANK(TOWN_SCENE_INIT), TOWN_SCENE_INIT

; ... rest of main game logic ...

; In Bank 2 (e.g., scene data bank)

TOWN_SCENE_INIT:
  ; Load town background
  VM_LOAD_TILESET TILESET_TOWN
  ; Place town NPCs
  VM_ACTOR_SET_POS NPC_TOWN_GUARD, 10, 5
  VM_ACTOR_SET_POS NPC_MERCHANT, 15, 8
  ; ... other town-specific setup ...
  VM_RET ; Return from the routine

In this example, when the game needs to transition to the town scene, VM_CALL_FAR is used to jump to the TOWN_SCENE_INIT routine, even though it resides in a different memory bank. The GBVM handles the necessary bank switching behind the scenes, ensuring the code executes correctly.

Analogy to other programming languages: While modern operating systems and programming languages abstract away memory banking, VM_CALL_FAR is conceptually similar to dynamically loading a DLL (Dynamic Link Library) or a shared library in a desktop application, or importing a module from a different file in Python. You are accessing code that isn’t directly part of your current execution segment, requiring a specific mechanism to reach it. For embedded systems or older consoles, explicit memory management like banking is common.