### Compile SGDK Library (Console) Source: https://github.com/stephane-d/sgdk/wiki/SGDK-Installation This command compiles the SGDK library using the Make utility. Ensure you replace `` with your actual installation directory. The successful compilation results in the creation of the `libmd.a` file. ```console \bin\make -f \makelib.gen ``` -------------------------------- ### New Basic HELLO_WORLD Sample (SGDK 1.6) Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt A new basic 'HELLO_WORLD' sample has been added to the project, providing a straightforward entry point for new users to get started with SGDK. ```c // added new basic HELLO_WORLD sample ``` -------------------------------- ### SGDK Hello World with Game Loop Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Hello-World An enhanced 'Hello World' example that includes an infinite loop to simulate a game loop. This structure is more typical for game development, although it lacks proper screen synchronization. ```c #include int main(u16 hard) { VDP_drawText("Hello Genny World!", 10, 13); while(TRUE) { // read input // move sprite // update score // draw current screen (logo, start screen, settings, game, gameover, credits...) } return 0; } ``` -------------------------------- ### SGDK Hello World with VDP_waitVSync Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Hello-World This example introduces VDP_waitVSync() to synchronize the game loop with the screen refresh rate. This is crucial for smooth animation and preventing graphical glitches by ensuring updates happen during vertical blanking. ```c #include int main(u16 hard) { VDP_drawText("Hello Genny World!", 10, 13); while(TRUE) { // read input // move sprite // update score // draw current screen (logo, start screen, settings, game, gameover, credits...) // wait for screen refresh VDP_waitVSync(); } return 0; } ``` -------------------------------- ### Log File Format Example Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Illustrates the default structure of a log file, where each line contains a hexadecimal offset followed by a symbol name, separated by a colon. ```text [HexOffset]: [SymbolName] ``` -------------------------------- ### Sjasm Command-Line Usage Examples Source: https://github.com/stephane-d/sgdk/blob/master/tools/sjasm/README.txt Demonstrates various ways to invoke the Sjasm assembler with different options for output control, listing inclusion, and include path specification. ```bash sjasm -l prog.asm assemble prog.asm to prog.out with prog.lst as listfile, include labels and code in listfile sjasm -ql prog.asm assemble prog.asm to prog.out with prog.lst as listfile, include only the label listing in listfile sjasm prog.asm -i/devel/inc assemble prog.asm to prog.out with prog.lst as listfile, include only code in listfile and search in /devel/inc for includefiles if not found in the current directory sjasm -lidevel -izooi prog.asm prog.com assemble prog.asm to prog.com with prog.lst as listfile, include code and label listing in listfile and search in zooi and devel for includefiles if not found in the current directory ``` -------------------------------- ### SGDK Assembler Pseudo-Op: PUSH Register List Example Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Example of using the PUSH pseudo-op with a list of registers to push multiple register pairs onto the stack. ```Assembly PUSH AF,BC ; push af / push bc ``` -------------------------------- ### Fixed-Point Type Prefix Examples Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt These examples illustrate the new naming convention for fixed-point functions. F16_ is used for fix16 operations, F32_ for fix32, and FF16_/FF32_ for fastfix variants. ```c // Example: Convert an integer to fix16 fix16 value = F16(10); // Example: Convert fix16 to integer int intValue = F16_toInt(value); // Example: Convert fix16 to fix32 fix32 value32 = F16_toFix32(value); ``` -------------------------------- ### Basic C Main Function for SGDK Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Hello-World This is the fundamental entry point for any SGDK application, similar to a standard C program. It receives a 'hard' parameter indicating the type of reset. SGDK performs automatic initializations before calling this function. ```c int main(u16 hard) { return 0; } ``` -------------------------------- ### ConvSym Append to ROM Example Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md This example shows how to convert an ASM68K symbol file to DEB2 format and append it to an existing ROM file. The '-a' option enables append mode, typically used for integrating symbol data into ROMs for debugging. ```sh convsym symbols.sym rom.bin -output deb2 -a ``` -------------------------------- ### SGDK Hello World with VDP_drawText Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Hello-World Demonstrates printing 'Hello World!' to the Genesis screen using the VDP_drawText function. It includes the necessary genesis.h header and a basic main function structure. Coordinates are in tile units. ```c #include int main(u16 hard) { VDP_drawText("Hello World!", 10, 13); return 0; } ``` -------------------------------- ### SGDK 1.6+ Hello World with SYS_doVBlankProcess Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Hello-World The recommended 'Hello World' structure for SGDK versions 1.6 and later. It replaces VDP_waitVSync() with SYS_doVBlankProcess() to handle VBlank tasks, including waiting for VSync, ensuring better compatibility and fewer potential bugs. ```c #include int main(u16 hard) { VDP_drawText("Hello Genny World!", 10, 13); while(TRUE) { // read input // move sprite // update score // draw current screen (logo, start screen, settings, game, gameover, credits...) // SGDK 1.6+ VBlank process SYS_doVBlankProcess(); } return 0; } ``` -------------------------------- ### SGDK Assembler Pseudo-Op: POP Register List Example Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Example of using the POP pseudo-op with a list of registers to pop multiple register pairs from the stack in reverse order. ```Assembly POP AF,BC ; pop bc / pop af <- reversed order ``` -------------------------------- ### SGDK: Execute VBlank Tasks with SYS_doVBlankProcess() Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Hello-World This C code snippet shows how to integrate SYS_doVBlankProcess() within the main function to ensure that all SGDK VBlank tasks are executed after a screen refresh. It's a common pattern for synchronizing game logic with the display. ```c // wait for screen refresh and do all SGDK VBlank tasks SYS_doVBlankProcess(); } return 0; } ``` -------------------------------- ### SGDK Eclipse CDT IDE - Environment Variables Source: https://github.com/stephane-d/sgdk/wiki/Setup-SGDK-with-Eclipse-(old) Demonstrates setting up environment and build variables within Eclipse CDT for SGDK development. The GDK variable is crucial for referencing the SGDK installation directory, which is used by makefiles and other build scripts. This ensures that SGDK's include files and tools are accessible during the build process. ```shell # Setting up Build Variables in Eclipse CDT: # Variable name: GDK # Type: Directory # Value: (path to SGDK installation) # Setting up Environment Variables in Eclipse CDT: # Name: GDK # Value: (full path to SGDK installation) ``` -------------------------------- ### Default ASM68K Listing Format Options Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Represents the default configuration for parsing ASM68K listing files when no specific options are provided. This includes settings for local symbol characters and macro handling. ```assembly -inopt "/localSign=@ /localJoin=. /ignoreMacroDefs+ /ignoreMacroExp- /addMacrosAsOpcodes+ /processLocals+" ``` -------------------------------- ### ConvSym Filter, Lowercase, and Append to ROM with Ref Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md A comprehensive example demonstrating advanced ConvSym usage. It converts a plaintext log file, filters out symbols starting with 'z80', converts remaining symbols to lowercase, appends the data to a ROM, and writes a 32-bit Big-Endian pointer to the symbol data at a specific offset in the ROM. ```sh convsym symbols.log rom.bin -input log -a -filter "z80.+ " -exclude -tolower -ref 200 ``` -------------------------------- ### Compile User Project (Windows Command Line) Source: https://github.com/stephane-d/sgdk/wiki/Setup-SGDK-basic Compiles a user's project using the SGDK makefile. This command should be run from the project's root directory and requires the GDK_WIN environment variable to be set. It produces an output ROM file. ```batch %GDK_WIN%\bin\make -f %GDK_WIN%\makefile.gen ``` -------------------------------- ### SGDK Assembler Pseudo-Op: SET Instruction Example Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Shows an example of using the SET instruction, an undocumented Z80 instruction supported by SGDK, within an assembly context. ```Assembly SET 4,(IX+4),C (aka LD C,SET 4,(IX+4)) is LD C,(IX+4) / SET 4,C / LD (IX+4),C ``` -------------------------------- ### Sprite Tiles Sharing and Animation Examples Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt This sample, located in 'sample/advanced', showcases advanced sprite techniques including tile sharing for efficiency and tile-based animation. ```c // In 'sample/advanced' folder: // * added sprite tiles sharing and tile animation examples ``` -------------------------------- ### Compile SGDK Library (Windows Command Line) Source: https://github.com/stephane-d/sgdk/wiki/Setup-SGDK-basic Compiles the SGDK library using the provided makefile. This command requires the GDK_WIN environment variable to be set correctly. The output is the static library file libmd.a. ```batch %GDK_WIN%\bin\make -f %GDK_WIN%\makelib.gen ``` -------------------------------- ### Compile SGDK Project (Release Profile) Source: https://github.com/stephane-d/sgdk/wiki/SGDK-Usage This command compiles an SGDK project using the default release profile. It requires the full path to the SGDK installation and the makefile. The output is a 'rom.bin' file in the 'out' directory. ```console \bin\make -f \makefile.gen ``` -------------------------------- ### Initialize MegaWiFi and Game Loop in SGDK Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md This snippet demonstrates the essential setup for using MegaWiFi in an SGDK project. It includes initializing the MegaWiFi module, detecting its presence and firmware version, and integrating the `mw_process()` task into the game loop. It requires including several MegaWiFi header files. ```C #include "mw/util.h" #include "mw/tsk.h" #include "mw/megawifi.h" // Length of the wflash buffer #define MW_BUFLEN 1440 // TCP port to use (set to Megadrive release year ;-) #define MW_CH_PORT 1989 // Command buffer static char cmd_buf[MW_BUFLEN]; // Runs mw_process() during idle time static void user_tsk(void) { while (1) { mw_process(); } } // MegaWiFi initialization static void megawifi_init(void) { uint8_t ver_major = 0, ver_minor = 0; char *variant = NULL; enum mw_err err; // Initialize MegaWiFi mw_init(cmd_buf, MW_BUFLEN); // Try detecting the module err = mw_detect(&ver_major, &ver_minor, &variant); if (MW_ERR_NONE != err) { // Megawifi cart not found! // [...] } else { // MegaWiFi found! // [...] } } // Run the game loop once per frame static void game_loop(void) { // Make sure this yields spare CPU time to user task wait_vblank(); read_input(); draw_screen(); play_sound(); game_logic(); } // Global initialization static void init(void) { // Initialize hardware and game // [...] // Configure user task TSK_userSet(user_tsk); // Initialize MegaWiFi megawifi_init(); } /// Entry point void main() { // Initialization init(); while (1) { game_loop(); } } ``` -------------------------------- ### Task System Initialization (C) Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt Introduces the TSK_init() method for easier and proper initialization of the multi-tasking system. This function simplifies the setup process for managing concurrent tasks within the SGDK environment. Multitask support is further detailed in the 'task' unit. ```c #include // Initialize the multitasking system void init_tasks() { TSK_init(); // Create and manage tasks here } ``` -------------------------------- ### Sending Data (Synchronous and Asynchronous) Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md Provides examples for sending data over a connection using both the synchronous `mw_send_sync()` and the asynchronous `mw_send()` methods. Includes details on callback usage for asynchronous operations. ```APIDOC ## Sending Data ### Description Sends data over an established connection using either synchronous or asynchronous methods. ### Method N/A (Function calls) ### Endpoint N/A ### Parameters #### Synchronous Send (`mw_send_sync`) - **channel** (int) - The channel number of the connection. - **data** (void*) - Pointer to the data buffer to send. - **data_length** (int) - The length of the data to send. - **timeout_seconds** (int) - Timeout in seconds for the operation. #### Asynchronous Send (`mw_send`) - **channel** (int) - The channel number of the connection. - **data** (void*) - Pointer to the data buffer to send. - **data_length** (int) - The length of the data to send. - **ctx** (void*) - User context pointer for the callback. - **callback** (function pointer) - Callback function to be called upon completion (`send_complete_cb`). ### Request Example #### Synchronous ```C enum mw_err err; err = mw_send_sync(1, data, data_length, 2 * fps); // Send data with 2-second timeout if (MW_ERR_NONE == err) { // Data sent } else { // Timeout, data was not sent } ``` #### Asynchronous ```C void send_complete_cb(enum lsd_status stat, void *ctx) { UNUSED_PARAM(ctx); if (LSD_STAT_COMPLETE == stat) { // Data successfully sent } else { // Sending data failed } } void send_example(void) { enum lsd_status stat; stat = mw_send(1, data, data_length, NULL, send_complete_cb); if (stat < 0) { // Sending failed } } ``` ### Response #### Success Response (200) Indicates that the data has been sent successfully. #### Response Example N/A ``` -------------------------------- ### Raster Scroll MD Graphics Guide Reference (Project Update) Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt Added a reference to the Raster Scroll MD graphics guide in the README, providing users with additional resources for advanced graphics techniques. ```markdown /* added Raster Scroll MD graphics guide reference */ ``` -------------------------------- ### Configure AS Listing Format Options Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Defines options for parsing AS assembler listing files, including local symbol joining, local label processing, and ignoring internal symbols. These options are available from version 2.8 onwards. ```assembly /localJoin=. /processLocals+ /ignoreInternalSymbols+ ``` -------------------------------- ### Sound Sample with XGM Driver (C) Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt Details the modification of the sound sample to include an example utilizing the XGM driver. This highlights the integration and usage of the XGM driver for sound playback within SGDK projects. ```C // Example usage of XGM driver (conceptual) XGM_loadMusic("mymusic.xgm"); XGM_startMusic(); XGM_loadSFX("mysound.xgm"); XGM_playSFX(0); ``` -------------------------------- ### Configure ASM68K Listing Format Options Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Specifies options for parsing ASM68K listing files. Options control local symbol characters, macro definition and expansion handling, and local label processing. Default options can be set using the -inopt argument. ```assembly /localSign=@ /localJoin=. /ignoreMacroDefs+ /ignoreMacroExp- /addMacrosAsOpcodes+ /processLocals+ ``` -------------------------------- ### SGDK VDP Plane Size Setup Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt Adds a 'setupVram' parameter to the VDP_setPlaneSize function. This parameter controls whether VRAM is initialized when setting the plane size, offering more control over VRAM allocation and management during screen setup. ```c // Set plane size and initialize VRAM VDP_setPlaneSize(plane, planeWidth, planeHeight, TRUE); // Set plane size without initializing VRAM (useful if VRAM is managed manually) VDP_setPlaneSize(plane, planeWidth, planeHeight, FALSE); ``` -------------------------------- ### SGDK C: Play Music and Sound Effects with XGM2 Source: https://context7.com/stephane-d/sgdk/llms.txt Shows how to initialize and control music playback using XGM2, including starting, pausing, resuming, and stopping music. It also covers playing PCM sound effects on specified channels and controlling PSG (Programmable Sound Generator) for basic sound effects like square waves. Requires resources declared in resources.res. ```c // Declare in resources.res: // XGM2 music_stage1 "music/stage1.vgm" // WAV sfx_jump "sfx/jump.wav" 5 void initSound() { // Start music playback (auto-loops) XGM2_play(&music_stage1); // Set music playback position XGM2_setMusicTempo(60); // Set tempo // Pause/resume music XGM2_pausePlay(); XGM2_resumePlay(); // Stop music XGM2_stopPlay(); } void playSoundEffects() { // Play PCM sound effect on auto-selected channel XGM2_setPCM(SFX_JUMP, sfx_jump, sizeof(sfx_jump)); XGM2_playPCM(SFX_JUMP, 1, SOUND_PCM_CH_AUTO); // Stop PCM playback XGM2_stopPCM(SOUND_PCM_CH1); // PSG sound (square wave) PSG_setEnvelope(PSG_ENVELOPE_CHN0, 15); // Volume PSG_setFrequency(PSG_TONE_CHN0, 500); // Frequency // Stop PSG PSG_setEnvelope(PSG_ENVELOPE_CHN0, 0); } // Direct YM2612 FM synthesis (advanced) void playFMSound() { // Set FM channel operator parameters YM2612_writeSafe(0x30, 0x1F); // Detune and multiply YM2612_writeSafe(0x40, 0x20); // Total level YM2612_writeSafe(0x50, 0x1F); // Attack rate and rate scaling YM2612_writeSafe(0x60, 0x05); // Decay rate YM2612_writeSafe(0x70, 0x02); // Sustain rate YM2612_writeSafe(0x80, 0x11); // Sustain level and release rate } ``` -------------------------------- ### ConvSym AS Listing to Log Conversion Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md This command converts an AS listing file into a log format symbol file. It explicitly specifies the input format as 'as_lst' and the output format as 'log'. ```sh convsym listing.lst symbols.log -input as_lst -output log ``` -------------------------------- ### Default AS Listing Format Options Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Specifies the default options for the AS assembler listing format parser, as of version 2.8. This configuration includes default settings for local symbol joining, local label processing, and internal symbol handling. ```assembly -inopt "/localJoin=. /processLocals+ /ignoreInternalSymbols+" ``` -------------------------------- ### Using size_t for Memory Allocation Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt This example shows the use of size_t for specifying memory buffer sizes, which is now standard in SGDK. ```c // Allocate a buffer of 1024 bytes size_t bufferSize = 1024; void* memoryBuffer = MEM_alloc(bufferSize); if (memoryBuffer) { // Use the buffer MEM_free(memoryBuffer); } ``` -------------------------------- ### ConvSym 'asm68k_sym' Local Symbol Options Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md This example shows the default options for the 'asm68k_sym' input format in ConvSym, which include processing local symbols. It specifies the characters used for local symbol designation ('@') and joining local labels with their parents ('.'). Local labels are processed by default ('+'). ```shell -inopt "/localSign=@ /localJoin=. /processLocals+" ``` -------------------------------- ### Configure ASM Output Format (SGDK) Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Configures the assembly output format for symbol lists, compatible with ASM68K and AS assemblers. Allows custom printf-compatible format strings for label and offset pairs. ```shell -outopt "/fmt='%s:\t\tequ\t$%X'" ``` ```shell -outopt "%s:\t\tequ\t$%X" ``` -------------------------------- ### Configure Text Input Format (SGDK) Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Specifies the format string for parsing input text files. Supports printf-like syntax for defining line formats. Defaults to '%s %X'. ```shell -inopt "/fmt='%s %X' /offsetFirst-" ``` -------------------------------- ### Default ConvSym Conversion (ASM to DEB2) Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md This command demonstrates the default usage of ConvSym, converting an ASM68K symbol file to the DEB2 format. It implicitly uses '-input asm68k_sym' and '-output deb2' due to their default settings. ```sh convsym symbols.sym symbols.deb2 ``` -------------------------------- ### Character and String Constant Examples - sjasm Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Provides examples of how to define character and string constants in sjasm. It shows the correct usage of single and double quotes for strings and characters, including using escape sequences for special characters like single and double quotes within strings. ```sjasm BYTE "stringconstant" ; single quote string constants can't be used with BYTE LD HL,'hl' LD HL,"hl" ; :( LD A,"7" ; :( LD A,'8' ; :) LD A,'\E' LD A,'"' LD A,"'" ``` -------------------------------- ### Configure LOG Output Format (SGDK) Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Configures the log output format for symbol lists, compatible with the 'log' input format. Allows custom printf-compatible format strings for offset and label pairs. ```shell -outopt "/fmt='%X: %s'" ``` ```shell -outopt "%X: %s" ``` -------------------------------- ### ConvSym 'txt' Input Format Options Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md These options configure the 'txt' input format for ConvSym, allowing for flexible parsing of generic text symbol files. The '/fmt' option defines the expected structure of each line, including hex offset, symbol type, and label name. '/offsetFirst' ensures the offset is read correctly. ```shell -inopt "/fmt='%X %*[TtBbCcDd] %511s /offsetFirst+" ``` -------------------------------- ### SGDK Assembler Pseudo-Op: ABYTEC Example Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Demonstrates the usage of the ABYTEC pseudo-op, which defines bytes with the last byte of a string having bit 7 set, and applies an offset. ```Assembly ABYTEC 0 "KIP" ; Same as BYTE "KI",'P'|128 ABYTEC 1 "ABC",0,"DE" ; Same as BYTE "BC",'D'|128,1,'E','F'|128 ``` -------------------------------- ### SGDK Joypad Input Event Handler Example Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Input Initializes the joypad handler and registers a callback function to process button presses and releases for JOY_1. It uses SGDK constants for button checks and waits for VSync in the main loop. ```c void myJoyHandler( u16 joy, u16 changed, u16 state) { if (joy == JOY_1) { if (state & BUTTON_START) { //player 1 press START button } else if (changed & BUTTON_START) { //player 1 released START button } } } int main( ) { JOY_init(); JOY_setEventHandler( &myJoyHandler ); while(1) { VDP_waitVSync(); } return 0; } ``` -------------------------------- ### Sjasm Local Label Definition Example Source: https://github.com/stephane-d/sgdk/blob/master/tools/sjasm/README.txt Shows how local labels are defined and accessed within modules in Sjasm assembly code. It demonstrates module and local label scoping. ```assembly module main Main: CALL SetScreen CALL vdp.Cls .loop: LD A,(.event) CALL ProcesEvent DJNZ .loop module vdp @SetScreen: .loop RET Cls: .loop DJNZ .loop RET endmodule Main.event ``` -------------------------------- ### Local Labels Example - sjasm Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Demonstrates the use of local labels within modules in sjasm. Labels starting with '@' are global. Labels starting with '.' are local to the preceding non-local label. Module names can be used to access labels from other modules using dot notation (e.g., 'vdp.Cls'). ```sjasm module main Main: ; main.Main CALL SetScreen ; SetScreen CALL vdp.Cls ; vdp.Cls .loop: ; main.Main.loop LD A,(.event) ; main.Main.event CALL ProcesEvent ; label not found: main.ProcesEvent DJNZ .loop ; main.Main.loop module vdp @SetScreen: ; SetScreen .loop ; vdp.SetScreen.loop RET Cls: ; vdp.Cls .loop ; vdp.Cls.loop DJNZ .loop ; vdp.Cls.loop RET endmodule Main.event ; main.Main.event byte 0 ``` -------------------------------- ### Configure Log File Format Options Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Sets options for parsing plain-text log files, which contain symbol names and their offsets. Options include specifying the separator character between offset and symbol, and whether to interpret offsets as decimal numbers. ```text /separator=: /useDecimal- ``` -------------------------------- ### Default Log File Format Options Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Defines the default configuration for parsing log files, where each line represents a symbol and its offset. This includes the default separator and the interpretation of offsets as hexadecimal. ```text -inopt "/separator=: /useDecimal-" ``` -------------------------------- ### SGDK Joypad Type Detection (Justifier Example) Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Input Initializes the joypad system and checks if the connected device on JOY_1 is a Konami Justifier. It displays a message if it is, as SGDK does not yet support it fully. VSync is used for timing. ```c int main( ) { JOY_init(); VDP_waitVSync(); if (JOY_getJoyID(JOY_1) & JOY_SUPPORT_JUSTIFIER) { VDP_drawText("JUSTIFIER NOT YET SUPPORTED", 10, 10); } while(1) { VDP_waitVSync(); } return 0; } ``` -------------------------------- ### Compile SGDK Project (Debug Profile) Source: https://github.com/stephane-d/sgdk/wiki/SGDK-Usage This command compiles an SGDK project with the debug profile enabled. This profile includes symbols and displays errors in the Gens KMod log. It requires the full path to the SGDK installation and the makefile. ```console \bin\make -f \makefile.gen debug ``` -------------------------------- ### SGDK C: DMA Transfer and Memory Management Source: https://context7.com/stephane-d/sgdk/llms.txt Provides examples for managing DMA (Direct Memory Access) transfers and memory operations. It shows how to set the DMA queue size, enable/disable DMA, queue transfers for VBlank, perform immediate transfers, and wait for completion. Memory functions include allocating/freeing heap memory, fast memory operations like memset and memcpy, and retrieving information about free RAM. ```c void setupDMA() { // Set DMA queue size (default is good for most cases) DMA_setQueueSize(32); // Enable/disable DMA VDP_setDMAEnabled(TRUE); } void transferData() { u16 data[100]; // Queue DMA transfer (executed during VBlank) DMA_queueDma(DMA_VRAM, data, TILE_USER * 32, 100 * 2, 2); // Immediate DMA transfer (use sparingly) DMA_doDma(DMA_VRAM, data, TILE_USER * 32, 100 * 2, 2); // Wait for DMA completion DMA_waitCompletion(); // Flush DMA queue (normally done by SYS_doVBlankProcess) DMA_flush(); } void memoryOperations() { // Allocate memory from heap u16* buffer = MEM_alloc(1024); if (buffer == NULL) { SYS_die("Out of memory"); } // Free memory MEM_free(buffer); // Fast memory operations memset(buffer, 0, 1024); // Clear memcpy(dest, src, 1024); // Copy // Get free memory u32 freeRAM = MEM_getFree(); u32 largestBlock = MEM_getLargestFreeBlock(); } ``` -------------------------------- ### Associate to an AP using MegaWiFi Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md This code demonstrates how to initiate and wait for an Access Point association using the MegaWiFi library. It calls `mw_ap_assoc()` to start the process and `mw_ap_assoc_wait()` to poll for success or failure within a specified timeout. Ensure `fps` is set appropriately for your machine's region (NTSC/PAL). ```C enum mw_err err; err = mw_ap_assoc(slot); if (MW_ERR_NONE == err) { err = mw_ap_assoc_wait(30 * fps); } if (MW_ERR_NONE == err) { // Association succeeded } else { // Association failed } ``` -------------------------------- ### PAL_getColor Example Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt This example demonstrates how to retrieve a color from the palette using PAL_getColor and shows that the returned value is in forced RGB333 format. ```c // Get the color from palette index 5 vdpColor color = PAL_getColor(5); // color will be in RGB333 format, with undefined bits set to 0. ``` -------------------------------- ### VDP_setVInterrupt Example Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt This example shows how to enable and disable vertical interrupts using the VDP_setVInterrupt function. This is typically used for synchronizing game logic with the screen refresh. ```c // Enable vertical interrupts VDP_setVInterrupt(TRUE); // Disable vertical interrupts VDP_setVInterrupt(FALSE); ``` -------------------------------- ### Loop Command in SGDK Source: https://github.com/stephane-d/sgdk/blob/master/bin/xgm.txt Specifies a loop point within the music data. The command contains an address that indicates where to jump back to, relative to the start of the music data block, enabling music looping. ```assembly ; $7E dddddd 4 ; Loop command, used for music looping sequence: ; dddddd = address where to loop relative to the start of music data bloc. ``` -------------------------------- ### M3D_setRotation Degree Input Example Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt This example shows how to use M3D_setRotation with angles specified in degrees. The function internally converts these degrees to the required fix16 format. ```c // Set rotation to 45 degrees around the X-axis M3D_setRotation(myObject, 45, 0, 0); ``` -------------------------------- ### SGDK Eclipse CDT IDE - Include Paths Source: https://github.com/stephane-d/sgdk/wiki/Setup-SGDK-with-Eclipse-(old) Configures the include paths for a C/C++ project in Eclipse CDT to include the SGDK header files. This allows your project's source code to reference the types, functions, and macros defined within the SGDK library. It is essential for successful compilation of Genesis projects. ```xml
``` -------------------------------- ### Convert SGDK Symbols using ConvSym CLI Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md This command-line invocation demonstrates how to use ConvSym to convert SGDK symbols from a text file to a binary ROM file. It specifies the input format as 'txt', defines a custom format string for parsing the symbol file, includes both ROM and RAM symbols, appends to the output file, and sets a reference pointer for debugging. ```shell convsym out/symbol.txt out/rom.bin -in txt -inopt "/fmt='%X %*[TtBbCcDd] %511s /offsetFirst+" -range 0 FFFFFF -a -ref @MDDBG__SymbolTablePtr ``` -------------------------------- ### KDebug Logging Methods (C) Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt Provides examples of using the KDebug logging methods introduced in SGDK for debugging purposes. These include general logging (KLog) and specific logging for unsigned (KLog_Uxx) and signed (KLog_Sxx) integer types. ```C KLog("Initialization complete."); u16 value = 123; KLog_U16(value); s32 signedValue = -456; KLog_S32(signedValue); ``` -------------------------------- ### GameJolt API Initialization Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md Initializes the GameJolt API by providing the endpoint, game credentials, username, user token, a command buffer, buffer size, and timeout. The provided buffer is used for all communication and must be copied if data needs to be preserved before subsequent calls. Recommended buffer size is at least 2 KiB. ```c if (gj_init("https://api.gamejolt.com/api/game/v1_2/", GJ_GAME_ID, GJ_PRIV_KEY, username, user_token, cmd_buf, MW_BUFLEN, MS_TO_FRAMES(30000))) { // Handle init error } ``` -------------------------------- ### Configure DEB2 Output Format (SGDK) Source: https://github.com/stephane-d/sgdk/blob/master/tools/convsym/README.md Configures the DEB2 output format, used for debug symbols compatible with MD Debugger and Error Handler. Supports an option to favor the last processed label when offsets are the same. ```shell -outopt "/favorLastLabels-" ``` -------------------------------- ### Program Initialization and WiFi Detection Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md This section details the necessary steps to initialize the MegaWiFi module, set up the game loop, and create a user task to process WiFi events. It also includes code for detecting the WiFi module and its firmware version. ```APIDOC ## Program Initialization ### Description Initializes MegaWiFi, the game loop, and a user task for `mw_process()`. Detects WiFi module presence and firmware version. ### Method N/A (Initialization code) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response N/A #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### SGDK Mouse Input Event Handler Example Source: https://github.com/stephane-d/sgdk/wiki/Tuto-Input Initializes joypad and mouse event handlers. The mouse handler updates global mouse coordinates based on deltas only when the left button is pressed. It also registers a joypad handler for button events. ```c s16 mouseX=0, mouseY=0; void myMouseHandler( u16 joy, s8 xDelta, s8 yDelta, u16 buttonState) { char str[4]; u8 mouseState; //move only if left pressed if ( buttonState & MOUSE_LEFT ) { mouseX+= xDelta; if (mouseX<0) mouseX = 0; mouseY+= yDelta; if (mouseY<0) mouseY = 0; } } int main( ) { JOY_init(); JOY_setEventHandler( &myJoyHandler ); //mouse button pressed is handled like a joypad, mainly to handle start JOY_setMouseEventHandler( &myMouseHandler ); while(1) { VDP_waitVSync(); } return 0; } ``` -------------------------------- ### SGDK Core Initialization and Main Loop (C) Source: https://context7.com/stephane-d/sgdk/llms.txt This snippet demonstrates the fundamental structure of an SGDK application. It initializes the VDP, sets screen and plane dimensions, and enters the main game loop. The `SYS_doVBlankProcess()` function is crucial for handling VDP, sound, and input updates at the end of each frame. ```c #include int main(bool hardReset) { // SGDK automatically initializes VDP, controllers, sound driver // hardReset indicates if this is a power-on or soft reset // Initialize VDP to default state VDP_init(); // Set screen resolution (320x224 for NTSC) VDP_setScreenWidth320(); VDP_setScreenHeight224(); // Set background plane size (64x32 tiles) VDP_setPlaneSize(64, 32, TRUE); // Game initialization u16 frameCounter = 0; while(TRUE) { // Game logic here frameCounter++; // Always call at end of frame - handles DMA queue flush, // palette fading, joypad polling, sound driver sync SYS_doVBlankProcess(); } return 0; } ``` -------------------------------- ### SGDK Assembler Pseudo-Op: RRC Instruction Example Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Demonstrates the usage of the RRC (Rotate Right through Carry) instruction, an undocumented Z80 instruction supported by SGDK, in an assembly example. ```Assembly RRC (IY),A (aka LD A,RRC (IY+0)) is LD A,(IY) / RRC A / LD (IY),A ``` -------------------------------- ### Sprite Masking Example in 'sample/fx' Source: https://github.com/stephane-d/sgdk/blob/master/changelog.txt This sample, found in the 'sample/fx' folder, provides an example of sprite masking, a technique used to create complex visual effects by selectively revealing or hiding parts of a sprite. ```c // In 'sample/fx' folder: // * added sprite masking example ``` -------------------------------- ### C: HTTP Request Helper Functions Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md Provides utility functions for initiating, receiving, and finishing HTTP requests. `http_begin` sets up the request, `sync_recv` handles synchronous data reception, and `http_finish` completes the transaction and retrieves the response. These functions abstract the low-level `megawifi` module calls. ```C static int http_begin(enum mw_http_method type, const char *url, unsigned int len) { enum mw_err err; err = mw_http_url_set(url); if (!err) { err = mw_http_method_set(type); } if (!err) { err = mw_http_open(len); } return err; } // Tries to synchronously receive exactly the indicated data length static int sync_recv(uint8_t ch, char *buf, int len, uint16_t tout_frames) { int recvd = 0; int err = 0; uint8_t get_ch = ch; int16_t get_len; while (err == 0 && recvd < len) { get_len = len - recvd; err = mw_recv_sync(&get_ch, buf + recvd, &get_len, tout_frames); if (!err) { if (get_ch != ch) { err = -1; } else { recvd += get_len; } } } return err; } // Performs final steps of an HTTP request static int http_finish(char *recv_buf, unsigned int *len) { enum mw_err err; uint32_t content_len = 0; err = mw_http_finish(&content_len, MS_TO_FRAMES(60000)); err = err >= 200 && err <= 300 ? 0 : err; if (content_len > b.msg_buf_len) { err = -1; } if (!err && content_len) { err = sync_recv(MW_HTTP_CH, recv_buf, content_len, 0); } if (!err && len) { *len = content_len; } return err; } ``` -------------------------------- ### Eclipse CDT Build Command for SGDK Source: https://github.com/stephane-d/sgdk/wiki/Setup-SGDK-with-Eclipse-(old) Configures the build command for a Makefile Project in Eclipse CDT to use SGDK's makefile.gen. This ensures that the correct build process is invoked for Genesis projects. It defines the path to the make executable and the specific makefile to use. ```xml org.eclipse.cdt.core.cnature org.eclipse.cdt.core.make nature org.eclipse.cdt.core.makebuilder org.eclipse.cdt.core.cnature org.eclipse.cdt.core.make nature ``` -------------------------------- ### SGDK PSG Music ID Table Structure Source: https://github.com/stephane-d/sgdk/blob/master/bin/xgm2.txt The PSGID table stores the starting addresses for PSG music data tracks. Similar to the FMID table, each entry is 2 bytes representing the address divided by 256. An empty entry is indicated by $FFFF. ```assembly ; PSGID: PSG music id table ; This table contain the start address of PSG music data for all tracks (128 entries = 256 bytes) ; Each entry of the table consist of 2 bytes representing the address / 256: ; entry+$0: PSG music data block address / 256 ; An empty entry should have its address set to $FFFF. ``` -------------------------------- ### Tile and Image Loading to VRAM in C Source: https://context7.com/stephane-d/sgdk/llms.txt Demonstrates loading various graphical assets like images, tilesets, and fonts into VRAM using the SGDK library. It covers loading entire images, specific tilesets, and manual tile data, along with map loading. ```c // Declare in resources.res: // IMAGE bg_image "gfx/background.png" NONE // TILESET player_tiles "gfx/player.png" NONE void loadGraphics() { // Load entire image to background VDP_drawImageEx(BG_A, &bg_image, TILE_ATTR_FULL(PAL0, 0, FALSE, FALSE, 1), 0, 0, // x, y position in tiles FALSE, // load palette DMA); // transfer method // Load tileset to VRAM at specific index u16 tileIndex = TILE_USER_INDEX; VDP_loadTileSet(&player_tiles, tileIndex, DMA); // Load font VDP_loadFont(&font_custom, DMA); // Manual tile data loading u32 tiles[8] = {0x11111111, 0x22222222, 0x33333333, 0x44444444, 0x55555555, 0x66666666, 0x77777777, 0x88888888}; VDP_loadTileData(tiles, tileIndex + 100, 1, DMA); } // Declare map in resources.res: // MAP level1_map "maps/level1.png" level1_tileset NONE 0 void loadMap() { // Load map to background plane VDP_setMapEx(BG_B, level1_map.tilemap, TILE_ATTR_FULL(PAL1, 0, FALSE, FALSE, 1), 0, 0, // destination x, y in tiles 0, 0, // source x, y in map 40, 28, // width, height in tiles DMA); } ``` -------------------------------- ### Get Last GameJolt API Error (C) Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md Retrieves detailed error information after a GameJolt API function has failed. Call this immediately after the failed function call to get specific error context. ```C // Assume a previous API call failed, e.g., returned false or NULL char *error_message = gj_get_error(); if (error_message) { // Log or display the error_message } ``` -------------------------------- ### User Task for Game Logic and Network Processing in C Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md Demonstrates a user task structure for managing game logic updates and processing network events concurrently. It highlights the importance of careful timing when interacting with the VDP to avoid hard-to-debug issues. ```c static void user_tsk(void) { while (1) { update_game_logic(); mw_process(); } } ``` -------------------------------- ### Local and Global Label Behavior - sjasm Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Illustrates how local labels (starting with '.') and global labels (starting with '@') are handled with module definitions. It shows how labels are scoped and potential duplicate label errors when local labels are reused within different scopes. ```sjasm MODULE xxx Label ; xxx.Label .Local ; xxx.Label.Local @Label ; Label .Local ; xxx.Label.Local => duplicate label error @Label2 ; Label2 .Local ; xxx.Label2.Local @yyy.Local ; yyy.Local yyy.Local ; xxx.yyy.Local ``` -------------------------------- ### C: Generic HTTP GET Request Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md Implements a generic HTTP GET request that does not include a data payload. It utilizes the `http_begin` and `http_finish` helper functions to perform the request and retrieve the response. The function returns the HTTP status code or -1 if the request fails. ```C /**************************************************************************** * \brief Generic HTTP GET request without data payload. * * \param[in] url URL for the request. * \param[out] recv_buf Buffer used for HTTP response data. * \param[out] len Length of the response. * * \return HTTP status code, or -1 if request was not completed. ****************************************************************************/ int http_get(const char *url, char *recv_buf, unsigned int *len) { enum mw_err err; err = http_begin(MW_HTTP_METHOD_GET, url, 0); if (!err) { err = http_finish(recv_buf, len); } return err; } ``` -------------------------------- ### Source File Line Format - sjasm Source: https://github.com/stephane-d/sgdk/blob/master/bin/sjasm.txt Defines the standard format for lines in sjasm source files: 'Label Operator Operand Comment'. All fields are optional. Lines without a label must start with whitespace. Comments can be single-line (starting with ';' or '//') or multi-line (enclosed in '/*' and '*/'). ```text ; comment // comment ld /* comment */ a,80 /* comment */ ld /* but this won't be ld a,3! */ a,3 ``` -------------------------------- ### Fetch Data from GameJolt Cloud using Wildcard (C) Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md Retrieves data from the GameJolt cloud store using a key pattern with a wildcard character ('*'). Returns an error if fetching fails. ```C char *data; data = data_store_fetch("the_meaning_of_.*"), false); if (!data) { // Error fetching data return; } cloud_computed_meaning_of_life_is(data); ``` -------------------------------- ### Manage Game Sessions (C) Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/mw/README.md Manages GameJolt player sessions by opening a session and periodically pinging it to keep it active. Pinging is recommended every 30 seconds. ```C // Do this just once to open the session if (gj_sessions_open()) { // Something went wrong, session not opened } // [...] // Do this every 30 seconds approximately if (gj_sessions_ping(true)) { // Something went wrong, ping failed } ``` -------------------------------- ### Initialize MiniMusic Sound Driver Source: https://github.com/stephane-d/sgdk/blob/master/src/ext/minimusic/doc/api-c.md Initializes the MiniMusic sound driver. It requires a pointer to the sound data and its size. The sound data format is described in doc/format.md and must not exceed 6144 bytes. ```c #include "minimus.h" // ... sound_data definition ... minimusic_init(&sound_data, sizeof(sound_data)); ```