diff --git a/standalone-openfl-app/src/ApplicationMain.hx b/standalone-openfl-app/src/ApplicationMain.hx index a08cb49b..2fdf4c84 100644 --- a/standalone-openfl-app/src/ApplicationMain.hx +++ b/standalone-openfl-app/src/ApplicationMain.hx @@ -1,63 +1,136 @@ package; import openfl.Lib; +import lime.utils.AssetType; +import lime.tools.Asset; import lime.ui.WindowAttributes; +import openfl.system.System; import openfl.display.Application; import openfl.display.Stage; import openfl.events.Event; +import openfl.events.FullScreenEvent; @:access(lime.app.Application) @:access(lime.system.System) @:access(openfl.display.Stage) @:access(openfl.events.UncaughtErrorEvents) class ApplicationMain { - public static function main() { - @:privateAccess lime.system.System.__registerEntryPoint("src/Main.hx", create); - create(null); - } + public static function main() { + lime.system.System.__registerEntryPoint("src/DocumentClass.hx", create); + create(null); + } - public static function create(config):Void { - try { - trace("Creating application"); - var app = new Application(); + // public static function create(config):Void { + // try { + // trace("Creating minimal application"); + // var app = new Application(); - // Initialize assets via custom loader - try { - Assets.initializeAssets(); - trace("Assets initialized"); - } catch (e:Dynamic) { - trace("Error initializing assets: " + e); - } + // // Initialize assets via macro-generated code + // Assets.initializeAssets(); + // trace("Assets initialized"); - // Minimal metadata - app.meta["name"] = "DSTEngine Demo"; + // // Minimal metadata + // app.meta["name"] = "Debug Application"; - // Simple window - var attributes:WindowAttributes = { - height: 600, - width: 800, - title: "DST Engine Demo" - }; + // // Simple window + // var attributes:WindowAttributes = { + // height: 600, + // width: 800, + // title: "Debug Window" + // }; - app.createWindow(attributes); + // app.createWindow(attributes); + + // // Skip preloader, just call start directly + // start(app.window.stage); - // Start application - start(app.window.stage); - - var result = app.exec(); - lime.system.System.exit(result); - } catch (e:Dynamic) { - trace("Error creating application: " + e); - trace(haxe.CallStack.toString(haxe.CallStack.exceptionStack())); - } - } + // var result = app.exec(); + // lime.system.System.exit(result); + // } catch (e:Dynamic) { + // trace("Error: " + e); + // } + // } - public static function start(stage:Stage):Void { - try { - var main = new Main(); - stage.addChild(main); - } catch (e:Dynamic) { - trace("Error starting application: " + e); - } - } + public static function create(config):Void + { + var app = new Application(); + app.meta["build"] = "1.0.0"; // Replace with actual build number + app.meta["company"] = "Your Company"; // Replace with your company name + app.meta["file"] = "src/Main.hx"; // Path to your main application file + app.meta["name"] = "Your Application"; // Replace with your application title + app.meta["packageName"] = "com.yourcompany.yourapp"; // Replace with your package name + app.meta["version"] = "1.0.0"; // Replace with your application version + // var asset = new Asset(); + // asset.sourcePath = "src/assets"; // Path to your assets + // asset.targetPath = "assets"; // Target path for assets + // asset.type = AssetType.IMAGE; // Type of asset + if (config.hxtelemetry != null) + { + app.meta["hxtelemetry-allocations"] = config.hxtelemetry.allocations; + app.meta["hxtelemetry-host"] = config.hxtelemetry.host; + } + var attributes:WindowAttributes = { + allowHighDPI: true, // Set to true or false as needed + alwaysOnTop: false, // Set to true or false as needed + borderless: false, // Set to true or false as needed + frameRate: 60, // Set your desired frame rate + height: 600, // Set your desired window height + hidden: false, // Set to true or false as needed + maximized: false, // Set to true or false as needed + minimized: false, // Set to true or false as needed + resizable: true, // Set to true or false as needed + title: "Your Application", // Replace with your application title + width: 800, // Set your desired window width + x: 100, // Set your desired x position + y: 100 // Set your desired y position + }; + app.createWindow(attributes); + var preloader = getPreloader(); + app.preloader.onProgress.add(function(loaded, total) + { + @:privateAccess preloader.update(loaded, total); + }); + app.preloader.onComplete.add(function() + { + @:privateAccess preloader.start(); + }); + preloader.onComplete.add(start.bind(app.window.stage)); + app.preloader.load(); + var result = app.exec(); + lime.system.System.exit(result); + } + + public static function start(stage:Stage):Void { + if (stage.__uncaughtErrorEvents.__enabled) { + try { + // Instantiate and add DocumentClass + var documentClass = new DocumentClass(); + Lib.current.addChild(documentClass); + + + // Then dispatch events + stage.dispatchEvent(new Event(Event.RESIZE, false, false)); + if (stage.window.fullscreen) { + stage.dispatchEvent(new FullScreenEvent(FullScreenEvent.FULL_SCREEN, false, false, true, true)); + } + } catch (e:Dynamic) { + stage.__handleError(e); + } + } else { + // Instantiate and add DocumentClass + var documentClass = new DocumentClass(); + Lib.current.addChild(documentClass); + + + // Then dispatch events + stage.dispatchEvent(new Event(Event.RESIZE, false, false)); + if (stage.window.fullscreen) { + stage.dispatchEvent(new FullScreenEvent(FullScreenEvent.FULL_SCREEN, false, false, true, true)); + } + } + } + + public static function getPreloader() { + return new openfl.display.Preloader(); + } } diff --git a/standalone-openfl-app/src/Assets.hx b/standalone-openfl-app/src/Assets.hx index 42321aec..70025a70 100644 --- a/standalone-openfl-app/src/Assets.hx +++ b/standalone-openfl-app/src/Assets.hx @@ -1,261 +1,8 @@ package; -import haxe.io.Path; -import openfl.utils.AssetLibrary; -import openfl.utils.AssetManifest; -import openfl.utils.AssetType; -import openfl.events.Event; -import openfl.events.EventDispatcher; -import sys.FileSystem; -import sys.io.File; -import haxe.crypto.Base64; +class Assets{ -/** - * Custom asset management system that initializes OpenFL's asset system. - * This supplements OpenFL's built-in asset handling. - */ -class Assets { - // Track initialization state - public static var isLoaded:Bool = false; - // Event dispatcher for asset loading events - private static var dispatcher:EventDispatcher = new EventDispatcher(); - - // Potential manifest locations - private static var manifestPaths = [ - "manifest/default.json", - "bin/cpp/manifest/default.json", - "../manifest/default.json" - ]; - - // Event types - public static inline var ASSET_LOADED:String = "assetLoaded"; - public static inline var ASSET_ERROR:String = "assetError"; - - /** - * Initialize the asset system - */ - public static function initializeAssets():Void { - if (isLoaded) return; // Don't load twice - - trace("Initializing asset system..."); - - // First, try to initialize embedded assets if the macro created them - try { - if (Reflect.hasField(macros.AssetMacro, "initEmbeddedAssets")) { - trace("Initializing embedded assets..."); - Reflect.callMethod(macros.AssetMacro, - Reflect.field(macros.AssetMacro, "initEmbeddedAssets"), []); - isLoaded = true; - } - } catch (e:Dynamic) { - trace("No embedded assets available: " + e); - } - - // Then try to load from manifest files - loadFromManifest(); - - if (isLoaded) { - trace("Asset system initialized successfully."); - - // Log available assets - trace("Available assets:"); - for (assetPath in openfl.Assets.list()) { - var type = getAssetTypeString(assetPath); - trace(" - " + assetPath + " (Type: " + type + ")"); - } - } else { - trace("WARNING: Asset system could not be fully initialized."); - } - } - - /** - * Try to load assets from an external manifest file - */ - private static function loadFromManifest():Void { - trace("Checking for asset manifest files..."); - for (path in manifestPaths) { - if (FileSystem.exists(path)) { - try { - trace("Loading asset manifest from: " + path); - var content = File.getContent(path); - var jsonStartPos = 0; - while (jsonStartPos < content.length && content.charAt(jsonStartPos) != '{') { - jsonStartPos++; - } - if (jsonStartPos > 0) { - content = content.substr(jsonStartPos); - } - if (content == null || content.length == 0 || content.charAt(0) != '{') { - trace("Invalid JSON content in manifest file"); - continue; - } - var manifestData = haxe.Json.parse(content); - var manifest = new AssetManifest(); - manifest.name = manifestData.name; - manifest.assets = manifestData.assets; - manifest.rootPath = manifestData.rootPath != null ? manifestData.rootPath : Path.directory(path); - manifest.version = manifestData.version; - manifest.libraryType = manifestData.libraryType; - manifest.libraryArgs = manifestData.libraryArgs; - if (manifest.assets != null && manifest.assets.length > 0) { - trace("Parsed manifest with " + manifest.assets.length + " assets"); - var library = AssetLibrary.fromManifest(manifest); - if (library != null) { - var libraryName = manifest.name != null ? manifest.name : "default"; - if (openfl.Assets.hasLibrary(libraryName)) { - openfl.Assets.unloadLibrary(libraryName); - } - openfl.Assets.registerLibrary(libraryName, library); - trace("Registered asset library: " + libraryName); - isLoaded = true; - dispatcher.dispatchEvent(new Event(ASSET_LOADED)); - return; - } else { - trace("ERROR: Failed to create library from manifest"); - } - } else { - trace("ERROR: No assets found in manifest"); - } - } catch (e:Dynamic) { - trace("Error loading manifest from " + path + ": " + e); - } - } else { - trace("Manifest not found at: " + path); - } - } - dispatcher.dispatchEvent(new Event(ASSET_ERROR)); - } - - /** - * Add event listener for asset events - */ - public static function addEventListener(type:String, listener:Dynamic->Void, - useCapture:Bool = false, priority:Int = 0, - useWeakReference:Bool = false):Void { - dispatcher.addEventListener(type, listener, useCapture, priority, useWeakReference); - } - - /** - * Remove event listener - */ - public static function removeEventListener(type:String, listener:Dynamic->Void, - useCapture:Bool = false):Void { - dispatcher.removeEventListener(type, listener, useCapture); - } - - /** - * Force reload the asset system - */ - public static function reload():Void { - var libraryNames = openfl.Assets.list().map(function(id) { - var parts = id.split(":"); - return parts.length > 1 ? parts[0] : "default"; - }).filter(function(name) { - return name != null && name != ""; - }); - var uniqueNames = new Map(); - for (name in libraryNames) { - uniqueNames.set(name, true); - } - for (name in uniqueNames.keys()) { - if (openfl.Assets.hasLibrary(name)) { - try { - openfl.Assets.unloadLibrary(name); - } catch (e:Dynamic) { - trace("Error unloading library " + name + ": " + e); - } - } - } - - isLoaded = false; - initializeAssets(); - } - - /** - * Helper function to determine asset types by extension - */ - private static function getAssetTypeString(id:String):String { - try { - if (!openfl.Assets.exists(id)) return "unknown"; - var extension = Path.extension(id).toLowerCase(); - return switch(extension) { - case "jpg", "jpeg", "png", "gif", "bmp": "image"; - case "mp3", "ogg", "wav": "sound"; - case "ttf", "otf": "font"; - case "txt", "json", "xml", "csv", "tsv": "text"; - default: "binary"; - } - } catch (e:Dynamic) { - return "unknown"; - } - } - - /** - * Debug the manifest and asset system status - */ - public static function debugManifest():String { - var result = "Asset System Status:\n"; - result += "Initialized: " + isLoaded + "\n\n"; - var hasManifest = false; - for (path in manifestPaths) { - if (FileSystem.exists(path)) { - hasManifest = true; - try { - var content = File.getContent(path); - var jsonStartPos = 0; - while (jsonStartPos < content.length && content.charAt(jsonStartPos) != '{') { - jsonStartPos++; - } - if (jsonStartPos > 0) { - content = content.substr(jsonStartPos); - } - result += "Manifest: " + path + "\n"; - result += "Size: " + content.length + " bytes\n"; - if (content.length > 200) { - result += "Content: " + content.substr(0, 200) + "...\n"; - } else { - result += "Content: " + content + "\n"; - } - var assetCount = "unknown"; - try { - var jsonData = haxe.Json.parse(content); - if (jsonData != null && jsonData.assets != null) { - assetCount = Std.string(jsonData.assets.length); - } - } catch (e:Dynamic) { - assetCount = "Error: " + e; - } - result += "Assets: " + assetCount + "\n"; - } catch (e:Dynamic) { - result += "Error reading manifest " + path + ": " + e + "\n"; - } - } - } - if (!hasManifest) { - result += "No manifest files found.\n"; - } - var libraryNames = []; - try { - for (asset in openfl.Assets.list()) { - var libName = ""; - var colonIndex = asset.indexOf(":"); - if (colonIndex > -1) { - libName = asset.substring(0, colonIndex); - } else { - libName = "default"; - } - if (libraryNames.indexOf(libName) == -1) { - libraryNames.push(libName); - } - } - } catch (e:Dynamic) { - result += "Error getting libraries: " + e + "\n"; - } - result += "\nLibraries: " + libraryNames.join(", ") + "\n"; - result += "Asset count: " + openfl.Assets.list().length; - return result; - } } \ No newline at end of file diff --git a/standalone-openfl-app/src/EmbeddedAssetLibrary.hx b/standalone-openfl-app/src/EmbeddedAssetLibrary.hx deleted file mode 100644 index 449280cc..00000000 --- a/standalone-openfl-app/src/EmbeddedAssetLibrary.hx +++ /dev/null @@ -1,87 +0,0 @@ -package; - -import haxe.io.Bytes; -import openfl.display.BitmapData; -import openfl.media.Sound; -import openfl.utils.AssetLibrary; -import openfl.utils.AssetType; -import openfl.utils.Future; -import openfl.display.Loader; -import openfl.events.Event; -import openfl.utils.ByteArray; - -class EmbeddedAssetLibrary extends AssetLibrary { - private var byteData:Map; - private var texts:Map; - private var images:Map; - private var sounds:Map; - - public function new(byteData:Map, texts:Map, - images:Map, sounds:Map) { - super(); - this.byteData = byteData; - this.texts = texts; - this.images = images; - this.sounds = sounds; - } - - override public function exists(id:String, type:AssetType = null):Bool { - switch (type) { - case AssetType.BINARY: - return byteData.exists(id); - case AssetType.TEXT: - return texts.exists(id); - case AssetType.IMAGE: - return images.exists(id); - case AssetType.SOUND: - return sounds.exists(id); - default: - return byteData.exists(id) || texts.exists(id) || images.exists(id) || sounds.exists(id); - } - } - - override public function getType(id:String):AssetType { - if (byteData.exists(id)) return AssetType.BINARY; - if (texts.exists(id)) return AssetType.TEXT; - if (images.exists(id)) return AssetType.IMAGE; - if (sounds.exists(id)) return AssetType.SOUND; - return null; - } - - override public function getText(id:String):String { - return texts.get(id); - } - - override public function getBytes(id:String):Bytes { - return byteData.get(id); - } - - override public function getBitmapData(id:String):BitmapData { - return images.get(id); - } - - override public function loadBitmapData(id:String):Future { - var future = new Future(); - if (images.exists(id)) { - future.onComplete(images.get(id)); - } else { - loadBitmapDataAsync(id); - } - return future; - } - - private function loadBitmapDataAsync(id:String):Void { - if (byteData.exists(id)) { - var loader = new Loader(); - loader.contentLoaderInfo.addEventListener(Event.COMPLETE, function(e) { - var bitmapData = cast(loader.content, BitmapData); - images.set(id, bitmapData); - }); - loader.loadBytes(ByteArray.fromBytes(byteData.get(id))); - } - } - - override public function getSound(id:String):Sound { - return sounds.get(id); - } -} \ No newline at end of file diff --git a/standalone-openfl-app/src/Main.hx b/standalone-openfl-app/src/Main.hx index 83440455..4e58b05a 100644 --- a/standalone-openfl-app/src/Main.hx +++ b/standalone-openfl-app/src/Main.hx @@ -1,12 +1,8 @@ package; +import openfl.utils.AssetType; import openfl.display.Sprite; -import openfl.events.Event; import openfl.Assets; -import openfl.display.Bitmap; -import openfl.display.BitmapData; -import openfl.text.TextField; -import openfl.text.TextFormat; class Main extends Sprite { public function new() { @@ -16,102 +12,9 @@ class Main extends Sprite { graphics.beginFill(0x3498db, 1); graphics.drawRect(0, 0, 800, 600); graphics.endFill(); - - // Create title - var title = new TextField(); - title.defaultTextFormat = new TextFormat("Arial", 24, 0xFFFFFF, true); - title.text = "OpenFL Asset Test"; - title.width = 400; - title.x = 20; - title.y = 20; - addChild(title); - - // Display info about available assets - displayAssetInfo(); - - // Try to load and display a text asset - loadTextAsset(); - - // Debug manifest content - debugManifestInfo(); - } - - private function displayAssetInfo():Void { - var info = new TextField(); - info.defaultTextFormat = new TextFormat("Arial", 16, 0xFFFFFF); - info.width = 760; - info.height = 300; - info.x = 20; - info.y = 60; - info.multiline = true; - info.wordWrap = true; - - var assetList = openfl.Assets.list(); - info.text = "Available Assets (" + assetList.length + "):\n"; - - for (asset in assetList) { - var extension = asset.substr(asset.lastIndexOf(".") + 1).toLowerCase(); - var typeStr = getAssetTypeFromExtension(extension); - info.text += "• " + asset + " [" + typeStr + "]\n"; - } - - addChild(info); - } - - private function getAssetTypeFromExtension(extension:String):String { - return switch(extension) { - case "jpg", "jpeg", "png", "gif", "bmp": "IMAGE"; - case "mp3", "ogg", "wav": "SOUND"; - case "ttf", "otf": "FONT"; - case "txt", "json", "xml", "csv", "tsv": "TEXT"; - default: "BINARY"; - }; - } - - private function loadTextAsset():Void { - var textDisplay = new TextField(); - textDisplay.defaultTextFormat = new TextFormat("Arial", 14, 0xFFFFFF); - textDisplay.width = 760; - textDisplay.height = 200; - textDisplay.x = 20; - textDisplay.y = 380; - textDisplay.multiline = true; - textDisplay.wordWrap = true; - textDisplay.border = true; - textDisplay.borderColor = 0xFFFFFF; - textDisplay.background = true; - textDisplay.backgroundColor = 0x333333; - - var textPath = "data/img/placeholder.txt"; - - if (Assets.exists(textPath)) { - // Synchronous loading - var content = Assets.getText(textPath); - textDisplay.text = "Loaded text content from '" + textPath + "':\n\n" + content; - } else { - // Try alternative paths - var altPath = "assets/data/img/placeholder.txt"; - if (Assets.exists(altPath)) { - var content = Assets.getText(altPath); - textDisplay.text = "Loaded text content from '" + altPath + "':\n\n" + content; - } else { - textDisplay.text = "Could not find text asset '" + textPath + "' or '" + altPath + "'"; - } - } - - addChild(textDisplay); - } - - private function debugManifestInfo():Void { - var debug = new TextField(); - debug.defaultTextFormat = new TextFormat("Arial", 12, 0xFF0000); - debug.width = 760; - debug.height = 100; - debug.x = 20; - debug.y = 540; - debug.multiline = true; - debug.wordWrap = true; - debug.text = Assets.debugManifest(); - addChild(debug); + + var testAsset = Assets.getText("assets/data/img/placeholder.txt"); + trace(testAsset); + } } diff --git a/standalone-openfl-app/src/ManifestResources.hx b/standalone-openfl-app/src/ManifestResources.hx index 4e85a9b1..25d37b90 100644 --- a/standalone-openfl-app/src/ManifestResources.hx +++ b/standalone-openfl-app/src/ManifestResources.hx @@ -1,15 +1,118 @@ -// filepath: /standalone-openfl-app/standalone-openfl-app/src/ManifestResources.hx package; -class ManifestResources -{ - public static var preloadLibraries:Array = []; - public static var preloadLibraryNames:Array = []; +import haxe.io.Bytes; +import haxe.io.Path; +import lime.utils.AssetBundle; +import lime.utils.AssetLibrary; +import lime.utils.AssetManifest; +import lime.utils.Assets; - public static function init(config:Dynamic):Void - { - // Load assets and resources here - // Example: preloadLibraries.push("path/to/library"); - // Example: preloadLibraryNames.push("LibraryName"); - } -} \ No newline at end of file +#if sys +import sys.FileSystem; +#end + +#if disable_preloader_assets +@:dox(hide) class ManifestResources { + public static var preloadLibraries:Array; + public static var preloadLibraryNames:Array; + public static var rootPath:String; + + public static function init (config:Dynamic):Void { + preloadLibraries = new Array (); + preloadLibraryNames = new Array (); + } +} +#else +@:access(lime.utils.Assets) + + +@:keep @:dox(hide) class ManifestResources { + + + public static var preloadLibraries:Array; + public static var preloadLibraryNames:Array; + public static var rootPath:String; + + + public static function init (config:Dynamic):Void { + + preloadLibraries = new Array (); + preloadLibraryNames = new Array (); + + rootPath = null; + + if (config != null && Reflect.hasField (config, "rootPath")) { + + rootPath = Reflect.field (config, "rootPath"); + + if(!StringTools.endsWith (rootPath, "/")) { + + rootPath += "/"; + + } + + } + + if (rootPath == null) { + + #if (ios || tvos || webassembly) + rootPath = "assets/"; + #elseif android + rootPath = ""; + #elseif (console || sys) + rootPath = lime.system.System.applicationDirectory; + #else + rootPath = "./"; + #end + + } + + #if (openfl && !flash && !display) + + #end + + var data, manifest, library, bundle; + + Assets.libraryPaths["default"] = rootPath + "manifest/default.json"; + + + library = Assets.getLibrary ("default"); + if (library != null) preloadLibraries.push (library); + else preloadLibraryNames.push ("default"); + + + } + + +} + +#if !display +#if flash + +@:keep @:bind @:noCompletion #if display private #end class __ASSET__assets_data_img_placeholder_txt extends null { } +@:keep @:bind @:noCompletion #if display private #end class __ASSET__manifest_default_json extends null { } + + +#elseif (desktop || cpp) + + + + +#else + + + +#end + +#if (openfl && !flash) + +#if html5 + +#else + +#end + +#end +#end + +#end \ No newline at end of file diff --git a/standalone-openfl-app/src/macros/AssetMacro.hx b/standalone-openfl-app/src/macros/AssetMacro.hx index 91a65ed7..ebed5820 100644 --- a/standalone-openfl-app/src/macros/AssetMacro.hx +++ b/standalone-openfl-app/src/macros/AssetMacro.hx @@ -1,264 +1,9 @@ package macros; -import haxe.macro.Context; -import haxe.macro.Expr; -import sys.FileSystem; -import sys.io.File; -import haxe.io.Path; -#if macro -import haxe.Json; -import haxe.crypto.Base64; -import haxe.format.JsonPrinter; -#end +class AssetMacro{ + + public static function buildAssets(){ -class AssetMacro { - public static macro function buildAssets():Array { - var fields = Context.getBuildFields(); - - #if !display - try { - // Define output directories - var targetBuildDir = "bin/cpp"; - var manifestDir = targetBuildDir + "/manifest"; - var assetsOutputDir = targetBuildDir + "/assets"; - - // Create directories if they don't exist - ensureDirectory(manifestDir); - ensureDirectory(assetsOutputDir); - ensureDirectory("manifest"); - - // Add a test placeholder if no assets exist - if (!FileSystem.exists("assets")) { - ensureDirectory("assets/data/img"); - File.saveContent("assets/data/img/placeholder.txt", "This is a placeholder file."); - } - - // Scan for assets and build asset list - var assets = []; - var assetDir = "assets"; - var embeddedAssets = new Map(); - - if (FileSystem.exists(assetDir)) { - scanAssets(assetDir, assets, "", assetsOutputDir, embeddedAssets); - trace('Found ${assets.length} assets in ${assetDir}'); - } else { - trace('WARNING: Assets directory not found: ${assetDir}'); - } - - // Create a default asset if none found - if (assets.length == 0) { - var placeholder = { - path: "assets/data/img/placeholder.txt", - type: "TEXT", - id: "data/img/placeholder.txt" - }; - assets.push(placeholder); - var placeholderContent = "This is a placeholder file."; - embeddedAssets.set(placeholder.id, { - data: Base64.encode(haxe.io.Bytes.ofString(placeholderContent)), - type: "TEXT" - }); - } - - // Create manifest in OpenFL format - var manifest = { - name: "default", - assets: assets.map(function(asset) { - return { - id: asset.id, - path: asset.path, - type: asset.type.toLowerCase() - }; - }), - rootPath: ".", - version: 2, - libraryType: null, - libraryArgs: [] - }; - var manifestJson = haxe.format.JsonPrinter.print(manifest, null, " "); - File.saveContent(manifestDir + "/default.json", manifestJson); - trace('Asset manifest saved to: ' + manifestDir + "/default.json"); - File.saveContent("manifest/default.json", manifestJson); - trace('Asset manifest also saved to: manifest/default.json'); - - // Generate the embedded assets code - if (embeddedAssets.keys().hasNext()) { - var initExprs = []; - initExprs.push(macro var assetLibrary = new CustomAssetLibrary()); - for (id in embeddedAssets.keys()) { - var asset = embeddedAssets.get(id); - if (asset == null) continue; - switch (asset.type) { - case "TEXT": - var dataExpr = macro haxe.crypto.Base64.decode($v{asset.data}).getString(0, haxe.crypto.Base64.decode($v{asset.data}).length); - initExprs.push(macro assetLibrary.registerAsset($v{id}, "text", $dataExpr)); - case "IMAGE": - initExprs.push(macro { - var bytes = haxe.crypto.Base64.decode($v{asset.data}); - assetLibrary.registerAsset($v{id}, "image", bytes); - }); - case "SOUND": - initExprs.push(macro { - var bytes = haxe.crypto.Base64.decode($v{asset.data}); - assetLibrary.registerAsset($v{id}, "sound", bytes); - }); - default: - var dataExpr = macro haxe.crypto.Base64.decode($v{asset.data}); - initExprs.push(macro assetLibrary.registerAsset($v{id}, "binary", $dataExpr)); - } - } - initExprs.push(macro openfl.Assets.registerLibrary("default", assetLibrary)); - fields.push({ - name: "initEmbeddedAssets", - doc: "Initializes embedded assets for the application", - meta: [], - access: [Access.APublic, Access.AStatic], - kind: FieldType.FFun({ - args: [], - expr: macro $b{initExprs}, - params: [], - ret: macro :Void - }), - pos: Context.currentPos() - }); - } - } catch (e:Dynamic) { - trace('ERROR in asset macro: ${e}'); - #if debug - trace(haxe.CallStack.toString(haxe.CallStack.exceptionStack())); - #end - } - #end - - return fields; } - - #if macro - private static function ensureDirectory(dir:String):Void { - if (!FileSystem.exists(dir)) { - try { - var pathParts = dir.split("/"); - var currentPath = ""; - - for (part in pathParts) { - if (part == "") continue; - currentPath += part + "/"; - if (!FileSystem.exists(currentPath)) { - FileSystem.createDirectory(currentPath); - } - } - } catch (e:Dynamic) { - trace('ERROR creating directory ${dir}: ${e}'); - } - } - } - - private static function scanAssets(dir:String, assets:Array, relativePath:String = "", - outputDir:String = null, embeddedAssets:Map):Void { - if (!FileSystem.exists(dir)) return; - - try { - var files = FileSystem.readDirectory(dir); - - for (file in files) { - try { - var path = dir + "/" + file; - var relPath = relativePath == "" ? file : relativePath + "/" + file; - - if (FileSystem.isDirectory(path)) { - // Create the corresponding directory in output - if (outputDir != null) { - ensureDirectory(outputDir + "/" + relPath); - } - - // Recursive scan subdirectories - scanAssets(path, assets, relPath, outputDir, embeddedAssets); - } else { - // Determine asset type based on extension - var extension = Path.extension(file).toLowerCase(); - var type = getAssetType(extension); - - // Skip hidden files and non-asset files - if (file.charAt(0) == "." || type == "UNKNOWN") continue; - - // Copy the file to output directory - if (outputDir != null) { - var outputPath = outputDir + "/" + relPath; - try { - File.copy(path, outputPath); - trace('Copied asset: ${path} to ${outputPath}'); - } catch (e:Dynamic) { - trace('Error copying ${path} to ${outputPath}: ${e}'); - } - } - - // Add to asset list with proper path format - var assetId = relPath.split("\\").join("/"); // Normalize path separators - var assetPath = "assets/" + assetId; - - assets.push({ - path: assetPath, - type: type, - id: assetId - }); - - // Embed the asset content for runtime access - try { - var content = File.getBytes(path); - embeddedAssets.set(assetId, { - data: Base64.encode(content), - type: type - }); - } catch (e:Dynamic) { - trace('Warning: Could not embed asset ${assetId}: ${e}'); - } - - trace('Added asset: ${assetId}'); - } - } catch (innerE:Dynamic) { - trace('Error processing asset ${file}: ${innerE}'); - } - } - } catch (e:Dynamic) { - trace('Error reading directory ${dir}: ${e}'); - } - } - - private static function getAssetType(extension:String):String { - return switch(extension) { - case "jpg", "jpeg", "png", "gif", "bmp": - "IMAGE"; - case "mp3", "ogg", "wav": - "SOUND"; - case "ttf", "otf": - "FONT"; - case "txt", "json", "xml", "csv", "tsv", "frag", "vert", "properties": - "TEXT"; - case "bytes", "bin": - "BINARY"; - default: - "TEXT"; // Default to TEXT for unknown types - } - } - - private static function generateEmbeddedAssetExprs(embeddedAssets:Map):Array { - var exprs:Array = []; - for (id in embeddedAssets.keys()) { - var asset = embeddedAssets.get(id); - if (asset == null) continue; - var dataExpr = macro haxe.crypto.Base64.decode($v{asset.data}); - switch (asset.type) { - case "TEXT": - exprs.push(macro texts.set($v{id}, dataExpr.getString(0, dataExpr.length))); - case "IMAGE": - exprs.push(macro byteData.set($v{id}, dataExpr)); - case "SOUND": - exprs.push(macro byteData.set($v{id}, dataExpr)); - default: - exprs.push(macro byteData.set($v{id}, dataExpr)); - } - } - return exprs; - } - #end + } \ No newline at end of file