### Heaps Application Setup and Sprite Creation Source: https://github.com/heapsio/heaps/wiki/Simple-sprites Demonstrates initializing Heaps resources and creating various types of sprites within an hxd.App. Includes examples for single sprites, sprite strips, sprite sheets, and using `autoCut`. ```haxe import hxd.Res; import h2d.Tile; import h2d.Bitmap; class SimpleSprites extends hxd.App { static function main() { new SimpleSprites(); Res.initLocal(); } override function init() { // creating a simple sprite var tile = Res.mysprite.toTile(); var bmp = new Bitmap( tile, s2d ); infoLabel(bmp,"a simple sprite"); // creating a sprite strip (a row of sprites, horizontal) var tiles = Res.mysprite_strip.toTile().split( 3 ); var bmp = new Bitmap( tiles[1], s2d ); infoLabel(bmp,"from a strip\n(index = 1)"); // creating a sprite sheet (a grid of sprites) var tiles = Res.mysprite_sheet.toTile().grid( 32 ); var bmp = new Bitmap( tiles[1][0], s2d ); infoLabel(bmp,"from a sheet\n(index: x=1, y=0)"); // using autoCut (will also punch the background in case it's not transparent) var tile = Tile.autoCut( Res.mysprite_sheet.toBitmap(), 32, 32 ); // (!!!) mind size (!!!) var bmp = new Bitmap( tile.tiles[0][0], s2d ); infoLabel(bmp,"autoCut()\nalso a sheet/grid\n(index: x=0, y=0)"); // a simple sprite again, but the tile is centered and horizontally flipped var tile = tile.tiles[1][0]; // uses the sheet from above tile = tile.center(); tile.flipX(); var bmp = new Bitmap( tile, s2d ); infoLabel(bmp,"centered + flipped"); // (representation) // position all added `h2d.Object`s var _y = 0; for( o in s2d.getLayer(0) ) o.setPosition( 250, (++_y)*100 ); } function infoLabel( obj:h2d.Object, infotext:String ){ var t = new h2d.Text( hxd.res.DefaultFont.get(), obj ); t.text = infotext; t.setPosition( -225, 0 ); } } ``` -------------------------------- ### Install Heaps from GitHub Source: https://github.com/heapsio/heaps/wiki/Installation Installs the bleeding-edge version of Heaps directly from its GitHub repository. This is the recommended option for the latest features. ```bash haxelib git heaps https://github.com/HeapsIO/heaps.git ``` -------------------------------- ### Intro Scene Implementation Source: https://github.com/heapsio/heaps/wiki/Scenes An example of an introductory scene that displays text and transitions to the main menu after a delay. It uses `h2d.Text` for displaying information and `haxe.Timer` for timed events. ```haxe class Intro extends h2d.Scene { public function new() { super(); var t = new h2d.Text( hxd.res.DefaultFont.get(), this ); t.text = "Intro scene"; trace(t.text); var t = new h2d.Text( hxd.res.DefaultFont.get(), this ); t.setPosition( 50, 50 ); t.text = "Game by _____" ; t.scale( 3 ); t.textColor = 0x00FFFF; var t = new h2d.Text( hxd.res.DefaultFont.get(), this ); t.setPosition( 50, 150 ); t.text = "Created with the Heaps game engine.\nSee more on\nhttps://heaps.io"; t.scale( 2 ); t.textColor = 0x606060; var t = new haxe.Timer( 3 * 1000 ); t.run = () -> { Main.app.setScene( new MainMenu() ); t.stop(); }; } } ``` -------------------------------- ### Install Additional Libraries from GitHub Source: https://github.com/heapsio/heaps/wiki/Installation Installs the latest versions of libraries for HashLink support directly from their GitHub repositories. This is recommended for access to the newest updates. ```bash haxelib git hlopenal https://github.com/HaxeFoundation/hashlink master libs/openal haxelib git hlsdl https://github.com/HaxeFoundation/hashlink master libs/sdl haxelib git hldx https://github.com/HaxeFoundation/hashlink master libs/directx ``` -------------------------------- ### Install Additional Libraries for HashLink Source: https://github.com/heapsio/heaps/wiki/Installation Installs essential libraries for HashLink target support, such as OpenAL, DirectX, and SDL/GL. Use this command for stable library versions. ```bash haxelib install hlopenal haxelib install hlsdl haxelib install hldx ``` -------------------------------- ### Initialize and Setup Roguelike Game Source: https://github.com/heapsio/heaps/wiki/Rogue Sets up the game's initial state, including displaying instructions, parsing the level string into game objects, and configuring the camera to follow the player. Ensure the level string is correctly formatted. ```haxe class Roguelike extends hxd.App { var player : h2d.Object; final fieldSize = 32; var levelString : String = "\n\n ###################\n ########################### # #\n # # # A #\n # ############ #\n # #\n # @ ############ #\n # # # #\n # # # C #\n # # ###################\n # E #\n # #\n ###########################\n "; var walls : Array = []; var howToPlayInfo : h2d.Object; static function main() {new Roguelike();} override function init() { var t = new h2d.Text( hxd.res.DefaultFont.get(), s2d ); t.text = "Use the arrow keys\nor w-a-s-d to move around."; t.scale(2); howToPlayInfo = t; // setting up the level from a string var x = 0; var y = 0; for( i in 0...levelString.length ){ var char = levelString.charAt( i ); if( char=="\n"){ y++; x=0; } else if( char!=" ") characterToGameObject( char, x, y ); x++; } // setting camera s2d.camera.anchorX = 0.5; s2d.camera.anchorY = 0.5; // placing how-to-play info correctly (after player has been placed) var cam = s2d.camera; howToPlayInfo.setPosition( player.x - (cam.viewportWidth/2), player.y - (cam.viewportHeight/2) ); } function characterToGameObject( character:String, x:Float, y:Float ){ if( character!=" " ) { // no empty objects var o = new h2d.Object( s2d ); var t = new h2d.Text( hxd.res.DefaultFont.get(), o ); t.text = character; t.scale( 2 ); o.setPosition( x *fieldSize, y *fieldSize ); // creating the "real" logical object switch ( character ){ case "@": // the player player = o; // basic camera s2d.camera.follow = player; case "#": // walls walls.push( o ); default: trace('The character <$character> hasn\'t been assigned to a game object.'); // doesn\'t work right... but good enough } } } var dt_counter : Float = 0; override function update(dt:Float) { dt_counter += dt; if( dt_counter > 0.1 ) { // 10 times per second // player movement if( hxd.Key.isDown( hxd.Key.UP ) || hxd.Key.isDown( hxd.Key.W ) ) moveIfPositionIsWallFree( player, player.x, player.y - fieldSize ); // okay the code\'s a bit clunky I admit that! if( hxd.Key.isDown( hxd.Key.DOWN ) || hxd.Key.isDown( hxd.Key.S ) ) moveIfPositionIsWallFree( player, player.x, player.y + fieldSize ); if( hxd.Key.isDown( hxd.Key.LEFT ) || hxd.Key.isDown( hxd.Key.A ) ) moveIfPositionIsWallFree( player, player.x - fieldSize, player.y ); if( hxd.Key.isDown( hxd.Key.RIGHT ) || hxd.Key.isDown( hxd.Key.D ) ) moveIfPositionIsWallFree( player, player.x + fieldSize, player.y ); dt_counter -= 0.1; // reset // could also just do `dt_counter = 0;` but is less fine } } function moveIfPositionIsWallFree( obj:h2d.Object, x:Float, y:Float ) { if( checkIfPositionIsWallFree(x,y) ) obj.setPosition(x,y); } function checkIfPositionIsWallFree( x:Float, y:Float ) : Bool { var free = true; for( w in walls ){ if( w.x == x && w.y == y ) free = false; } return free; } } ``` -------------------------------- ### Initialize PBR Material Renderer Source: https://github.com/heapsio/heaps/wiki/PBR-Materials This code sets the global material setup to use PBR materials, automatically creating the necessary renderer, environment, and lighting systems. ```haxe //The following will automatically create a PBR Material renderer. //It will also create the correct environment and //lighting system that must be used for PBR materials. h3d.mat.MaterialSetup.current = new h3d.mat.PbrMaterialSetup(); ``` -------------------------------- ### Install Heaps using haxelib Source: https://github.com/heapsio/heaps/wiki/Installation Installs the latest stable version of the Heaps engine using the haxelib package manager. Ensure haxelib is recognized in your command line. ```bash haxelib install heaps ``` -------------------------------- ### Heaps Application Entry Point (`hxd.App`) Source: https://context7.com/heapsio/heaps/llms.txt Subclass `hxd.App` to manage application lifecycle. Override `init()` for setup, `update(dt)` for per-frame logic, and `onResize()` for window events. `s2d` and `s3d` provide access to the 2D and 3D scenes respectively. ```Haxe class Main extends hxd.App { var bmp : h2d.Bitmap; override function init() { // Initialize resources (embed all files from /res at compile time) hxd.Res.initEmbed(); // Create a red 100x100 tile and display it var tile = h2d.Tile.fromColor(0xFF0000, 100, 100); bmp = new h2d.Bitmap(tile, s2d); bmp.x = s2d.width * 0.5; bmp.y = s2d.height * 0.5; // Center pivot bmp.tile.dx = -50; bmp.tile.dy = -50; } override function update(dt : Float) { // dt = elapsed seconds since last frame bmp.rotation += dt * 1.5; // rotate ~1.5 rad/s } override function onResize() { bmp.x = s2d.width * 0.5; bmp.y = s2d.height * 0.5; } static function main() { new Main(); } } ``` -------------------------------- ### Build HashLink/C Output with Visual Studio MSBuild Source: https://github.com/heapsio/heaps/wiki/HashLink Makefile example for building a HashLink C project using MSBuild. It allows specifying the platform (e.g., x64) and build configuration (e.g., Release). ```makefile PLATFORM=x64 MS_BUILD?="C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/MSBuild/Current/Bin/MSBuild.exe" #MS_BUILD?="C:/Program Files/Microsoft Visual Studio/2022/Community/MSBuild/Current/Bin/MSBuild.exe" CONFIG?=Release all: $(MS_BUILD) game.sln -t:game -nologo -verbosity:minimal -property:Configuration=$(CONFIG) -property:Platform=$(PLATFORM) ``` -------------------------------- ### Full Scene Capture and Display Example Source: https://github.com/heapsio/heaps/wiki/Render-Target Demonstrates rendering one scene (obj2) to a render target and then displaying that render target's texture on an object (obj1) in a second scene. Requires initialization of two scenes and careful management of render targets. ```haxe override function init() { rendertarget = new Texture(engine.width,engine.height, [ Target ]); rendertarget.depthBuffer = new DepthBuffer(engine.width, engine.height); s3dTarget = new h3d.scene.Scene(); // The object we're going to display in our scene var prim = h3d.prim.Cube.defaultUnitCube(); var mat = h3d.mat.Material.create(renderTarget); obj1 = new h3d.scene.Mesh(prim, mat, s3d); // The object we're going to capture in our Render Target obj2 = cache.loadModel(hxd.Res.mdl.test2); s3dTarget.addChild(obj2); } override function render(e:h3d.Engine) { // Render the target first engine.pushTarget(renderTarget); engine.clear(0, 1); s3dTarget.render(e); engine.popTarget(); // Now render our scene s3d.render(e); s2d.render(e); } ``` -------------------------------- ### Haxe Layers Example Source: https://github.com/heapsio/heaps/wiki/Layers Demonstrates adding objects to different layers and using ysort for depth sorting. Houses are sorted by their y-position, clouds are in a sky layer, and soil is in the background layer. ```Haxe class Main extends hxd.App { var clouds : Array = []; var LAYER_FOR_SOIL : Int = 0; var LAYER_FOR_BUILDINGS : Int = 1; var LAYER_FOR_SKY : Int = 2; static function main() { new Main(); } override function init() { engine.backgroundColor = 0xFF33cc33; // game's background color is now green for( i in 0...40 ) add_house(); for( i in 0...40 ) add_cloud(); for( i in 0...20 ) add_soil_stain(); // button to add houses var addHouseButton = new h2d.Interactive( 200, 32, s2d ); addHouseButton.backgroundColor = 0xFF0000FF; addHouseButton.onClick = (e)->{ var h = add_house(); trace('New house at (${h.x}|${h.y})'); }; var t = new h2d.Text( hxd.res.DefaultFont.get(), addHouseButton ); t.text = "Press here to add a house"; } function add_house() : h2d.Object { var g = new h2d.Graphics(); g.beginFill( 0xFFFFFF ); g.drawRect( -20, 0, 40, 24 ); // a window g.beginFill( 0x6699ff ); g.drawRect( -8, 8, 8, 8 ); g.beginFill( 0x6699ff ); g.drawRect( 2, 8, 8, 8 ); // roof g.beginFill( 0xFF0000 ); g.addVertex( -20, 0, 1, 0, 0, 1 ); g.addVertex( 0, -16, 1, 0, 0, 1 ); g.addVertex( 20, 0, 1, 0, 0, 1 ); g.addVertex( -20, 0, 1, 0, 0, 1 ); g.endFill(); set_to_random_postion( g ); s2d.add( g, LAYER_FOR_BUILDINGS ); return g; // allows to receive the reference to the created object... } function add_cloud() { var g = new h2d.Graphics(); // Haxe is very mighty when it comes to functions: var add_row_of_bubbles = (maxAmountAdd:Int, yLevel:Float ) -> { var bubbles : Int = 3 + Math.round( hxd.Math.random( maxAmountAdd ) ); var colors : haxe.ds.Vector = new haxe.ds.Vector(3); colors[0] = 0xFFFFFF; colors[1] = 0xf2f2f2; colors[2] = 0xe6e6e6; var i : Int = Math.round( hxd.Math.random( colors.length-1) ); g.beginFill( colors[i] ); for( i in 0...bubbles ) g.drawCircle( -16+hxd.Math.random(32), 0+yLevel, 4 + hxd.Math.random(8) ); } add_row_of_bubbles( 8, -8 ); // upper level of bubbles add_row_of_bubbles( 24, 0 ); // lower level of bubbles set_to_random_postion( g ); clouds.push( g ); s2d.add( g, LAYER_FOR_SKY ); } function add_soil_stain() { var g = new h2d.Graphics(); g.beginFill( 0x84e184 ); // lighter green g.drawEllipse( 0, 0, 32 + hxd.Math.random(64), 8 + hxd.Math.random(8) ); set_to_random_postion( g ); s2d.add( g, LAYER_FOR_SOIL ); } function set_to_random_postion( obj:h2d.Object ) { obj.setPosition( hxd.Math.random( s2d.width ), hxd.Math.random( s2d.height ) ); } override function update(dt:Float) { for( c in clouds ){ c.x += 0.1; if( c.x > s2d.width ) c.x = 0; } s2d.ysort( LAYER_FOR_BUILDINGS ); // buildings rendered in correct order! } } ``` -------------------------------- ### Implement Real-time Shadows in Heaps H3D Source: https://github.com/heapsio/heaps/wiki/Shadows This example demonstrates setting up a scene with objects that cast and receive shadows. Ensure normals are added to geometry and lighting is enabled. The floor receives shadows, while spheres cast and receive them. A directional light and camera controller are included. ```haxe //Create a floor plane where we can view our cast shadows var floor = new h3d.prim.Cube(10, 10, 0.1); //Make sure se add normals floor.addNormals(); floor.translate( -5, -5, 0); var m = new h3d.scene.Mesh(floor, s3d); //Enabled lighting m.material.mainPass.enableLights = true; //Enable receieiving of shadows. Our floor does not need to cast m.material.receiveShadows = true; //Greate some sphere geometry for casting and receiving shadows var sphere = new h3d.prim.Sphere(1, 32, 24); //Make sure we add normals sphere.addNormals(); var p = new h3d.scene.Mesh(sphere, s3d); p.z = 1; p.material.mainPass.enableLights = true; //Enable casting and receiving of shadows p.material.shadows = true; p.material.color.setColor(Std.random(0x1000000)); var p2 = new h3d.scene.Mesh(sphere, s3d); p2.z = 2.5; p2.x = 1; p2.y = 1; p2.scale(0.5); p2.material.mainPass.enableLights = true; //Enable casting and receiving of shadows p2.material.shadows = true; p2.material.color.setColor(Std.random(0x1000000)); //Set up a light otherwise we don't get any shadows var directionalLight = new h3d.scene.DirLight(new h3d.Vector(-0.3, -0.2, -1), s3d); //Move our camera to a position to see the shadows s3d.camera.pos.set(12, 12, 6); //Setup a Camera Controller to move the camera new h3d.scene.CameraController(s3d).loadFromCamera(); ``` -------------------------------- ### Build HashLink/C Output with GCC Source: https://github.com/heapsio/heaps/wiki/HashLink Example GCC command to compile the generated C code for HashLink. This command includes optimization, standard C version, include paths, and links necessary HashLink libraries. ```bash cd bin gcc -O3 -o mygame -std=c11 -I hlout hlout/game.c -lhl -lheaps.hdll -lui.hdll -lfmt.hdll [-L/path/to/required/hdll] ``` -------------------------------- ### Basic Flow Layout Example Source: https://github.com/heapsio/heaps/wiki/Flow Demonstrates the creation and basic arrangement of child objects within an h2d.Flow container. The default layout is horizontal. ```haxe class FlowsDemo extends hxd.App { static function main() {new FlowsDemo();} override function init() { // the mere container var flow = new h2d.Flow( s2d ); flow.setPosition( 50, 50 ); // setting the flow design // by default will be: //flow.layout = h2d.Flow.FlowLayout.Horizontal; // these objects below get added to the flow var t = new h2d.Text( hxd.res.DefaultFont.get(), flow ); t.text = "Some text."; var tile = h2d.Tile.fromColor( 0x0000FF, 96, 32 ); var b = new h2d.Bitmap( tile, flow ); var t = new h2d.Text( hxd.res.DefaultFont.get(), flow ); t.text = "A bigger text."; t.scale(3); var ia = new h2d.Interactive( 50, 50, flow ); ia.backgroundColor = 0xFF808080; ia.onClick = (e)->{trace("Click!");}; // red line to draw the flow borders var t = new h2d.Text( hxd.res.DefaultFont.get(), s2d ); t.text = "Red-lined rectangle represents the h2d.Flow object."; var g = new h2d.Graphics( s2d ); g.lineStyle( 1, 0xFF0000 ); var bounds = flow.getBounds(); g.drawRect( bounds.x, bounds.y, bounds.width, bounds.height ); } } ``` -------------------------------- ### Set Material Blend Mode Source: https://github.com/heapsio/heaps/wiki/Materials Demonstrates how to set the blend mode for a material to control how it interacts with objects behind it. The example uses 'BlendMode.Add'. ```haxe mat.blendMode = h2d.BlendMode.Multiply; enum BlendMode { None; Alpha; Add; SoftAdd; Multiply; Erase; Screen; } ``` -------------------------------- ### Heaps Application with Text and Bitmap Source: https://github.com/heapsio/heaps/wiki/H2D-Introduction This example demonstrates adding a text label and a red bitmap to the Heaps application. The bitmap is created from a solid color and its position and rotation are updated each frame. Requires `h2d.Text`, `h2d.Bitmap`, and `h2d.Tile`. ```haxe class Main extends hxd.App { var bmp : h2d.Bitmap; override function init() { var tf = new h2d.Text(hxd.res.DefaultFont.get(), s2d); tf.text = "Hello World !"; // allocate a Texture with red color and creates a 100x100 Tile from it var tile = h2d.Tile.fromColor(0xFF0000, 100, 100); // create a Bitmap object, which will display the tile // and will be added to our 2D scene (s2d) bmp = new h2d.Bitmap(tile, s2d); // modify the display position of the Bitmap sprite bmp.x = s2d.width * 0.5; bmp.y = s2d.height * 0.5; } // on each frame override function update(dt:Float) { // increment the display bitmap rotation by 0.1 radians bmp.rotation += 0.1; } static function main() { new Main(); } } ``` -------------------------------- ### Setup PBR Environment Map Source: https://github.com/heapsio/heaps/wiki/PBR-Materials Configures a sphere for the skybox and creates an environment map texture. This is used to provide realistic lighting and reflections for PBR materials. Ensure you have 'hxd.Res.front', 'hxd.Res.back', etc. available. ```haxe //Create a sphere that will be used for our Sky Sphere and the mesh of our PBR materials var sp = new h3d.prim.Sphere(1, 128, 128); //Make sure to add UVs and sp.addNormals(); sp.addUVs(); //Create a background mesh var bg = new h3d.scene.Mesh(sp, s3d); bg.scale(10); //Make sure it is always rendered bg.material.mainPass.culling = Front; bg.material.mainPass.setPassName("overlay"); //Create an environment map texture var envMap = new h3d.mat.Texture(512, 512, [Cube]); envMap.name = "envMap"; inline function set(face:Int, res:hxd.res.Image) { var pix = res.getPixels(); envMap.uploadPixels(pix, 0, face); } //Set the faces for the environment cube map set(0, hxd.Res.front); set(1, hxd.Res.back); set(2, hxd.Res.right); set(3, hxd.Res.left); set(4, hxd.Res.top); set(5, hxd.Res.bottom); //Create a new environment that we can use to control some of the material behavior var env = new h3d.scene.pbr.Environment(envMap); env.compute(); //Set the environment on the custom PBR renderer renderer = cast(s3d.renderer, h3d.scene.pbr.Renderer); renderer.env = env; //Finally create a shader and apply it to the background mesh so we can actually render our environment on screen. var cubeShader = bg.material.mainPass.addShader(new h3d.shader.pbr.CubeLod(env.env)); ``` -------------------------------- ### Heaps Drawable Objects Example (Haxe) Source: https://github.com/heapsio/heaps/wiki/Drawable This snippet demonstrates the creation and basic configuration of several drawable objects within a Heaps application. It includes h2d.Text, h2d.Bitmap, h2d.Graphics, h2d.Anim, and h2d.Interactive elements, along with their positioning and event handling. ```Haxe class Main extends hxd.App { static function main() { new Main(); } override function init() { // a h2d.Text (like from the Hello World! sample) var text = new h2d.Text( hxd.res.DefaultFont.get(), s2d ); text.text = "A simple h2d.Text"; text.textColor = 0xFBC707; // a h2d.Bitmap (from coded tile, no resource used) var bitmap = new h2d.Bitmap( h2d.Tile.fromColor( 0xFF0000, 32, 32 ), s2d ); // a h2d.Graphics var graphics = new h2d.Graphics( s2d ); graphics.lineStyle( 2, 0xFFFFFF ); graphics.beginFill( 0x33cc33 ); graphics.drawCircle( 0, 0, 16 ); graphics.beginFill( 0xff6666 ); graphics.drawRect( 4, 4, 12, 12 ); // an h2d.Anim object var k = 32; var tfa = []; // tiles for animation "tfa" tfa.push( h2d.Tile.fromColor( 0xFF0000, k, k ) ); tfa.push( h2d.Tile.fromColor( 0xFFFF00, k, k ) ); tfa.push( h2d.Tile.fromColor( 0x00FFFF, k, k ) ); tfa.push( h2d.Tile.fromColor( 0x0000FF, k, k ) ); tfa.push( h2d.Tile.fromColor( 0xFF00FF, k, k ) ); var anim = new h2d.Anim( tfa, 2, s2d ); // a h2d.Interactive (button-like) object var interactive = new h2d.Interactive( 100, 50, s2d ); var col_default = 0xFF3366ff; var col_over = 0xFF809fff; var col_push = 0xFF33cc33; interactive.backgroundColor = col_default; interactive.onOver = (e)->{ interactive.backgroundColor = col_over; }; interactive.onOut = (e)->{ interactive.backgroundColor = col_default; }; interactive.onPush = (e)->{ interactive.backgroundColor = col_push; }; interactive.onClick = (e)->{ trace("Clicking button."); }; // info texts explanationLabel( text, "h2d.Text:" ); explanationLabel( bitmap, "h2d.Bitmap:" ); explanationLabel( graphics, "h2d.Graphics:" ); explanationLabel( anim, "h2d.Anim:" ); explanationLabel( interactive, "h2d.Interactive:\n(click me)" ); // scatter positions text .setPosition( 200, 100 ); bitmap .setPosition( 200, 200 ); graphics .setPosition( 200, 300 ); anim .setPosition( 200, 400 ); interactive.setPosition( 200, 500 ); } function explanationLabel( obj:h2d.Object, explanation:String ) : h2d.Text { var t = new h2d.Text( hxd.res.DefaultFont.get(), obj ); t.text = explanation; t.setPosition( -150, 0 ); return t; } } ``` -------------------------------- ### Drawing Tiles from Tiled Map Data Source: https://github.com/heapsio/heaps/wiki/Drawing-Tiles This example demonstrates loading a Tiled map export in JSON format and rendering it using Heaps.io's h2d.TileGroup for static terrain, h2d.Bitmap for a backdrop, and h2d.SpriteBatch for moving sprites. Ensure resource files like backdrop.png, bunnies.png, tiles.png, and tiles.json are in the /res folder. ```Haxe class Main extends hxd.App { static function main() { // embed the resources hxd.Res.initEmbed(); new Main(); } override private function init() { super.init(); // Add backdrop Bitmap var bitmap = new h2d.Bitmap(hxd.Res.backdrop.toTile(), s2d); // parse Tiled json file var mapData:TiledMapData = haxe.Json.parse(hxd.Res.tiles_json.entry.getText()); // get tile image (tiles.png) from resources var tileImage = hxd.Res.tiles_png.toTile(); // create a TileGroup for fast tile rendering, attach to 2d scene var group = new h2d.TileGroup(tileImage, s2d); var tw = mapData.tilewidth; var th = mapData.tileheight; var mw = mapData.width; var mh = mapData.height; // make sub tiles from tile var tiles = [ for(y in 0 ... Std.int(tileImage.height / th)) for(x in 0 ... Std.int(tileImage.width / tw)) tileImage.sub(x * tw, y * th, tw, th) ]; // iterate on all layers for(layer in mapData.layers) { // iterate on x and y for(y in 0 ... mh) for (x in 0 ... mw) { // get the tile id at the current position var tid = layer.data[x + y * mw]; if (tid != 0) { // skip transparent tiles // add a tile to the TileGroup group.add(x * tw, y * th, tiles[tid - 1]); } } } // Create raining bunnies with SpriteBatch var bunnies = hxd.Res.bunnies.toTile(); var batch = new h2d.SpriteBatch(bunnies, s2d); batch.hasRotationScale = true; batch.hasUpdate = true; // Note: Does not count as a bunnymark. for (i in 0...100) { var bunny = new Bunny(bunnies); batch.add(bunny); bunny.reset(); } } } class Bunny extends h2d.SpriteBatch.BasicElement { public function new(t:h2d.Tile) { super(t); gravity = 100; } public function reset() { y = -t.height; x = Math.random() * (batch.getScene().width - t.width); scale = 1 + (Math.random() - 0.5) * .1; vx = Math.random() * 60; } override function update(dt:Float) { super.update(dt); if (y > batch.getScene().height) reset(); return true; } } // simple type definition for Tile map typedef TiledMapData = { layers:Array<{ data:Array}>, tilewidth:Int, tileheight:Int, width:Int, height:Int }; ``` -------------------------------- ### HashLink HXML Configuration for Slide Source: https://github.com/heapsio/heaps/wiki/Demo-of-Slide This is an example hxml file configuration for compiling a Heaps application using the Slide library with HashLink. It specifies the necessary libraries and the main class. ```hxml -lib heaps -lib hlsdl -lib slide -main SlideLibDemo -hl slide_demo.hl ``` -------------------------------- ### H3D Scene Interaction Setup Source: https://github.com/heapsio/heaps/wiki/H3D-Events-and-Interactivity Set up an interactive object in an H3D scene by creating an Interactive instance with a collider and scene object. Define callbacks for various interaction events such as onOver, onOut, onClick, onPush, and onRelease. ```Haxe var interaction = new h3d.scene.Interactive(collider, s3d); interaction.onOver = function(event) { trace("over"); } interaction.onOut = function(event) { trace("out"); } interaction.onClick = function(event) { trace("click!"); } interaction.onPush = function(event) { trace("down!"); } interaction.onRelease = function(event) { trace("up!"); } interaction.onClick = function(event) { trace("click!"); } ``` -------------------------------- ### Initialize Pak File System with Configuration Source: https://github.com/heapsio/heaps/wiki/Resource-Baking For Pak file systems, run the pak builder with the `-config ` flag. This generates a `res..pak` file that can then be loaded using `hxd.Res.initPak`. ```bash pak builder -config ``` -------------------------------- ### Heaps Slide Tweening Example Source: https://github.com/heapsio/heaps/wiki/Demo-of-Slide This Haxe code snippet demonstrates how to use the Slide library to animate a h2d.Graphics object. It defines a path with movements, waits, and easing, and includes callbacks for cycle completion and slide finishing. Ensure Slide is installed and imported. ```haxe import slide.Slide; class SlideLibDemo extends hxd.App { static function main() { new SlideLibDemo(); } override function init() { var g = new h2d.Graphics( s2d ); g.beginFill( 0xFFFFFF ); g.drawRect( 0, 0, 50, 50 ); g.setPosition(60,60); var foo = ()->{ trace("Cycle accomplished!"); }; var fin = ()->{ trace("Slide finished."); }; Slide.tween( g ) .to({x:400}, 1.5) .to({y:300}, 1 ) .wait(0.5) .to({x:60,y:60}, 0.5) .ease(slide.easing.Quad.easeIn) .call( (o)->{ foo(); trace(o,o.x,o.y); o.rotate(0.3); } ) .onComplete( fin ) .repeat(-1) // -1 = infinity (actually prevents function fin to be called here) .start(); } override function update(dt:Float) { Slide.step(dt); // tell Slide how many seconds have elapsed } } ``` -------------------------------- ### 3D Scene Initialization and Primitives Source: https://context7.com/heapsio/heaps/llms.txt Sets up a 3D application, initializes resources, and creates basic 3D primitives like cubes and spheres. Normals and UVs are added for lighting and texturing. ```haxe class My3DApp extends hxd.App { override function init() { hxd.Res.initEmbed(); // ── Primitives ──────────────────────────────────────────────────────── var cube = new h3d.prim.Cube(1, 1, 1); cube.addNormals(); cube.addUVs(); var sphere = new h3d.prim.Sphere(1, 32, 24); sphere.addNormals(); var meshCube = new h3d.scene.Mesh(cube, s3d); var meshSphere = new h3d.scene.Mesh(sphere, s3d); meshSphere.x = 3; // ── Materials ───────────────────────────────────────────────────────── meshCube.material.color.setColor(0xFF6633); meshCube.material.mainPass.enableLights = true; meshCube.material.shadows = true; // cast + receive meshCube.material.receiveShadows = true; // ── FBX / HMD model loading ─────────────────────────────────────────── var cache = new h3d.prim.ModelCache(); var hero = cache.loadModel(hxd.Res.characters.hero); s3d.addChild(hero); var anim = cache.loadAnimation(hxd.Res.characters.hero); hero.playAnimation(anim); // ── Lights ─────────────────────────────────────────────────────────── var sun = new h3d.scene.fwd.DirLight(new h3d.Vector(-0.3, -0.2, -1), s3d); sun.enableSpecular = true; sun.color.set(0.9, 0.9, 0.8); var pt = new h3d.scene.fwd.PointLight(s3d); pt.x = 5; pt.y = 0; pt.z = 4; pt.color.setColor(0xFF4400); pt.enableSpecular = true; s3d.lightSystem.ambientLight.set(0.1, 0.1, 0.15); // ── Shadow blurring ─────────────────────────────────────────────────── var shadowPass = s3d.renderer.getPass(h3d.pass.ShadowMap); shadowPass.blur.passes = 3; // ── Camera ──────────────────────────────────────────────────────────── s3d.camera.pos.set(8, 8, 5); s3d.camera.target.set(0, 0, 0); s3d.camera.fovY = 60; new h3d.scene.CameraController(s3d).loadFromCamera(); // FPS-style mouse control } override function update(dt : Float) { s3d.camera.pos.x += dt * 0.5; // camera animation } static function main() { new My3DApp(); } } ``` -------------------------------- ### Get Pixels from Image Source: https://github.com/heapsio/heaps/wiki/Graphical-surfaces Retrieves the pixel data from an image resource. ```haxe var mypixels = myimage.getPixels(); ``` -------------------------------- ### Initialize Local File System with Configuration Source: https://github.com/heapsio/heaps/wiki/Resource-Baking Use `hxd.Res.initLocal` to initialize the local file system with a specific configuration name. This allows for different resource handling based on the chosen configuration. ```haxe hxd.Res.initLocal(configurationName) ``` -------------------------------- ### Create Heaps 'Hello World' Application (Main.hx) Source: https://github.com/heapsio/heaps/wiki/Hello-World A basic Heaps application that displays 'Hello World !' using the `h2d.Text` component. ```haxe class Main extends hxd.App { override function init() { var tf = new h2d.Text(hxd.res.DefaultFont.get(), s2d); tf.text = "Hello World !"; } static function main() { new Main(); } } ``` -------------------------------- ### Custom Convert Implementation - Haxe Source: https://github.com/heapsio/heaps/wiki/Resource-Baking Example of a custom converter class that extends hxd.fs.Convert. It defines the source and destination formats and implements the conversion logic. ```haxe class MyCustomConvert extends hxd.fs.Convert { function new() { super("foo","bar"); // converts .foo files to .bar } override function convert() { // make a simple copy var bytes = sys.io.File.getBytes(srcPath); sys.io.File.saveBytes(dstPath, bytes); } // register the convert so it can be found static var _ = hxd.fs.Convert.register(new MyCustomConvert()); } ``` -------------------------------- ### Get File Content as String Source: https://github.com/heapsio/heaps/wiki/Rogue Use `sys.io.File.getContent` to read the content of a text file into a string. This is useful for loading custom level data or other text-based configurations. ```haxe sys.io.File.getContent( "path/to/file.txt" ) ``` -------------------------------- ### Apply and Color a Default Material Source: https://github.com/heapsio/heaps/wiki/Materials Applies a default white material to a cube geometry and then sets its color to Haxe orange. This is a basic setup before considering lighting. ```haxe var cube = new h3d.prim.Cube(); cube.translate( -0.5, -0.5, -0.5); var mesh = new Mesh(cube, s3d); mesh.material.color.setColor(0xEA8220); ``` -------------------------------- ### Get h2d.Text Dimensions Source: https://context7.com/heapsio/heaps/llms.txt Retrieve the calculated width and height of the rendered text. These dimensions are computed lazily upon first access after the text content or properties change. ```haxe // Measured dimensions (lazy, computed on first access after text change) trace(tf.textWidth, tf.textHeight); ``` -------------------------------- ### Heaps Application Entry Point Source: https://github.com/heapsio/heaps/wiki/Hello-HashLink Basic Heaps application structure using `hxd.App`. Initializes a text component to display 'Hello Hashlink !'. ```haxe class Main extends hxd.App { override function init() { var tf = new h2d.Text(hxd.res.DefaultFont.get(), s2d); tf.text = "Hello Hashlink !"; } static function main() { new Main(); } } ``` -------------------------------- ### Create a custom filter shader Source: https://github.com/heapsio/heaps/wiki/Filters Extends h3d.shader.ScreenShader to create a custom filter. This example modifies the red channel of the pixel color based on a provided 'red' parameter. ```haxe class MyFilterShader extends h3d.shader.ScreenShader { static var SRC = { @param var texture : Sampler2D; @param var red : Float; function fragment() { pixelColor = texture.get(input.uv); pixelColor.r = red; // change red channel } } } ``` -------------------------------- ### Initialize PAK FileSystem Loader Source: https://github.com/heapsio/heaps/wiki/Resource-Management Initialize the resource loader to use `hxd.fmt.pak.FileSystem`. This loads resources from `.pak` files in the local filesystem, with later loaded files overriding earlier ones. ```haxe hxd.Res.initPak(); ``` -------------------------------- ### Configure Multiple h2d.Camera Instances Source: https://context7.com/heapsio/heaps/llms.txt Add and remove additional camera objects to the scene for multi-camera setups. You can control their position, scale, and which camera handles user input. ```haxe // Multiple cameras var cam2 = new h2d.Camera(s2d); cam2.x = 100; cam2.y = 50; cam2.scaleX = 0.5; s2d.addCamera(cam2); s2d.removeCamera(cam2); s2d.interactiveCamera = s2d.camera; // only one camera handles input ``` -------------------------------- ### Initialize and Use Typed Resources with hxd.Res Source: https://context7.com/heapsio/heaps/llms.txt Initialize the resource system using `initEmbed`, `initLocal`, or `initPak`. Access assets via typed paths mirroring the directory structure. Supports dynamic loading and runtime loading from bytes. Includes live reload functionality for debug builds. ```haxe hxd.Res.initEmbed(); // embed all /res files into the binary (JS-friendly) hxd.Res.initLocal(); // read from local disk (HL/native) hxd.Res.initPak(); // load from res.pak, res1.pak, … (prepackaged) ``` ```haxe var tile : h2d.Tile = hxd.Res.player.toTile(); // PNG → Tile var texture : h3d.mat.Texture = hxd.Res.skybox.toTexture(); var sound : hxd.res.Sound = hxd.Res.music_loop; var model : hxd.res.Model = hxd.Res.characters.hero; ``` ```haxe var res : hxd.res.Any = hxd.Res.loader.load("ui/button.png"); var dynTile = res.toTile(); ``` ```haxe var bytes = hxd.net.BinaryLoader; // ... (platform-specific fetch) var anyRes = hxd.res.Any.fromBytes("sprite.png", rawBytes); ``` ```haxe hxd.Res.config_json.watch(function() { var data = hxd.Json.parse(hxd.Res.config_json.entry.getText()); trace("Config reloaded: " + data); }); hxd.Res.config_json.watch(null); // unwatch ``` ```haxe // haxe -hl hxd.fmt.pak.Build.hl -lib heaps -main hxd.fmt.pak.Build // hl hxd.fmt.pak.Build.hl ``` ```haxe // (in hxd.App subclass) override function loadAssets(done : Void -> Void) { new hxd.fmt.pak.Loader(s2d, done); } ``` -------------------------------- ### Haxe Compilation for HashLink Source: https://github.com/heapsio/heaps/wiki/Rogue This hxml file specifies the necessary libraries and the main class for compiling a Haxe project targeting HashLink. Ensure you have the 'heaps' and 'hlsdl' libraries installed. ```hxml -lib heaps -lib hlsdl -main Roguelike -hl roguelike.hl ```