### IApp Interface Implementation Source: https://context7.com/confettifx/the-forge/llms.txt This example demonstrates a minimal implementation of the IApp interface, covering initialization, resource path setup, renderer and queue creation, and the basic lifecycle methods. ```APIDOC ## IApp — Application Lifecycle Interface The entry point for all The Forge applications. Subclass `IApp` and implement the pure virtual methods: `Init`/`Exit` (one-time setup), `Load`/`Unload` (device-dependent resources with reload type), `Update` (per-frame CPU logic), and `Draw` (GPU command recording). Use the `DEFINE_APPLICATION_MAIN(MyApp)` macro for cross-platform `main` entry. ### Description This section provides a C++ code example showcasing a minimal implementation of the `IApp` interface. It includes: - **Initialization (`Init`)**: Setting up the file system paths for resources (shaders, textures, meshes, GPU configs) and initializing the renderer and graphics queue. - **Exiting (`Exit`)**: Cleaning up the graphics queue, renderer, and file system. - **Loading (`Load`)**: A placeholder for creating swap chains, pipelines, and descriptor sets. - **Unloading (`Unload`)**: An empty implementation for resource unloading. - **Updating (`Update`)**: A placeholder for per-frame CPU logic, emphasizing no GPU calls. - **Drawing (`Draw`)**: A placeholder for recording and submitting command buffers. - **Application Naming (`GetName`)**: Returning the application's name. ### Usage To use this, subclass `IApp` and implement the required virtual methods. Then, use the `DEFINE_APPLICATION_MAIN` macro to define your application's entry point. ### Code Example ```cpp // MyApp.cpp — minimal cross-platform application #include "Application/Interfaces/IApp.h" #include "Graphics/Interfaces/IGraphics.h" #include "Resources/ResourceLoader/Interfaces/IResourceLoader.h" class MyApp : public IApp { public: Renderer* pRenderer = NULL; Queue* pGraphicsQueue = NULL; bool Init() override { // Initialize file system paths FileSystemInitDesc fsDesc = {}; fsDesc.pAppName = "MyApp"; initFileSystem(&fsDesc); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_SHADER_BINARIES, "Shaders/Binary"); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_TEXTURES, "Textures"); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_MESHES, "Meshes"); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_GPU_CONFIG, "GPUCfg"); // Create renderer RendererDesc rendererDesc = {}; initRenderer(GetName(), &rendererDesc, &pRenderer); if (!pRenderer) { ShowUnsupportedMessage("Renderer failed to init"); return false; } // Create graphics queue QueueDesc queueDesc = {}; queueDesc.mType = QUEUE_TYPE_GRAPHICS; queueDesc.mFlag = QUEUE_FLAG_INIT_MICROPROFILE; initQueue(pRenderer, &queueDesc, &pGraphicsQueue); return true; } void Exit() override { exitQueue(pRenderer, pGraphicsQueue); exitRenderer(pRenderer); exitFileSystem(); } bool Load(ReloadDesc* pReloadDesc) override { // Create swap chain, pipelines, descriptor sets here return true; } void Unload(ReloadDesc* pReloadDesc) override {} void Update(float deltaTime) override { // CPU input/math updates — no GPU calls here } void Draw() override { // Record and submit command buffers } const char* GetName() override { return "MyApp"; } }; DEFINE_APPLICATION_MAIN(MyApp) ``` ``` -------------------------------- ### Build and Run OS X Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Application/ThirdParty/OpenSource/Fontstash/README.md Steps to build and run the Fontstash example project on OS X using premake4 and make. This includes generating the makefile, building, and executing the example. ```bash $ premake4 gmake $ cd build/ $ make $ ./example ``` -------------------------------- ### Guest Application (Plugin) Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Application/ThirdParty/OpenSource/cr/README.md Example of the guest application (real application) structure for live-reloading with cr.h. Implement the cr_main function to handle different operations. ```c CR_EXPORT int cr_main(struct cr_plugin *ctx, enum cr_op operation) { assert(ctx); switch (operation) { case CR_LOAD: return on_load(...); // loading back from a reload case CR_UNLOAD: return on_unload(...); // preparing to a new reload case CR_CLOSE: ...; // the plugin will close and not reload anymore } // CR_STEP return on_update(...); } ``` -------------------------------- ### Compile Example Project with Premake4 Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Application/ThirdParty/OpenSource/Fontstash/README.md Commands to compile the Fontstash example project using premake4. This involves generating platform-specific build files and then using the native build tools. ```bash premake4 xcode4 premake4 vs2010 premake4 gmake ``` -------------------------------- ### Host Application Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Application/ThirdParty/OpenSource/cr/README.md Example of a host application using cr.h to manage live-reloading of a plugin. Ensure CR_HOST is defined before including cr.h. ```c #define CR_HOST // required in the host only and before including cr.h #include "../cr.h" int main(int argc, char *argv[]) { // the host application should initalize a plugin with a context, a plugin cr_plugin ctx; // the full path to the live-reloadable application cr_plugin_open(ctx, "c:/path/to/build/game.dll"); // call the update function at any frequency matters to you, this will give // the real application a chance to run while (!cr_plugin_update(ctx)) { // do anything you need to do on host side (ie. windowing and input stuff?) } // at the end do not forget to cleanup the plugin context cr_plugin_close(ctx); return 0; } ``` -------------------------------- ### Starting Visual Studio with Environment Variables Set Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Utilities/ThirdParty/OpenSource/mcpp/mcpp-manual.html Use the 'Visual Studio command prompt' to start Visual Studio and ensure environment variables like include directories are set correctly. This is crucial for proper compilation and debugging. ```shell devenv /useenv ``` ```shell vcexpress /useenv ``` -------------------------------- ### Install CodeLite with Yay Source: https://github.com/confettifx/the-forge/blob/master/README.md Installs the CodeLite IDE using the 'yay' AUR helper. Ensure 'yay' is installed before running this command. ```bash yay -S codelite ``` -------------------------------- ### Install gltfpack via npm Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Tools/ThirdParty/OpenSource/meshoptimizer/README.md Install the gltfpack command-line tool globally using npm. ```bash npm install -g gltfpack ``` -------------------------------- ### Install Development Tools with Pacman Source: https://github.com/confettifx/the-forge/blob/master/README.md Installs essential development tools and libraries required for building applications on Steam Deck. Many packages may only be partially installed by default. ```bash sudo pacman -S glibc linux-api-headers git git-lfs base-devel libjpeg zlib curl libtiff libpng pcre2 expat libsecret gtk3 glib2 xz sdl fontconfig pango harfbuzz cairo gdk-pixbuf2 libx11 xorgproto atk freetype2 wayland libnotify qt5-base sqlite3 libssh linux-neptune-headers libarchive libxrandr libxrender systemd systemd-libs ``` -------------------------------- ### Install Yay AUR Helper Source: https://github.com/confettifx/the-forge/blob/master/README.md Installs the 'yay' AUR helper, which is used to install packages from the Arch User Repository. This involves cloning the repository, building, and installing the package. ```bash mkdir /home/deck/.yay-install && cd /home/deck/.yay-install ``` ```bash git clone https://aur.archlinux.org/yay-bin.git . ``` ```bash makepkg -si ``` -------------------------------- ### Sequential Option Handling Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Command-line options are processed sequentially, allowing for cumulative effects. This example shows setting a variable and then printing it before executing a script. ```bash $ lua -e'a=1' -e 'print(a)' script.lua ``` -------------------------------- ### Lua Function Definition Examples Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Illustrates function definitions with different parameter and vararg configurations. ```lua function f(a, b) end function g(a, b, ...) end function r() return 1,2,3 end ``` -------------------------------- ### Run Pre-Build Scripts Source: https://github.com/confettifx/the-forge/blob/master/README.md Execute pre-build scripts to download assets and install extensions. Use PRE_BUILD.bat for Windows and PRE_BUILD.command for Linux/Mac. ```batch PRE_BUILD.bat ``` ```bash PRE_BUILD.command ``` -------------------------------- ### Executing a String with 'arg' Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html This example demonstrates how the `arg` table is populated when no script is provided and a string is executed using the `-e` option. The option itself is stored at `arg[1]`. ```lua print(arg[1]) ``` -------------------------------- ### Full Frame Render Loop Example Source: https://context7.com/confettifx/the-forge/llms.txt Demonstrates a typical full frame render loop, including resource initialization, command buffer recording, submission, and presentation. This example covers the essential steps for rendering a frame using the IGraphics API. ```APIDOC ## Full Frame Render Loop Example This example illustrates the complete process of rendering a single frame, from initializing graphics resources to submitting commands and presenting the final image. ### Initialization ```cpp // Renderer and related structures Renderer* pRenderer = NULL; Queue* pQueue = NULL; CmdPool* pCmdPool = NULL; Cmd** ppCmds = NULL; SwapChain* pSwapChain = NULL; Fence* pRenderFence = NULL; Semaphore* pImageSemaphore = NULL; Pipeline* pPipeline = NULL; const uint32_t IMAGE_COUNT = 2; // Initialize Renderer RendererDesc rendererDesc = {}; initRenderer("Demo", &rendererDesc, &pRenderer); // Initialize Graphics Queue QueueDesc qDesc = { QUEUE_TYPE_GRAPHICS }; initQueue(pRenderer, &qDesc, &pQueue); // Initialize Command Pool CmdPoolDesc poolDesc = { pQueue }; initCmdPool(pRenderer, &poolDesc, &pCmdPool); // Initialize Command Buffers CmdDesc cmdDesc = { pCmdPool }; initCmd_n(pRenderer, &cmdDesc, IMAGE_COUNT, &ppCmds); // Initialize Synchronization Primitives initFence(pRenderer, &pRenderFence); initSemaphore(pRenderer, &pImageSemaphore); // Initialize Swap Chain SwapChainDesc scDesc = {}; scDesc.mWindowHandle = pWindow->handle; scDesc.mPresentQueueCount = 1; scDesc.ppPresentQueues = &pQueue; scDesc.mWidth = mSettings.mWidth; scDesc.mHeight = mSettings.mHeight; scDesc.mImageCount = IMAGE_COUNT; scDesc.mColorFormat = getSupportedSwapchainFormat(pRenderer, &scDesc, COLOR_SPACE_SDR_SRGB); addSwapChain(pRenderer, &scDesc, &pSwapChain); ``` ### Draw Frame ```cpp // Acquire next image from swap chain uint32_t imageIndex = 0; acquireNextImage(pRenderer, pSwapChain, pImageSemaphore, NULL, &imageIndex); // Get command buffer for the current image Cmd* pCmd = ppCmds[imageIndex]; resetCmdPool(pRenderer, pCmdPool); beginCmd(pCmd); // Transition swap chain image to render target state RenderTargetBarrier rtBarrier = { pSwapChain->ppRenderTargets[imageIndex], RESOURCE_STATE_PRESENT, RESOURCE_STATE_RENDER_TARGET }; cmdResourceBarrier(pCmd, 0, NULL, 0, NULL, 1, &rtBarrier); // Bind render target and clear BindRenderTargetsDesc bindDesc = {}; bindDesc.mRenderTargetCount = 1; bindDesc.mRenderTargets[0] = { pSwapChain->ppRenderTargets[imageIndex], LOAD_ACTION_CLEAR, STORE_ACTION_STORE, { .rgba = {0.2f,0.2f,0.2f,1.0f} } }; cmdBindRenderTargets(pCmd, &bindDesc); cmdSetViewport(pCmd, 0, 0, (float)mSettings.mWidth, (float)mSettings.mHeight, 0.0f, 1.0f); cmdSetScissor (pCmd, 0, 0, mSettings.mWidth, mSettings.mHeight); // Bind pipeline, descriptor set, and issue draw call cmdBindPipeline(pCmd, pPipeline); cmdBindDescriptorSet(pCmd, imageIndex, pDescriptorSet); cmdDrawIndexed(pCmd, indexCount, 0, 0); // Add debug markers cmdBeginDebugMarker(pCmd, 1, 0, 0, "Main Pass"); cmdEndDebugMarker(pCmd); // Transition swap chain image to present state rtBarrier = { pSwapChain->ppRenderTargets[imageIndex], RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_PRESENT }; cmdResourceBarrier(pCmd, 0, NULL, 0, NULL, 1, &rtBarrier); endCmd(pCmd); // Submit command buffer and present QueueSubmitDesc submitDesc = {}; submitDesc.ppCmds = &pCmd; submitDesc.mCmdCount = 1; submitDesc.pSignalFence = pRenderFence; submitDesc.ppSignalSemaphores = &pImageSemaphore; submitDesc.mSignalSemaphoreCount = 1; queueSubmit(pQueue, &submitDesc); QueuePresentDesc presentDesc = {}; presentDesc.pSwapChain = pSwapChain; presentDesc.mIndex = (uint8_t)imageIndex; presentDesc.ppWaitSemaphores = &pImageSemaphore; presentDesc.mWaitSemaphoreCount = 1; queuePresent(pQueue, &presentDesc); // Wait for fence to complete waitForFences(pRenderer, 1, &pRenderFence); ``` ``` -------------------------------- ### Makefile Example for bstrlib Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Utilities/ThirdParty/OpenSource/bstrlib/bstrlib.txt This Makefile demonstrates how to integrate bstrlib into a project, setting up include paths, object files, and compilation flags. ```makefile BSTRDIR = $(CDIR)/bstrlib INCLUDES = -I$(BSTRDIR) BSTROBJS = $(ODIR)/bstrlib.o DEFINES = CFLAGS = -O3 -Wall -pedantic -ansi -s $(DEFINES) application: $(ODIR)/main.o $(BSTROBJS) echo Linking: $@ $(CC) $< $(BSTROBJS) -o $@ $(ODIR)/%.o : $(BSTRDIR)/%.c echo Compiling: $< $(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@ $(ODIR)/%.o : %.c echo Compiling: $< $(CC) $(CFLAGS) $(INCLUDES) -c $< -o $@ ``` -------------------------------- ### io.popen Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Starts a program in a separate process and returns a file handle for reading from or writing to the program's standard input/output. ```APIDOC ## `io.popen (prog [, mode])` This function is system dependent and is not available on all platforms. Starts program `prog` in a separated process and returns a file handle that you can use to read data from this program (if `mode` is `"r"`, the default) or to write data to this program (if `mode` is `"w"`). ``` -------------------------------- ### C99 Flecs System Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/flecs/README.md Demonstrates how to define components, systems, and entities in C using Flecs. Requires Flecs C API. ```c typedef struct { float x, y; } Position, Velocity; void Move(ecs_iter_t *it) { Position *p = ecs_field(it, Position, 0); Velocity *v = ecs_field(it, Velocity, 1); for (int i = 0; i < it->count; i++) { p[i].x += v[i].x; p[i].y += v[i].y; } } int main(int argc, char *argv[]) { ecs_world_t *ecs = ecs_init(); ECS_COMPONENT(ecs, Position); ECS_COMPONENT(ecs, Velocity); ECS_SYSTEM(ecs, Move, EcsOnUpdate, Position, Velocity); ecs_entity_t e = ecs_insert(ecs, ecs_value(Position, {10, 20}), ecs_value(Velocity, {1, 2})); while (ecs_progress(ecs, 0)) { } } ``` -------------------------------- ### C++11 Flecs System Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/flecs/README.md Illustrates how to define components, systems, and entities in C++ using Flecs. Leverages the Flecs C++ API. ```cpp struct Position { float x, y; }; struct Velocity { float x, y; }; int main(int argc, char *argv[]) { flecs::world ecs; ecs.system() .each([](Position& p, const Velocity& v) { p.x += v.x; p.y += v.y; }); auto e = ecs.entity() .insert([](Position& p, Velocity& v) { p = {10, 20}; v = {1, 2}; }); while (ecs.progress()) { } } ``` -------------------------------- ### Example Macro Call Usage Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Utilities/ThirdParty/OpenSource/mcpp/mcpp-manual.html Demonstrates how a macro call is used within a conditional expression, showing the context in which the expanded macro appears. ```c && ELFW(ST_TYPE) (sym->st_info) != STT_TLS /* elf/do-lookup.h:81 */ ``` -------------------------------- ### bstring Initialization and Usage Example (C) Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Utilities/ThirdParty/OpenSource/bstrlib/TFREADME.md Demonstrates stack and heap initialization of bstring buffers, safe string formatting, and destruction or assertion of buffer ownership. ```c void foo(const char* name) { // You can initialize bstring buffer on stack or on heap // 1. Stack initialization // no need to initialize strBuf when using bemptyfromarr unsigned char strBuf[256]; // str data will point to strBuf bstring str = bemptyfromarr(strBuf); // 2. Heap initialization bstring str = bdynallocfromliteral("", 256); // Do some useful work with string // safe sprintf that will alloc new buffer on heap if needed bformat(&str, "hello %s", name); // ... // There are 2 ways to finish working with bstring // 1. Use bdestroy that will free underlying buffer only if ownage bit was set // (bit is set automatically when bstrlib allocates memory) bdestroy(&str); // 2. Assert that bstring didn't allocate additional memory // Use this approach with caution and only if // string was initialized with stack allocated buffer // and you are 100% sure that string should never overflow ASSERT(!bownsdata(&str)); } ``` -------------------------------- ### Run Sample Code to List CPU Features Source: https://github.com/confettifx/the-forge/blob/master/Common_3/OS/ThirdParty/OpenSource/cpu_features/README.md Execute the built sample program to display CPU features in a human-readable format. This is useful for a quick overview of the system's CPU capabilities. ```shell % ./build/list_cpu_features arch : x86 brand : Intel(R) Xeon(R) CPU E5-1650 0 @ 3.20GHz family : 6 (0x06) model : 45 (0x2D) stepping : 7 (0x07) uarch : INTEL_SNB flags : aes,avx,cx16,smx,sse4_1,sse4_2,ssse3 ``` -------------------------------- ### Clone and Build The Forge Project Source: https://github.com/confettifx/the-forge/wiki/Home Clone the repository, navigate to the directory, and run the pre-build script. On Windows, open the solution file and build in Debug mode. ```bash git clone https://github.com/ConfettiFX/The-Forge.git cd The-Forge ./PRE_BUILD.bat (On Windows) ./PRE_BUILD.command (On other platforms) # double-click The-Forge\Examples_3\Unit_Tests\PC_VS2019\Unit_Tests.sln # build Debug ``` -------------------------------- ### Run Sample Code to List CPU Features in JSON Source: https://github.com/confettifx/the-forge/blob/master/Common_3/OS/ThirdParty/OpenSource/cpu_features/README.md Execute the built sample program with the --json flag to output CPU features in a structured JSON format. This is ideal for programmatic parsing and integration into other applications. ```shell % ./build/list_cpu_features --json {"arch":"x86","brand":" Intel(R) Xeon(R) CPU E5-1650 0 @ 3.20GHz","family":6,"model":45,"stepping":7,"uarch":"INTEL_SNB","flags":["aes","avx","cx16","smx","sse4_1","sse4_2","ssse3"]} ``` -------------------------------- ### coroutine.resume Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Starts or resumes the execution of a coroutine. ```APIDOC ## coroutine.resume (co [, val1, ···]) ### Description Starts or continues the execution of coroutine `co`. The first time you resume a coroutine, it starts running its body. The values `val1`, ... are passed as the arguments to the body function. If the coroutine has yielded, `resume` restarts it; the values `val1`, ... are passed as the results from the yield. If the coroutine runs without any errors, `resume` returns **true** plus any values passed to `yield` (when the coroutine yields) or any values returned by the body function (when the coroutine terminates). If there is any error, `resume` returns **false** plus the error message. ### Parameters * `co` - The coroutine to resume. * `val1, ···` - Optional arguments to pass to the coroutine. ### Returns * `boolean` - True on success, false on error. * If successful, followed by any values returned by the coroutine. * If an error occurs, followed by the error message. ``` -------------------------------- ### Create and Use FPS Camera Source: https://context7.com/confettifx/the-forge/llms.txt Demonstrates how to create a first-person camera controller, set its motion parameters, handle input for movement and rotation, and build the view-projection matrix. Remember to clean up the camera controller when done. ```cpp // Create FPS camera CameraMotionParameters camParams = {}; camParams.maxSpeed = 200.0f; camParams.acceleration = 800.0f; camParams.braking = 300.0f; ICameraController* pCamera = createFpsCameraController( vec3(0.0f, 2.0f, -5.0f), // initial position vec3(0.0f, 0.0f, 1.0f) // initial look-at direction ); pCamera->setMotionParameters(camParams); // In Update(): pCamera->onMove ({ inputGetValue(0, CUSTOM_MOVE_X), inputGetValue(0, CUSTOM_MOVE_Y) }); pCamera->onRotate ({ inputGetValue(0, CUSTOM_LOOK_X), inputGetValue(0, CUSTOM_LOOK_Y) }); // Build view-projection matrix for shaders CameraMatrix proj = CameraMatrix::perspectiveReverseZ( PI / 3.0f, // 60 degree FOV (float)mSettings.mHeight / mSettings.mWidth, 0.01f, 3000.0f ); // Apply TAA jitter proj.applyProjectionSampleOffset(jitterX, jitterY); mat4 view = pCamera->getViewMatrix(); mat4 viewProj = proj.mCamera * view; // Cleanup destroyCameraController(pCamera); ``` -------------------------------- ### Initialize and Use ImGui-Based UI System Source: https://context7.com/confettifx/the-forge/llms.txt Initializes the UI system, loads its resources, creates UI panels, and adds various widgets bound to application variables. Call `cmdDrawUserInterface` within your render loop to display the UI. ```cpp // Init UserInterfaceDesc uiDesc = {}; uiDesc.pRenderer = pRenderer; uiDesc.mFrameCount = IMAGE_COUNT; uiDesc.mEnableRemoteUI = true; initUserInterface(&uiDesc); UserInterfaceLoadDesc uiLoadDesc = {}; uiLoadDesc.mColorFormat = pSwapChain->ppRenderTargets[0]->mFormat; uiLoadDesc.mWidth = mSettings.mWidth; uiLoadDesc.mHeight = mSettings.mHeight; uiLoadDesc.mDisplayWidth = mSettings.mWidth; uiLoadDesc.mDisplayHeight = mSettings.mHeight; loadUserInterface(&uiLoadDesc); // Create a window panel UIComponentDesc compDesc = {}; compDesc.mStartPosition = { 10.0f, 50.0f }; compDesc.mStartSize = { 300.0f, 400.0f }; UIComponent* pPanel = NULL; uiAddComponent("Settings", &compDesc, &pPanel); // Add widgets bound to app variables static float gLightIntensity = 1.0f; static bool gEnableShadows = true; static int32_t gQualityIndex = 1; static uint32_t gMSAA = 0; const char* qualityNames[] = { "Low", "Medium", "High", "Ultra" }; SliderFloatWidget sliderW = {}; sliderW.pData = &gLightIntensity; sliderW.mMin = 0.0f; sliderW.mMax = 10.0f; uiAddComponentWidget(pPanel, "Light Intensity", &sliderW, WIDGET_TYPE_SLIDER_FLOAT); CheckboxWidget cbW = {}; cbW.pData = &gEnableShadows; UIWidget* pCbWidget = uiAddComponentWidget(pPanel, "Enable Shadows", &cbW, WIDGET_TYPE_CHECKBOX); uiSetWidgetOnEditedCallback(pCbWidget, NULL, [](void*) { LOGF(LogLevel::eINFO, "Shadow toggle changed"); }); DropdownWidget ddW = {}; ddW.pData = &gMSAA; ddW.pNames = qualityNames; ddW.mCount = TF_ARRAY_COUNT(qualityNames); uiAddComponentWidget(pPanel, "Quality", &ddW, WIDGET_TYPE_DROPDOWN); // In Draw() cmdDrawUserInterface(pCmd); ``` -------------------------------- ### Load Volk Instance Only Entrypoints Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Graphics/ThirdParty/OpenSource/volk/README.md Use this function instead of `volkLoadInstance` if you only need instance-level entrypoints. When using the table-based interface, this can help enforce the usage of function tables by leaving device-specific functions as NULL. ```c void volkLoadInstanceOnly(); ``` -------------------------------- ### Macro Expansion Comments in mcpp Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Utilities/ThirdParty/OpenSource/mcpp/mcpp-manual.html Illustrates the comment markers used by mcpp to denote the start and end of macro expansions and argument locations within source code. These markers include /">*<...*/> for expansion start and /">*>");*/ for expansion end. ```c foo(NULL); foo(BAR(some_, var)); foo = BAZ(NULL, 2); bar = BAZ(BAZ(a,b), c); ``` ```c foo(/">*0L/">*>");*/); foo(/">*/">*!BAR:0-0 5:9-5:14*//">*!BAR:0-1 5:16-5:19*/>some_var/">*>");*/); foo = /">*/">*!BAZ:0-0 6:11-6:15*//">*!BAZ:0-1 6:17-6:18*/>/">*/">*0L/">*>");*//">*BAZ:0-0>");*/ + /">*2/">*BAZ:0-1>");*//">*BAZ>");*/; bar = /">*/">*!BAZ:0-0 7:11-7:19*//">*!BAZ:0-1 7:21-7:22*/>/">*/">*/">*!BAZ:1-0*//">*!BAZ:1-1*/>/">*a/">*BAZ:1-0>");*/ + /">*b/">*BAZ:1-1>");*//">*BAZ>");*//">*BAZ:0-0>");*/ + /">*c/">*BAZ:0-1>");*//">*BAZ>");*/; ``` -------------------------------- ### Full Frame Render Loop with IGraphics Source: https://context7.com/confettifx/the-forge/llms.txt Demonstrates the complete process of initializing graphics resources, recording commands for a frame, submitting them for execution, and presenting the rendered image. Ensure all necessary graphics objects like Renderer, Queue, CmdPool, SwapChain, and Pipeline are properly initialized before use. ```cpp // Full frame render loop: init resources, record commands, submit and present Renderer* pRenderer = NULL; Queue* pQueue = NULL; CmdPool* pCmdPool = NULL; Cmd** ppCmds = NULL; SwapChain* pSwapChain = NULL; Fence* pRenderFence = NULL; Semaphore* pImageSemaphore = NULL; Pipeline* pPipeline = NULL; const uint32_t IMAGE_COUNT = 2; // --- Init --- RendererDesc rendererDesc = {}; initRenderer("Demo", &rendererDesc, &pRenderer); QueueDesc qDesc = { QUEUE_TYPE_GRAPHICS }; initQueue(pRenderer, &qDesc, &pQueue); CmdPoolDesc poolDesc = { pQueue }; initCmdPool(pRenderer, &poolDesc, &pCmdPool); CmdDesc cmdDesc = { pCmdPool }; initCmd_n(pRenderer, &cmdDesc, IMAGE_COUNT, &ppCmds); initFence(pRenderer, &pRenderFence); initSemaphore(pRenderer, &pImageSemaphore); // Swap chain SwapChainDesc scDesc = {}; scDesc.mWindowHandle = pWindow->handle; scDesc.mPresentQueueCount = 1; scDesc.ppPresentQueues = &pQueue; scDesc.mWidth = mSettings.mWidth; scDesc.mHeight = mSettings.mHeight; scDesc.mImageCount = IMAGE_COUNT; scDesc.mColorFormat = getSupportedSwapchainFormat(pRenderer, &scDesc, COLOR_SPACE_SDR_SRGB); addSwapChain(pRenderer, &scDesc, &pSwapChain); // --- Draw Frame --- uint32_t imageIndex = 0; acquireNextImage(pRenderer, pSwapChain, pImageSemaphore, NULL, &imageIndex); Cmd* pCmd = ppCmds[imageIndex]; resetCmdPool(pRenderer, pCmdPool); beginCmd(pCmd); // Transition swapchain to render target RenderTargetBarrier rtBarrier = { pSwapChain->ppRenderTargets[imageIndex], RESOURCE_STATE_PRESENT, RESOURCE_STATE_RENDER_TARGET }; cmdResourceBarrier(pCmd, 0, NULL, 0, NULL, 1, &rtBarrier); // Bind render target and clear BindRenderTargetsDesc bindDesc = {}; bindDesc.mRenderTargetCount = 1; bindDesc.mRenderTargets[0] = { pSwapChain->ppRenderTargets[imageIndex], LOAD_ACTION_CLEAR, STORE_ACTION_STORE, { .rgba = {0.2f,0.2f,0.2f,1.0f} } }; cmdBindRenderTargets(pCmd, &bindDesc); cmdSetViewport(pCmd, 0, 0, (float)mSettings.mWidth, (float)mSettings.mHeight, 0.0f, 1.0f); cmdSetScissor (pCmd, 0, 0, mSettings.mWidth, mSettings.mHeight); // Draw with bound pipeline cmdBindPipeline(pCmd, pPipeline); cmdBindDescriptorSet(pCmd, imageIndex, pDescriptorSet); cmdDrawIndexed(pCmd, indexCount, 0, 0); // Debug markers cmdBeginDebugMarker(pCmd, 1, 0, 0, "Main Pass"); cmdEndDebugMarker(pCmd); // Transition to present rtBarrier = { pSwapChain->ppRenderTargets[imageIndex], RESOURCE_STATE_RENDER_TARGET, RESOURCE_STATE_PRESENT }; cmdResourceBarrier(pCmd, 0, NULL, 0, NULL, 1, &rtBarrier); endCmd(pCmd); // Submit and present QueueSubmitDesc submitDesc = {}; submitDesc.ppCmds = &pCmd; submitDesc.mCmdCount = 1; submitDesc.pSignalFence = pRenderFence; submitDesc.ppSignalSemaphores = &pImageSemaphore; submitDesc.mSignalSemaphoreCount = 1; queueSubmit(pQueue, &submitDesc); QueuePresentDesc presentDesc = {}; presentDesc.pSwapChain = pSwapChain; presentDesc.mIndex = (uint8_t)imageIndex; presentDesc.ppWaitSemaphores = &pImageSemaphore; presentDesc.mWaitSemaphoreCount = 1; queuePresent(pQueue, &presentDesc); waitForFences(pRenderer, 1, &pRenderFence); ``` -------------------------------- ### Shader Entry Point Initialization and Return Source: https://github.com/confettifx/the-forge/wiki/FSL-Programming-Guide Defines the structure for shader entry points using INIT_MAIN and RETURN macros. Use RETURN() for void functions and RETURN(value) for functions returning a value. ```fsl INIT_MAIN; // ... shader code ... RETURN(); // for void main function float4 Out = (...); RETURN(Out); // for main function with return type ``` -------------------------------- ### Length Operation Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Function to get the length of a value on the stack. ```APIDOC ## `lua_len` ### Description Returns the length of the value at the given index. It is equivalent to the '`#`' operator in Lua and may trigger a metamethod for the "length" event. The result is pushed on the stack. ### Signature `void lua_len (lua_State *L, int index);` ``` -------------------------------- ### io.output Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Sets or gets the default output file. Similar to io.input but for output operations. ```APIDOC ## `io.output ([file])` Similar to [`io.input`](#pdf-io.input), but operates over the default output file. ``` -------------------------------- ### Register Resource Directories for FileSystem Source: https://context7.com/confettifx/the-forge/llms.txt Initialize the FileSystem and register resource directories to manage access to assets like textures, meshes, and shaders. Files are then opened relative to these registered paths. ```cpp // Register resource directories FileSystemInitDesc fsDesc = { "MyApp" }; initFileSystem(&fsDesc); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_TEXTURES, "Textures"); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_MESHES, "Meshes"); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_SHADER_BINARIES, "Shaders/Binary"); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_GPU_CONFIG, "GPUCfg"); fsSetPathForResourceDir(pSystemFileIO, RM_CONTENT, RD_FONTS, "Fonts"); ``` -------------------------------- ### Load Volk Instance Entrypoints Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Graphics/ThirdParty/OpenSource/volk/README.md After creating a Vulkan instance, call this function to load all required Vulkan entrypoints, including extensions. Vulkan can then be used as usual. ```c void volkLoadInstance(VkInstance instance); ``` -------------------------------- ### Initialize Volk Loader Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Graphics/ThirdParty/OpenSource/volk/README.md Call this function first to attempt loading the Vulkan loader from the system. If it returns VK_SUCCESS, you can proceed to create a Vulkan instance. Failure indicates the Vulkan loader is not installed. ```c VkResult volkInitialize(); ``` -------------------------------- ### Get bstring Length Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Utilities/ThirdParty/OpenSource/bstrlib/bstrlib.txt Returns the length of a bstring. If the bstring pointer is NULL, 0 is returned. ```c int blength (const_bstring b); ``` -------------------------------- ### Get Texture Dimensions in FSL Source: https://github.com/confettifx/the-forge/wiki/FSL-Programming-Guide Retrieves the dimensions of a texture. Can be used with or without a sampler state. ```fsl int2 size = GetDimensions( gTextureA, gSampler ); ``` ```fsl int2 size2 = GetDimensions(gTextureB, NO_SAMPLER); ``` -------------------------------- ### Create and Add Graphics Pipeline with Descriptor Layouts Source: https://github.com/confettifx/the-forge/wiki/FSL-Programming-Guide This example demonstrates creating a graphics pipeline descriptor, setting its type, and initializing it with descriptor layouts using PIPELINE_LAYOUT_DESC before adding the pipeline. It shows how to specify descriptor set layouts for persistent and per-frame updates. ```cpp PipelineDesc desc = {}; desc.mType = PIPELINE_TYPE_GRAPHICS; PIPELINE_LAYOUT_DESC(desc, SRT_LAYOUT_DESC(SrtData, Persistent), SRT_LAYOUT_DESC(SrtData, PerFrame), NULL, NULL); // ... fill pipelineSettings addPipeline(pRenderer, &desc, &pSpherePipeline); ``` -------------------------------- ### Lua Closure and Upvalue Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Shows how closures capture local variables (upvalues) from their enclosing scope. ```lua a = {} local x = 20 for i=1,10 do local y = 0 a[i] = function () y=y+1; return x+y end end ``` -------------------------------- ### Lua Lexical Scoping Example Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Demonstrates lexical scoping rules with nested blocks and local variables. ```lua x = 10 -- global variable do -- new block local x = x -- new 'x', with value 10 print(x) --> 10 x = x+1 do -- another block local x = x+1 -- another 'x' print(x) --> 12 end print(x) --> 11 end print(x) --> 10 (the global one) ``` -------------------------------- ### Initialize and Use Profiler System Source: https://context7.com/confettifx/the-forge/llms.txt Initializes the profiler, sets up GPU and CPU timers, and enables per-frame profiling. Timestamps can be added within command buffers for detailed GPU timing. ```cpp // Init ProfilerDesc profDesc = {}; profDesc.pRenderer = pRenderer; profDesc.ppQueues = &pGraphicsQueue; profDesc.mGpuProfilerCount = 1; const char* profNames[] = { "Graphics" }; profDesc.ppProfilerNames = profNames; ProfileToken gpuProfileTokens[1] = {}; profDesc.pProfileTokens = gpuProfileTokens; initProfiler(&profDesc); loadProfilerUI(mSettings.mWidth, mSettings.mHeight); ProfileToken gGpuMainToken = getCpuProfileToken("GPU", "Main", 0xFF00FF00); ProfileToken gCpuFrameToken = getCpuProfileToken("CPU", "Frame", 0xFF00FFFF); // Per frame flipProfiler(); // In Draw(): cmdBeginGpuFrameProfile(pCmd, gpuProfileTokens[0]); { cmdBeginGpuTimestampQuery(pCmd, gpuProfileTokens[0], "Shadow Pass"); // ... shadow rendering ... cmdEndGpuTimestampQuery(pCmd, gpuProfileTokens[0]); } { cmdBeginGpuTimestampQuery(pCmd, gpuProfileTokens[0], "Main Pass"); // ... main rendering ... cmdEndGpuTimestampQuery(pCmd, gpuProfileTokens[0]); } cmdEndGpuFrameProfile(pCmd, gpuProfileTokens[0]); // Draw overlay text FontDrawDesc profFont = { NULL, gFontID, 0xffffffff, 15.0f }; float2 origin = { 8.0f, 15.0f }; origin = cmdDrawCpuProfile(pCmd, origin, &profFont); origin = cmdDrawGpuProfile(pCmd, origin, gpuProfileTokens[0], &profFont); // Dump HTML report (64 frames max) dumpProfileData("MyApp", 64); ``` -------------------------------- ### FSL Identity Matrix and Vector Initialization Source: https://github.com/confettifx/the-forge/wiki/FSL-Programming-Guide Shows how to create an identity matrix and initialize vectors with identical components using helper functions. ```fsl f4x4 id = Identity(); ``` ```fsl float4 color = f4(1); ``` -------------------------------- ### Lua Integer Constants Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Examples of valid integer constants in Lua, including decimal and hexadecimal formats. ```lua 3 ``` ```lua 345 ``` ```lua 0xff ``` ```lua 0xBEBADA ``` -------------------------------- ### debug.traceback Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Generates a traceback string for the current call stack, optionally with a message prefix and a starting level. ```APIDOC ## `debug.traceback ([thread,] [message [, level]])` ### Description If `message` is present but is neither a string nor **nil**, this function returns `message` without further processing. Otherwise, it returns a string with a traceback of the call stack. The optional `message` string is appended at the beginning of the traceback. An optional `level` number tells at which level to start the traceback (default is 1, the function calling `traceback`). ### Parameters * **thread** (thread, optional) - The thread for which to generate the traceback. Defaults to the current thread. * **message** (string | nil, optional) - An optional message to prepend to the traceback. * **level** (integer, optional) - The stack level at which to start the traceback. Defaults to 1. ### Returns * (string) - A string representing the call stack traceback. ``` -------------------------------- ### Platform Initialization Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Application/ThirdParty/OpenSource/cr/README.md Placeholder function for platform-specific initialization. Currently does nothing. ```c++ static void cr_plat_init() { } ``` -------------------------------- ### string.byte Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Returns the internal numeric codes of characters in a string. Supports indexing from the start or end of the string. ```APIDOC ## string.byte (s [, i [, j]]) ### Description Returns the internal numeric codes of the characters `s[i]`, `s[i+1]`, ..., `s[j]`. The default value for `i` is 1; the default value for `j` is `i`. These indices are corrected following the same rules of function [`string.sub`](#pdf-string.sub). Numeric codes are not necessarily portable across platforms. ### Parameters * **s** (string) - The input string. * **i** (integer, optional) - The starting index. Defaults to 1. * **j** (integer, optional) - The ending index. Defaults to `i`. ### Returns * (number) - The numeric codes of the characters. ``` -------------------------------- ### bfindreplacecaseless Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Utilities/ThirdParty/OpenSource/bstrlib/bstrlib.txt Similar to bfindreplace, but performs case-insensitive replacements of substrings within a bstring, starting from a specified position. ```APIDOC ## bfindreplacecaseless ### Description Replaces all occurrences of the `find` substring, ignoring case, with a `replace` bstring after a given `position` in the bstring `b`. The `find` bstring must have a length > 0, otherwise `BSTR_ERR` is returned. This function does not perform recursive per character replacement; successive searches resume at the position after the last replace. ### Parameters - **b** (bstring) - The bstring to perform replacements on. - **find** (const_bstring) - The substring to find (case-insensitive). - **replace** (const_bstring) - The substring to replace with. - **position** (int) - The position in `b` to start searching from. ### Returns - **BSTR_OK** on success. - **BSTR_ERR** if `find` has a length of 0 or on other failures. ``` -------------------------------- ### binstr Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Utilities/ThirdParty/OpenSource/bstrlib/bstrlib.txt Searches for the occurrence of one bstring within another, starting from a specified position and searching forward. ```APIDOC ## binstr ### Description Search for the bstring s2 in s1 starting at position pos and looking in a forward (increasing) direction. If it is found then it returns with the first position after pos where it is found, otherwise it returns BSTR_ERR. The algorithm used is brute force; O(m*n). ### Signature extern int binstr (const_bstring s1, int pos, const_bstring s2); ### Parameters - **s1** (const_bstring) - The bstring to search within. - **pos** (int) - The starting position for the search (inclusive). - **s2** (const_bstring) - The bstring to search for. ### Return Value - Returns the index of the first character of the first occurrence of s2 in s1 after pos. - Returns BSTR_ERR if s2 is not found in s1 after pos. ``` -------------------------------- ### Initialize Platform Signal Handlers Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Application/ThirdParty/OpenSource/cr/README.md Sets up signal handlers for critical signals like SIGILL, SIGBUS, SIGSEGV, and SIGABRT. This is crucial for detecting runtime errors within plugins. ```c static void cr_plat_init() { CR_TRACE static bool initialized = false; if (initialized) { return; } initialized = true; struct sigaction sa; sa.sa_flags = SA_SIGINFO | SA_RESTART | SA_NODEFER; sigemptyset(&sa.sa_mask); sa.sa_sigaction = cr_signal_handler; #if defined(CR_LINUX) sa.sa_restorer = nullptr; #endif if (sigaction(SIGILL, &sa, nullptr) == -1) { CR_ERROR("Failed to setup SIGILL handler\n"); } if (sigaction(SIGBUS, &sa, nullptr) == -1) { CR_ERROR("Failed to setup SIGBUS handler\n"); } if (sigaction(SIGSEGV, &sa, nullptr) == -1) { CR_ERROR("Failed to setup SIGSEGV handler\n"); } if (sigaction(SIGABRT, &sa, nullptr) == -1) { CR_ERROR("Failed to setup SIGABRT handler\n"); } } ``` -------------------------------- ### Global substitution with string.gsub Source: https://github.com/confettifx/the-forge/blob/master/Common_3/Game/ThirdParty/OpenSource/lua-5.3.5/doc/manual.html Replace all occurrences of a pattern in a string with a specified replacement. This example doubles each matched word. ```lua x = string.gsub("hello world", "(%w+)", "%1 %1") ```