### Initialize Kha Project via Command Line Source: https://github.com/kode/kha/wiki/Getting-Started This command initializes a new Kha project in the current directory. It requires Node.js and the Kha framework to be installed. ```bash node /path/to/Kha/make --init ``` -------------------------------- ### Build and Install Android Application with Kha CLI Source: https://github.com/kode/kha/wiki/Android Demonstrates how to compile, debug, and install an Android application using the Kha command-line interface. It includes commands for building the native project for a specific architecture and then using adb to install the generated APK onto a connected device or emulator. ```bash node Kha/make android-native --compile --debug --arch arm7 # change __PROJECT_NAME__ to your khafile project name adb install -r -d build/android-native-build/__PROJECT_NAME__/app/build/outputs/apk/debug/app-debug.apk ``` -------------------------------- ### Clone Empty Kha Project and Update Source: https://github.com/kode/kha/wiki/Getting-Started This command clones a minimal Kha project template and then updates its submodules and downloads necessary tools. This is a good starting point for new projects. ```bash git clone https://github.com/Kha-Samples/Empty.git git submodule update --init Kha/get_dlc ``` -------------------------------- ### Clone Kha Repository and Download Dependencies Source: https://github.com/kode/kha/wiki/Getting-Started This command clones the Kha repository from GitHub and then downloads necessary binary tools and submodules for cross-platform development. ```bash git clone https://github.com/Kode/Kha.git ./Kha/get_dlc ``` -------------------------------- ### Install Debian/Ubuntu Build Dependencies Source: https://github.com/kode/kha/wiki/Linux Installs essential packages for C++ compilation and graphics development on Debian/Ubuntu-based Linux distributions. This includes build tools, OpenGL/Vulkan libraries, and input/windowing system dependencies. ```bash sudo apt install ninja-build g++ libxinerama-dev libxrandr-dev libasound2-dev libxi-dev mesa-common-dev libgl-dev libxcursor-dev libvulkan-dev libudev-dev libegl-dev libwayland-dev wayland-protocols libxkbcommon-dev ``` -------------------------------- ### Update Kha Framework Source: https://github.com/kode/kha/wiki/Getting-Started This procedure updates the Kha framework by pulling the latest changes from the main branch and downloading updated dependencies. ```bash cd Kha git pull origin main get_dlc ``` -------------------------------- ### 3D Monkey Model Rendering Example Source: https://github.com/kode/kha/wiki/Feature-Tests Provides an example of rendering a 3D monkey model. This typically involves loading a 3D model file (e.g., OBJ), setting up vertex buffers and shaders, and issuing draw calls to render the model in a 3D scene. Dependencies include a 3D model loader and graphics API setup. ```cpp #include #include #include int main() { // Matrix transformations for 3D rendering glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(0.0f, 0.0f, -3.0f)); glm::mat4 view = glm::lookAt(glm::vec3(0.0f, 0.0f, 3.0f), glm::vec3(0.0f, 0.0f, 0.0f), glm::vec3(0.0f, 1.0f, 0.0f)); glm::mat4 projection; projection = glm::perspective(glm::radians(45.0f), 800.0f / 600.0f, 0.1f, 100.0f); return 0; } ``` -------------------------------- ### Build Kha Project for Specific Target via Command Line Source: https://github.com/kode/kha/wiki/Getting-Started This command builds a Kha project for a specified target, such as 'html5'. It requires Node.js and the Kha framework. ```bash node /path/to/Kha/make html5 ``` -------------------------------- ### Clone Kha Repository Recursively Source: https://github.com/kode/kha/wiki/Getting-Started This command clones the Kha repository and all its submodules, including tools for all operating systems. This results in a larger download but ensures all dependencies are present. ```bash git clone --recursive https://github.com/Kode/Kha.git ``` -------------------------------- ### Install Fedora Build Dependencies Source: https://github.com/kode/kha/wiki/Linux Installs necessary packages for C++ compilation and graphics development on Fedora and similar Linux distributions. This includes C++ compiler, OpenGL libraries, and ALSA development files. ```bash sudo dnf install gcc-c++ libXinerama-devel mesa-libGL-devel mesa-libGL-devel alsa-lib-devel libstdc++-static ``` -------------------------------- ### Configure Android Environment Variables (Unix) Source: https://github.com/kode/kha/wiki/Android Sets up essential environment variables for Android development on Unix-based systems. It defines the ANDROID_HOME path and adds the platform-tools and tools directories to the system's PATH for easy access to Android debugging bridge (adb) and other command-line utilities. ```bash export ANDROID_HOME=/YourPathToAndroid/sdk export PATH=$ANDROID_HOME/platform-tools:$PATH export PATH=$ANDROID_HOME/tools:$PATH ``` -------------------------------- ### Create and Draw to Render Target (Haxe) Source: https://github.com/kode/kha/wiki/Render-to-Texture Demonstrates creating a render target image using `Image.createRenderTarget` and drawing 2D shapes into it using `g2`. The `g.begin()` and `g.end()` calls manage the rendering process. Remember to call `g.end()` before starting another `g.begin...g.end()` block. ```haxe import kha.Image; import kha.Color; ... final image = Image.createRenderTarget(256, 256); final g = image.g2; g.begin(); // sets up everything for rendering into the texture g.color = Color.Red; g.fillRect(20, 20, 50, 50); g.end(); // after the end call, the image can be used just like any other image ``` -------------------------------- ### Configure Global Keystore and Passwords in gradle.properties Source: https://github.com/kode/kha/wiki/Android Sets global keystore and password configurations for Gradle builds by creating or updating the 'gradle.properties' file in the USER_HOME/.gradle directory. This file defines aliases, passwords, and the path to the keystore file, ensuring consistent signing across builds. ```properties RELEASE_KEY_ALIAS=my-key-alias RELEASE_STORE_PASSWORD= RELEASE_KEY_PASSWORD= RELEASE_STORE_FILE=PathTo/my-release-key.keystore ``` -------------------------------- ### Manage Application Windows with kha.Window (Haxe) Source: https://context7.com/kode/kha/llms.txt Provides functions to get window information (position, size, title, VSync), resize, move, toggle fullscreen, set title, listen for resize events, and create new windows using kha.Window and related enums. ```haxe import kha.Window; import kha.WindowMode; import kha.WindowOptions; import kha.System; class WindowManager { public function getWindowInfo() { var window = Window.get(0); // Get primary window trace('Position: (${window.x}, ${window.y})'); trace('Size: ${window.width}x${window.height}'); trace('Title: ${window.title}'); trace('VSync: ${window.vSynced}'); } public function resizeWindow(width: Int, height: Int) { var window = Window.get(0); window.resize(width, height); } public function moveWindow(x: Int, y: Int) { var window = Window.get(0); window.move(x, y); } public function toggleFullscreen() { var window = Window.get(0); if (window.mode == WindowMode.Windowed) { window.mode = WindowMode.Fullscreen; } else { window.mode = WindowMode.Windowed; } } public function setTitle(title: String) { var window = Window.get(0); window.title = title; } public function listenForResize() { var window = Window.get(0); window.notifyOnResize(function(width: Int, height: Int) { trace('Window resized to ${width}x${height}'); }); } public function createSecondWindow() { var newWindow = Window.create({ title: "Second Window", width: 400, height: 300, x: 100, y: 100 }); } } ``` -------------------------------- ### Multisample Render Targets Example Source: https://github.com/kode/kha/wiki/Feature-Tests Demonstrates the use of multisample render targets in graphics rendering. This technique improves anti-aliasing quality by rendering to multiple samples per pixel. It typically involves setting up the render target with multisampling flags and rendering commands. ```glsl #version 330 core layout (location = 0) in vec4 aPos; void main() { gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0); } ``` -------------------------------- ### Add Kha as a Git Submodule Source: https://github.com/kode/kha/wiki/Getting-Started This command adds the Kha repository as a Git submodule to your project, allowing for robust version management of the framework and its dependencies. ```bash git submodule add https://github.com/Kode/Kha git submodule update --init Kha/get_dlc ``` -------------------------------- ### Conditional Compilation for Kha Android Native Builds Source: https://github.com/kode/kha/wiki/Android Demonstrates how to use conditional compilation flags in Haxe to include or exclude code based on the target platform. It specifically shows how to target Android native builds using '#if kha_android_native' and provides an alternative for other platforms. ```haxe #if kha_android_native // This code will be run by android-native builds #else // For other platforms #end // Beware, this is separated flag for android java backend: #if kha_android && !kha_android_native // This code will be discarded by android-native builds #end ``` -------------------------------- ### Run Local Server with Kha Source: https://github.com/kode/kha/wiki/HTML5 Starts a local development server using Kha's make tool. This is useful for testing HTML5 projects in browsers that restrict access to local files. The server defaults to port 8080, but a custom port can be specified. ```bash node Kha/make --server ``` ```bash node Kha/make --server --port 1234 ``` -------------------------------- ### Generate Release Keystore with keytool Source: https://github.com/kode/kha/wiki/Android Generates a private signing keystore and a single key for Android release builds. This command creates a keystore file named 'my-release-key.keystore' with an alias 'my-key-alias', using RSA encryption with a key size of 2048 bits and a validity of 10000 days. ```bash keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000 ``` -------------------------------- ### Multiple Render Targets (MRT) Example Source: https://github.com/kode/kha/wiki/Feature-Tests Illustrates the implementation of Multiple Render Targets (MRT) in graphics rendering. MRT allows a fragment shader to write to multiple textures simultaneously, enabling complex effects like deferred shading. This requires specific hardware and API support. ```glsl #version 330 core out vec4 FragColor; void main() { FragColor = vec4(1.0, 0.5, 0.2, 1.0); } ``` -------------------------------- ### Kha Graphics2D API Drawing Example Source: https://context7.com/kode/kha/llms.txt Demonstrates various 2D drawing operations using Kha's Graphics2D API, including drawing shapes, images, text, and applying transformations. It requires importing necessary Kha modules and assets. ```haxe import kha.Framebuffer; import kha.Color; import kha.Assets; import kha.math.FastMatrix3; class Renderer { public static function render(framebuffer: Framebuffer) { var g = framebuffer.g2; // Begin rendering with clear color g.begin(true, Color.fromBytes(30, 30, 40)); // Draw filled rectangle g.color = Color.Red; g.fillRect(50, 50, 100, 80); // Draw rectangle outline g.color = Color.Yellow; g.drawRect(200, 50, 100, 80, 2.0); // Draw line g.color = Color.Cyan; g.drawLine(50, 200, 300, 250, 3.0); // Draw triangle g.color = Color.Magenta; g.fillTriangle(400, 100, 350, 200, 450, 200); // Draw image g.color = Color.White; // Reset color to draw image unaltered g.drawImage(Assets.images.player, 500, 100); // Draw scaled sub-image (sprite from spritesheet) g.drawScaledSubImage(Assets.images.spritesheet, 0, 0, 32, 32, // source: sx, sy, sw, sh 100, 300, 64, 64 // dest: dx, dy, dw, dh ); // Draw text g.font = Assets.fonts.arial; g.fontSize = 24; g.color = Color.White; g.drawString("Score: 1000", 50, 400); // Apply transformation (rotation around center) g.pushRotation(Math.PI / 4, 600, 300); g.color = Color.Green; g.fillRect(550, 250, 100, 100); g.popTransformation(); // Apply scaling g.pushScale(2.0, 2.0); g.color = Color.Blue; g.fillRect(50, 250, 30, 30); // Will be 60x60 at 100,500 g.popTransformation(); // Set opacity g.pushOpacity(0.5); g.color = Color.White; g.fillRect(700, 100, 80, 80); g.popOpacity(); // Scissor clipping g.scissor(0, 0, 400, 300); g.color = Color.Orange; g.fillRect(350, 250, 100, 100); // Partially clipped g.disableScissor(); g.end(); } } ``` -------------------------------- ### Build SSL Library (Windows vs. Others) Source: https://github.com/kode/kha/blob/main/Backends/Kore-HL/hl/libs/ssl/CMakeLists.txt This snippet defines how the 'ssl.hdll' shared library is built. On Windows (WIN32), it compiles mbedTLS source files directly. On other platforms, it finds and links against an installed MbedTLS package. The primary input is the operating system, and the output is the 'ssl.hdll' library. ```cmake if (WIN32) set(MBEDTLS_INCLUDE_DIRS ${INCLUDES_BASE_DIR}/mbedtls/include) set(MBEDTLS_LIBRARIES crypt32) add_library(ssl.hdll SHARED ${INCLUDES_BASE_DIR}/mbedtls/library/aes.c ${INCLUDES_BASE_DIR}/mbedtls/library/aesni.c ${INCLUDES_BASE_DIR}/mbedtls/library/arc4.c ${INCLUDES_BASE_DIR}/mbedtls/library/asn1parse.c ${INCLUDES_BASE_DIR}/mbedtls/library/asn1write.c ${INCLUDES_BASE_DIR}/mbedtls/library/base64.c ${INCLUDES_BASE_DIR}/mbedtls/library/bignum.c ${INCLUDES_BASE_DIR}/mbedtls/library/blowfish.c ${INCLUDES_BASE_DIR}/mbedtls/library/camellia.c ${INCLUDES_BASE_DIR}/mbedtls/library/ccm.c ${INCLUDES_BASE_DIR}/mbedtls/library/certs.c ${INCLUDES_BASE_DIR}/mbedtls/library/cipher.c ${INCLUDES_BASE_DIR}/mbedtls/library/cipher_wrap.c ${INCLUDES_BASE_DIR}/mbedtls/library/ctr_drbg.c ${INCLUDES_BASE_DIR}/mbedtls/library/debug.c ${INCLUDES_BASE_DIR}/mbedtls/library/des.c ${INCLUDES_BASE_DIR}/mbedtls/library/dhm.c ${INCLUDES_BASE_DIR}/mbedtls/library/ecdh.c ${INCLUDES_BASE_DIR}/mbedtls/library/ecdsa.c ${INCLUDES_BASE_DIR}/mbedtls/library/ecjpake.c ${INCLUDES_BASE_DIR}/mbedtls/library/ecp.c ${INCLUDES_BASE_DIR}/mbedtls/library/ecp_curves.c ${INCLUDES_BASE_DIR}/mbedtls/library/entropy.c ${INCLUDES_BASE_DIR}/mbedtls/library/entropy_poll.c ${INCLUDES_BASE_DIR}/mbedtls/library/error.c ${INCLUDES_BASE_DIR}/mbedtls/library/gcm.c ${INCLUDES_BASE_DIR}/mbedtls/library/havege.c ${INCLUDES_BASE_DIR}/mbedtls/library/hmac_drbg.c ${INCLUDES_BASE_DIR}/mbedtls/library/md.c ${INCLUDES_BASE_DIR}/mbedtls/library/md2.c ${INCLUDES_BASE_DIR}/mbedtls/library/md4.c ${INCLUDES_BASE_DIR}/mbedtls/library/md5.c ${INCLUDES_BASE_DIR}/mbedtls/library/md_wrap.c ${INCLUDES_BASE_DIR}/mbedtls/library/memory_buffer_alloc.c ${INCLUDES_BASE_DIR}/mbedtls/library/oid.c ${INCLUDES_BASE_DIR}/mbedtls/library/padlock.c ${INCLUDES_BASE_DIR}/mbedtls/library/pem.c ${INCLUDES_BASE_DIR}/mbedtls/library/pk.c ${INCLUDES_BASE_DIR}/mbedtls/library/pkcs11.c ${INCLUDES_BASE_DIR}/mbedtls/library/pkcs12.c ${INCLUDES_BASE_DIR}/mbedtls/library/pkcs5.c ${INCLUDES_BASE_DIR}/mbedtls/library/pkparse.c ${INCLUDES_BASE_DIR}/mbedtls/library/pkwrite.c ${INCLUDES_BASE_DIR}/mbedtls/library/pk_wrap.c ${INCLUDES_BASE_DIR}/mbedtls/library/platform.c ${INCLUDES_BASE_DIR}/mbedtls/library/ripemd160.c ${INCLUDES_BASE_DIR}/mbedtls/library/rsa.c ${INCLUDES_BASE_DIR}/mbedtls/library/rsa_internal.c ${INCLUDES_BASE_DIR}/mbedtls/library/sha1.c ${INCLUDES_BASE_DIR}/mbedtls/library/sha256.c ${INCLUDES_BASE_DIR}/mbedtls/library/sha512.c ${INCLUDES_BASE_DIR}/mbedtls/library/ssl_cache.c ${INCLUDES_BASE_DIR}/mbedtls/library/ssl_ciphersuites.c ${INCLUDES_BASE_DIR}/mbedtls/library/ssl_cli.c ${INCLUDES_BASE_DIR}/mbedtls/library/ssl_cookie.c ${INCLUDES_BASE_DIR}/mbedtls/library/ssl_srv.c ${INCLUDES_BASE_DIR}/mbedtls/library/ssl_ticket.c ${INCLUDES_BASE_DIR}/mbedtls/library/ssl_tls.c ${INCLUDES_BASE_DIR}/mbedtls/library/threading.c ${INCLUDES_BASE_DIR}/mbedtls/library/timing.c ${INCLUDES_BASE_DIR}/mbedtls/library/version.c ${INCLUDES_BASE_DIR}/mbedtls/library/version_features.c ${INCLUDES_BASE_DIR}/mbedtls/library/x509.c ${INCLUDES_BASE_DIR}/mbedtls/library/x509write_crt.c ${INCLUDES_BASE_DIR}/mbedtls/library/x509write_csr.c ${INCLUDES_BASE_DIR}/mbedtls/library/x509_create.c ${INCLUDES_BASE_DIR}/mbedtls/library/x509_crl.c ${INCLUDES_BASE_DIR}/mbedtls/library/x509_crt.c ${INCLUDES_BASE_DIR}/mbedtls/library/x509_csr.c ${INCLUDES_BASE_DIR}/mbedtls/library/xtea.c ssl.c ) else() find_package(MbedTLS REQUIRED) add_library(ssl.hdll SHARED ssl.c ) endif() set_as_hdll(ssl) target_include_directories(ssl.hdll PRIVATE ${MBEDTLS_INCLUDE_DIRS} ) target_link_libraries(ssl.hdll libhl ${MBEDTLS_LIBRARIES} ) if(APPLE) find_library(SECURITY_LIBRARY Security REQUIRED) find_library(COREFOUNDATION_LIBRARY CoreFoundation REQUIRED) target_link_libraries(ssl.hdll ${COREFOUNDATION_LIBRARY} ${SECURITY_LIBRARY}) endif() install( TARGETS ssl.hdll DESTINATION ${HDLL_DESTINATION} ) ``` -------------------------------- ### Resize Images During Asset Inclusion in Khafile.js Source: https://github.com/kode/kha/wiki/Managing-Your-Assets This example demonstrates how to resize images when including them in your Kha project via `khafile.js`. The `scale` option within `project.addAssets` allows you to specify a scaling factor, effectively resizing the images during the build process. ```javascript project.addAssets('assets/**', { scale: 0.5 }); ``` -------------------------------- ### Configure VS Code Tasks for Krom Build and Launch Source: https://github.com/kode/kha/wiki/Debugging This tasks.json configuration for VS Code sets up tasks to build and launch a Kha project for the Krom target. It includes a 'Krom Build&Launch' task that executes the Krom binary with debug and watch flags, depending on other build and path setup tasks. ```json { "version": "2.0.0", "tasks": [ { "label": "Krom Build&Launch", "type": "shell", "command": "/home/jsnadeau/Kromx/Deployment/Krom", "args": ["${workspaceRoot}/build/krom/","${workspaceRoot}/build/krom-resources/","--debug","--watch"], "dependsOrder": "sequence", "dependsOn":[ "Kha: Build for Krom", "setpath" ] }, { "label": "setpath", "type": "shell", "command": "cd", "args": ["${workspaceRoot}/build/"] } ] } ``` -------------------------------- ### Initialize Kha Application Source: https://context7.com/kode/kha/llms.txt Initializes the Kha application with specified window and framebuffer options. This function serves as the entry point for all Kha applications and sets up the rendering callback. ```haxe import kha.System; import kha.Framebuffer; import kha.Color; class Main { public static function main() { System.start({title: "My Kha Game", width: 800, height: 600}, function(window) { // Initialization complete, set up rendering System.notifyOnFrames(function(framebuffers) { render(framebuffers[0]); }); }); } static function render(framebuffer: Framebuffer) { var g = framebuffer.g2; g.begin(true, Color.Black); g.color = Color.White; g.fillRect(100, 100, 200, 150); g.end(); } } ``` -------------------------------- ### Update Kha Submodules Dangerously Source: https://github.com/kode/kha/wiki/Getting-Started This command updates all Kha submodules to their latest commits. Use with caution as it may introduce untested changes. ```bash cd Kha git pull origin main get_dlc_dangerously ``` -------------------------------- ### Initial Window Size for Flash and HTML5 Source: https://github.com/kode/kha/wiki/khafile.js Defines the initial width and height of the application window for Flash and HTML5 targets. ```javascript project.windowOptions.width = 1366; ``` ```javascript project.windowOptions.height = 768; ``` -------------------------------- ### Monitor Android Application Logs with adb logcat Source: https://github.com/kode/kha/wiki/Android Provides commands to monitor real-time logs from an Android application using the Android Debug Bridge (adb) logcat utility. It specifies different tags to filter logs, including general application logs (kinc, kore), native crash stacktraces (DEBUG), and Java-side crash stacktraces (AndroidRuntime). ```bash adb logcat -s kinc kore DEBUG AndroidRuntime ``` -------------------------------- ### Create and Manipulate Colors with kha.Color (Haxe) Source: https://context7.com/kode/kha/llms.txt Demonstrates creating colors using predefined constants, byte components, float components, hex values, and HTML strings. Also shows how to read and modify color components and retrieve the raw integer value. ```haxe import kha.Color; class ColorExample { public function createColors() { // Predefined colors var black = Color.Black; var white = Color.White; var red = Color.Red; var transparent = Color.Transparent; // From byte components (0-255) var custom1 = Color.fromBytes(128, 64, 200, 255); // From float components (0.0-1.0) var custom2 = Color.fromFloats(0.5, 0.25, 0.8, 1.0); // From hex value var custom3 = Color.fromValue(0xFFAABBCC); // ARGB format // From HTML string var custom4 = Color.fromString("#FF5500"); var custom5 = Color.fromString("#F50"); // Short form var custom6 = Color.fromString("#80FF5500"); // With alpha } public function manipulateColor() { var color = Color.fromBytes(100, 150, 200, 255); // Read components as bytes (0-255) var r = color.Rb; var g = color.Gb; var b = color.Bb; var a = color.Ab; // Read components as floats (0.0-1.0) var rf = color.R; var gf = color.G; var bf = color.B; var af = color.A; // Modify components color.Rb = 255; // Set red to max color.A = 0.5; // Set 50% opacity // Get raw integer value var intValue: Int = color.value; } public function colorBlending(framebuffer: kha.Framebuffer) { var g = framebuffer.g2; g.begin(); // Semi-transparent red g.color = Color.fromFloats(1.0, 0.0, 0.0, 0.5); g.fillRect(100, 100, 100, 100); // Semi-transparent blue overlapping g.color = Color.fromFloats(0.0, 0.0, 1.0, 0.5); g.fillRect(150, 150, 100, 100); g.end(); } } ``` -------------------------------- ### Basic Project Configuration in khafile.js Source: https://github.com/kode/kha/wiki/khafile.js Sets up a basic Kha project by defining the project name and specifying asset and source directories. This is the foundational configuration for any Kha project. ```javascript var project = new Project('ProjectName'); project.addAssets('Assets/**'); project.addSources('Sources'); resolve(project); ``` -------------------------------- ### Interleaved Layout Example Source: https://github.com/kode/kha/wiki/Feature-Tests Showcases the use of interleaved vertex data layouts. Interleaved layouts store different vertex attributes (like position, color, texture coordinates) consecutively within the same buffer, improving cache efficiency. This is common in modern graphics APIs. ```cpp #include #include #include int main() { // Initialization code here... return 0; } ``` -------------------------------- ### Initialize hxtelemetry in Main Class (Haxe) Source: https://github.com/kode/kha/wiki/Profiling This Haxe code demonstrates how to initialize the hxtelemetry library within your application's main class. It sets up the telemetry instance and schedules its frame advancement. ```haxe class Main { static var hxt = new hxtelemetry.HxTelemetry(); public static function main() { kha.System.init(..., system_initializedHandler); } static function system_initializedHandler() { kha.Scheduler.addFrameTask(hxt.advance_frame.bind(null), 0); } } ``` -------------------------------- ### Adding Conditional Compilation Flags Source: https://github.com/kode/kha/wiki/khafile.js Enables conditional compilation flags that can be used within the code to control features based on build configurations. For example, `debug_collisions` can be defined. ```javascript project.addDefine('debug_collisions'); ``` -------------------------------- ### Android Native Target Specific Options Source: https://github.com/kode/kha/wiki/khafile.js Configures specific options for the Android native build target, including package name, version codes, screen orientation, permissions, install location, metadata, and custom build file paths. ```javascript const android = project.targetOptions.android_native; android.package = 'com.example.app'; android.versionCode = 1; android.versionName = '1.0'; // https://developer.android.com/guide/topics/manifest/activity-element.html#screen android.screenOrientation = 'portrait'; android.permissions = ['android.permission.VIBRATE']; // https://developer.android.com/guide/topics/manifest/manifest-element#install android.installLocation = "internalOnly"; // https://developer.android.com/guide/topics/manifest/meta-data-element android.metadata = []; // same as android.disableStickyImmersiveMode = true; android.globalBuildGradlePath = 'data/android/build.gradle'; android.buildGradlePath = 'data/android/app/build.gradle'; android.proguardRulesPath = 'data/android/app/proguard-rules.pro'; // for files in Android Studio project-level dir android.customFilesPath = 'data/android/files'; ``` -------------------------------- ### Configure Kha Project with khafile.js Source: https://context7.com/kode/kha/llms.txt The khafile.js file is used to configure Kha projects, including assets, sources, libraries, compiler flags, and platform-specific options. It allows setting window dimensions, custom icons, and target-specific configurations for HTML5, Android, and iOS. Build event callbacks and sub-project inclusion are also supported. ```javascript // khafile.js - Basic project configuration var project = new Project('MyGame'); // Add asset and source folders project.addAssets('Assets/**'); project.addSources('Sources'); // Add shader folder project.addShaders('Sources/Shaders/**'); // Add external library project.addLibrary('zui'); // Add Haxe compiler flags project.addParameter('-dce full'); project.addDefine('debug_physics'); // Set custom icon project.icon = 'Assets/icon.png'; // Window configuration project.windowOptions.width = 1280; project.windowOptions.height = 720; // HTML5-specific options project.targetOptions.html5.canvasId = 'game-canvas'; project.targetOptions.html5.disableContextMenu = true; // Android options project.targetOptions.android_native.package = 'com.mycompany.mygame'; project.targetOptions.android_native.versionCode = 1; project.targetOptions.android_native.versionName = '1.0'; project.targetOptions.android_native.screenOrientation = 'landscape'; project.targetOptions.android_native.permissions = ['android.permission.VIBRATE']; // iOS options project.targetOptions.ios.bundle = 'com.mycompany.mygame'; project.targetOptions.ios.developmentTeam = 'ABCD123456'; project.targetOptions.ios.version = '1.0'; // Build event callbacks callbacks.postBuild = function() { console.log('Build complete!'); }; // Include sub-project await project.addProject('Libraries/MyLibrary'); resolve(project); ``` -------------------------------- ### Configure VS Code Tasks for HTTP Server Source: https://github.com/kode/kha/wiki/Debugging This task configuration for VS Code's tasks.json starts a local HTTP server to serve the HTML5 build of a Kha project. It uses the 'http-server' npm package and specifies the build directory as the root. ```json { "version": "2.0.0", "tasks": [ { "label": "Start Server", "type": "shell", "command": "npx", "args": [ "http-server", "${workspaceFolder}/build/html5" ] } ] } ``` -------------------------------- ### Kha Render Target Creation and Usage Source: https://context7.com/kode/kha/llms.txt Illustrates how to create and utilize off-screen render targets in Kha for drawing. It covers basic creation, creation with advanced options (depth buffer, anti-aliasing), drawing to the target, and rendering the target to the screen. Requires importing Kha modules. ```haxe import kha.Image; import kha.Color; import kha.Framebuffer; import kha.graphics4.DepthStencilFormat; import kha.graphics4.TextureFormat; class RenderTargetExample { var renderTarget: Image; public function new() { // Create a 512x512 render target renderTarget = Image.createRenderTarget(512, 512); } public function createWithOptions() { // Create render target with depth buffer for 3D rendering renderTarget = Image.createRenderTarget( 1024, 1024, TextureFormat.RGBA32, DepthStencilFormat.DepthOnly, 4 // anti-aliasing samples ); } public function drawToRenderTarget() { var g = renderTarget.g2; g.begin(true, Color.Transparent); g.color = Color.Red; g.fillRect(20, 20, 100, 100); g.color = Color.Blue; g.fillRect(80, 80, 100, 100); g.end(); } public function render(framebuffer: Framebuffer) { // First draw to render target drawToRenderTarget(); // Then draw render target to screen var g = framebuffer.g2; g.begin(true, Color.Black); g.color = Color.White; g.drawScaledImage(renderTarget, 100, 100, 256, 256); g.end(); } public function cleanup() { renderTarget.unload(); // Free GPU memory } } ``` -------------------------------- ### Enable Anti-Aliasing with FrameBufferOptions in System.start() Source: https://github.com/kode/kha/wiki/FAQ Configure hardware anti-aliasing globally by specifying the 'samplesPerPixel' in the FrameBufferOptions of the System.start() function. The system attempts to find a supported sample count close to the provided value. Note that hardware anti-aliasing support varies across hardware, OS, drivers, and targets. ```javascript System.start({ width: 1024, height: 768, framebuffer: { samplesPerPixel: 4 } }, function(_) {}); ``` -------------------------------- ### Customize Local Library Directory (JavaScript) Source: https://github.com/kode/kha/wiki/Libraries Shows how to specify a custom directory for local libraries in a Kha project's `khafile.js`. By default, Kha looks in a folder named `Libraries`. This example sets the local library path to `libs` using `project.localLibraryPath` before adding libraries. ```javascript project.localLibraryPath = 'libs'; ``` -------------------------------- ### Add Libraries to Kha Project (JavaScript) Source: https://github.com/kode/kha/wiki/Libraries Demonstrates how to add external libraries to a Kha project using the `khafile.js` configuration file. Libraries like 'Kha2D' and 'zui' can be added using the `project.addLibrary()` method. Khamake will then locate these libraries in the project's `Libraries` folder or Haxelib installation. ```javascript project.addLibrary("Kha2D"); project.addLibrary("zui"); ``` -------------------------------- ### Play Audio with Kha audio1.Audio Source: https://context7.com/kode/kha/llms.txt Kha.audio1.Audio provides basic audio playback for sounds and music. It supports playing sounds directly or streaming music. Sounds may need to be uncompressed before playback for optimal performance. Dependencies include 'kha.audio1.Audio', 'kha.audio1.AudioChannel', 'kha.Assets', and 'kha.Sound'. ```Haxe import kha.audio1.Audio; import kha.audio1.AudioChannel; import kha.Assets; import kha.Sound; class AudioManager { var musicChannel: AudioChannel; var soundEffects: Map = new Map(); public function init() { // Sounds must be uncompressed before playing (done automatically by loadEverything) // For individual loading, manually uncompress: Assets.loadSound("explosion", function(sound: Sound) { sound.uncompress(function() { soundEffects.set("explosion", sound); }); }); } public function playSoundEffect(name: String) { var sound = soundEffects.get(name); if (sound != null) { var channel = Audio.play(sound, false); // false = don't loop if (channel != null) { channel.volume = 0.8; } } } public function playMusic() { // Stream for long audio files (music) - doesn't need uncompress musicChannel = Audio.stream(Assets.sounds.background_music, true); // true = loop if (musicChannel != null) { musicChannel.volume = 0.5; } } public function pauseMusic() { if (musicChannel != null) { musicChannel.pause(); } } public function resumeMusic() { if (musicChannel != null) { musicChannel.play(); } } public function stopMusic() { if (musicChannel != null) { musicChannel.stop(); musicChannel = null; } } public function setMusicVolume(volume: Float) { if (musicChannel != null) { musicChannel.volume = volume; // 0.0 to 1.0 } } } ``` -------------------------------- ### Selective Asset Embedding in khafile.js Source: https://github.com/kode/kha/wiki/Embedding-Assets-Within-Built-Applications This example illustrates a strategy for embedding specific asset types (like audio and textures) while leaving others accessible in their original locations. It uses `project.addAssets()` for directories containing specific file types, allowing for a mix of embedded and non-embedded assets. Dependencies: Kha build system. ```javascript project.addAssets('Assets/audio/**'); project.addAssets('Assets/texture/**'); ``` -------------------------------- ### Load All Assets Source: https://context7.com/kode/kha/llms.txt Loads all assets detected by khamake from the Assets folder. It provides a callback for when loading is complete and an error handler for failures. Individual asset loading functions are also available. ```haxe import kha.Assets; import kha.Image; import kha.Sound; import kha.Font; class AssetLoader { public static function loadAllAssets(callback: () -> Void) { // Load all assets detected by khamake Assets.loadEverything(function() { // Access loaded assets via Assets.images, Assets.sounds, etc. var playerSprite: Image = Assets.images.player; var jumpSound: Sound = Assets.sounds.jump; var mainFont: Font = Assets.fonts.arial; callback(); }, null, null, function(error) { trace("Failed to load asset: " + error.url); }); } public static function loadSingleImage(name: String, callback: Image -> Void) { Assets.loadImage(name, function(image: Image) { callback(image); }, function(error) { trace("Error loading image: " + error.error); }); } public static function loadFromPath() { // Load image from arbitrary path Assets.loadImageFromPath("images/custom.png", false, function(image) { trace("Loaded image: " + image.width + "x" + image.height); }); } } ```