diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index 758cd50f..0f3f1efd 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -7,7 +7,7 @@ jobs: build: name: Linux Build permissions: write-all - runs-on: ubuntu-20.04 + runs-on: ubuntu-latest steps: - name: Pulling the source uses: actions/checkout@v2 diff --git a/.github/workflows/macos.yml b/.github/workflows/macos.yml index 9ae13a76..449f82c6 100644 --- a/.github/workflows/macos.yml +++ b/.github/workflows/macos.yml @@ -7,7 +7,7 @@ jobs: build: name: Mac OS Build permissions: write-all - runs-on: macos-latest + runs-on: macos-13 steps: - name: Pulling the new commit uses: actions/checkout@v2 diff --git a/.gitignore b/.gitignore index 59fb2c28..259123b1 100644 --- a/.gitignore +++ b/.gitignore @@ -8,4 +8,5 @@ latest/windows/haxe/ .haxelib/ pages/ docs/doc.xml -mods/Baldi's Basics in Funkin'/ \ No newline at end of file +mods/Baldi's Basics in Funkin'/ +dev-libs/ \ No newline at end of file diff --git a/assets/data/characters/bf.xml b/assets/data/characters/bf.xml index 04e2b3c5..245fbffd 100644 --- a/assets/data/characters/bf.xml +++ b/assets/data/characters/bf.xml @@ -11,4 +11,8 @@ - \ No newline at end of file + + + + + diff --git a/assets/data/notes/Alt Anim Note.hx b/assets/data/notes/Alt Anim Note.hx index 08acea42..b44b1398 100644 --- a/assets/data/notes/Alt Anim Note.hx +++ b/assets/data/notes/Alt Anim Note.hx @@ -1 +1,2 @@ -function onNoteHit(event) if (event.noteType == "Alt Anim Note") event.animSuffix = "-alt"; \ No newline at end of file +function onNoteHit(event) if (event.noteType == "Alt Anim Note") event.animSuffix = "-alt"; +function onPlayerMiss(event) if (event.noteType == "Alt Anim Note") event.animSuffix = "-alt"; \ No newline at end of file diff --git a/assets/data/notes/No Anim Note.hx b/assets/data/notes/No Anim Note.hx index 31eb0c63..206d4f96 100644 --- a/assets/data/notes/No Anim Note.hx +++ b/assets/data/notes/No Anim Note.hx @@ -1 +1,2 @@ -function onNoteHit(event) if (event.noteType == "No Anim Note") event.animCancelled = true; \ No newline at end of file +function onNoteHit(event) if (event.noteType == "No Anim Note") event.animCancelled = true; +function onPlayerMiss(event) if (event.noteType == "No Anim Note") event.animCancelled = true; \ No newline at end of file diff --git a/assets/data/stages/mall.xml b/assets/data/stages/mall.xml index 3552cf27..3565f1be 100644 --- a/assets/data/stages/mall.xml +++ b/assets/data/stages/mall.xml @@ -1,21 +1,21 @@ - + - + - + - - + + + + + + + - - - - - - \ No newline at end of file + diff --git a/commandline/Utils.hx b/commandline/Utils.hx new file mode 100644 index 00000000..20216822 --- /dev/null +++ b/commandline/Utils.hx @@ -0,0 +1,69 @@ +package; + +using StringTools; + +class Utils { + // trace(evaluateArgsCondition("hello && (world || world)", ["hello", "world"])); // true + // trace(evaluateArgsCondition("hello && (!world || world)", ["hello"])); // true + // trace(evaluateArgsCondition("hello && (!world && world)", ["hello", "world"])); // false + public static function evaluateArgsCondition(condition:String, args:Array):Bool { + function evaluateToken(token:String):Bool { + if (token.charAt(0) == '!') { + return !args.contains(token.substr(1)); + } else { + return args.contains(token); + } + } + + condition = condition.replace('&&', '&').replace('||', '|').replace(" ", ""); + + var stack:Array = []; + var i = 0; + + while (i < condition.length) { + var char = condition.charAt(i); + + switch (char) { + case '(': + var j = i; + var balance = 1; + while (balance != 0) { + j++; + if (condition.charAt(j) == '(') balance++; + if (condition.charAt(j) == ')') balance--; + } + var subExpr = condition.substr(i + 1, j - i - 1); + stack.push(evaluateArgsCondition(subExpr, args)); + i = j; + case '&', '|': + stack.push(char); + default: + var token = ""; + while (i < condition.length && condition.charAt(i) != '&' && condition.charAt(i) != '|' && condition.charAt(i) != '(' && condition.charAt(i) != ')') { + token += condition.charAt(i); + i++; + } + stack.push(evaluateToken(token)); + i--; + } + i++; + } + + return evaluate(stack); + } + + public static function evaluate(stack:Array):Bool { + var result = stack.shift(); + while (stack.length > 0) { + var op = stack.shift(); + var next = stack.shift(); + switch(op) { + case '&': + result = result && next; + case '|': + result = result || next; + } + } + return result; + } +} diff --git a/commandline/commands/Compiler.hx b/commandline/commands/Compiler.hx index 08c39f24..671c7ffa 100644 --- a/commandline/commands/Compiler.hx +++ b/commandline/commands/Compiler.hx @@ -13,27 +13,24 @@ class Compiler { public static function testRelease(args:Array) { __runLime(args, ["test", getBuildTarget()]); } - public static function run(args:Array) { __runLime(args, ["run", getBuildTarget()]); } private static function __runLime(args:Array, arg:Array) { + arg.insert(0, "lime"); + arg.insert(0, "run"); for(a in args) arg.push(a); - Sys.command("lime", arg); + Sys.command("haxelib", arg); } public static function getBuildTarget() { return switch(Sys.systemName()) { - case "Windows": - "windows"; - case "Mac": - "macos"; - case "Linux": - "linux"; - case def: - def.toLowerCase(); + case "Windows": "windows"; + case "Mac": "macos"; + case "Linux": "linux"; + case def: def.toLowerCase(); } } } \ No newline at end of file diff --git a/commandline/commands/Update.hx b/commandline/commands/Update.hx index 269b2035..36a790ad 100644 --- a/commandline/commands/Update.hx +++ b/commandline/commands/Update.hx @@ -8,11 +8,9 @@ import sys.FileSystem; class Update { public static function main(args:Array) { - prettyPrint("Preparing installation..."); - var args = ArgParser.parse(args, ["S" => "silent-progress", "silent" => "silent-progress"]); var CHECK_VSTUDIO = !args.existsOption("no-vscheck"); - var REINSTALL_ALL = args.existsOption("all"); + var REINSTALL_ALL = args.existsOption("reinstall"); var SILENT = args.existsOption("silent-progress"); // to prevent messing with currently installed libs @@ -24,44 +22,168 @@ class Update { FileSystem.createDirectory('.haxelib'); } - var libs:Array = []; - var libsXML:Access = new Access(Xml.parse(File.getContent('./libs.xml')).firstElement()); + var libFile = "./libs.xml"; + if(args.existsOption("lib")) { + libFile = args.getOption("lib"); + if(libFile == null) { + Sys.println('Please specify a file with the --lib option as --lib=path/to/libs.xml'); + return; + } + } + if(!FileSystem.exists(libFile)) { + Sys.println('File $libFile does not exist.'); + return; + } + + var events:Array = []; + var libsXML:Access = new Access(Xml.parse(File.getContent(libFile)).firstElement()); + + function handleLib(libNode:Access) { + switch(libNode.name) { + case "lib" | "git": + var lib:Library = { + name: libNode.att.name, + type: libNode.name + }; + if (libNode.has.global) lib.global = libNode.att.global; + switch (lib.type) { + case "lib": + if (libNode.has.version) lib.version = libNode.att.version; + case "git": + if (libNode.has.url) lib.url = libNode.att.url; + if (libNode.has.ref) lib.ref = libNode.att.ref; + } + events.push({ + type: INSTALL, + data: lib + }); + case "cmd": + + events.push({ + type: CMD, + data: { + inLib: libNode.has.inLib ? libNode.att.inLib : null, + lines: { + if(Lambda.count(libNode.nodes.line) > 0) + [ + for(line in libNode.nodes.line) + line.innerData + ]; + else + [ + libNode.has.cmd ? libNode.att.cmd : "echo 'No command specified'" + ]; + } + } + }); + case "print": + events.push({ + type: PRINT, + data: { + text: libNode.innerData, + pretty: libNode.has.pretty && libNode.att.pretty == "true" + } + }); + default: + Sys.println('Unknown library type ${libNode.name}'); + } + } + + var platform = switch(Sys.systemName()) { + case "Windows": "windows"; + case "Mac": "mac"; + case "Linux": "linux"; + case def: def.toLowerCase(); + } + + var defines = args.args.copy(); + defines.push(platform); + if(args.args.length == 0) defines.push("all"); + + function parse(libNode:Access) { + if(libNode.name == "if") { + var cond = libNode.att.cond; + if(!Utils.evaluateArgsCondition(cond, defines)) { + return; + } + + for(child in libNode.elements) { + parse(child); + } + } else { + handleLib(libNode); + } + } for (libNode in libsXML.elements) { - var lib:Library = { - name: libNode.att.name, - type: libNode.name - }; - if (libNode.has.global) lib.global = libNode.att.global; - switch (lib.type) { - case "lib": - if (libNode.has.version) lib.version = libNode.att.version; - case "git": - if (libNode.has.url) lib.url = libNode.att.url; - if (libNode.has.ref) lib.ref = libNode.att.ref; - } - libs.push(lib); + parse(libNode); } var commandSuffix = " --always"; if (SILENT) commandSuffix += " --silent"; - for(lib in libs) { - var globalism:Null = lib.global == "true" ? "--global" : null; - var globalSuffix = globalism != null ? ' $globalism' : ''; - switch(lib.type) { - case "lib": - prettyPrint((lib.global == "true" ? "Globally installing" : "Locally installing") + ' "${lib.name}"...'); - Sys.command('haxelib install ${lib.name} ${lib.version != null ? " " + lib.version : " "}$globalSuffix$commandSuffix'); - case "git": - prettyPrint((lib.global == "true" ? "Globally installing" : "Locally installing") + ' "${lib.name}" from git url "${lib.url}"'); - Sys.command('haxelib git ${lib.name} ${lib.url}${lib.ref != null ? ' ${lib.ref}' : ''}$globalSuffix$commandSuffix'); - default: - prettyPrint('Cannot resolve library of type "${lib.type}"'); + for(event in events) { + switch(event.type) { + case INSTALL: + var lib:Library = event.data; + var globalism:Null = lib.global == "true" ? "--global" : null; + var globalSuffix = globalism != null ? ' $globalism' : ''; + switch(lib.type) { + case "lib": + prettyPrint((lib.global == "true" ? "Globally installing" : "Locally installing") + ' "${lib.name}"...'); + Sys.command('haxelib install ${lib.name} ${lib.version != null ? " " + lib.version : " "}$globalSuffix$commandSuffix'); + case "git": + prettyPrint((lib.global == "true" ? "Globally installing" : "Locally installing") + ' "${lib.name}" from git url "${lib.url}"'); + Sys.command('haxelib git ${lib.name} ${lib.url}${lib.ref != null ? ' ${lib.ref}' : ''}$globalSuffix$commandSuffix'); + default: + prettyPrint('Cannot resolve library of type "${lib.type}"'); + } + case CMD: + var cmd:CmdData = event.data; + var lib = cmd.inLib; + var oldCwd = Sys.getCwd(); + if(lib != null) { + var libPrefix = '.haxelib/$lib'; + if(FileSystem.exists(libPrefix)) { + if(FileSystem.exists(libPrefix + '/.dev')) { // haxelib dev + var devPath = File.getContent(libPrefix + '/.dev'); + if(!FileSystem.exists(devPath)) { + Sys.println('Cannot find dev path $devPath for $lib'); + Sys.setCwd(oldCwd); + continue; + } + Sys.setCwd(devPath); + } else if(FileSystem.exists(libPrefix + '/.current')) { + var version = StringTools.replace(File.getContent(libPrefix + '/.current'), ".", ","); + if(!FileSystem.exists(libPrefix + '/$version')) { + Sys.println('Cannot find version $version of $lib'); + Sys.setCwd(oldCwd); + continue; + } + Sys.setCwd(libPrefix + '/$version'); + } else { + Sys.println('Cannot find .dev or .current file in $libPrefix'); + Sys.setCwd(oldCwd); + continue; + } + } + } + for(line in cmd.lines) { + var line = StringTools.replace(line, "$PLATFORM", platform); + //Sys.println(line); + Sys.command(line); + } + Sys.setCwd(oldCwd); + case PRINT: + var data:PrintData = event.data; + if(data.pretty) + prettyPrint(data.text); + else + Sys.println(data.text); } } - var proc = new Process('haxe --version'); + /*var proc = new Process('haxe --version'); proc.exitCode(true); var haxeVer = proc.stdout.readLine(); if (haxeVer != "4.2.5") { @@ -84,7 +206,7 @@ class Update { break; } } - } + }*/ // vswhere.exe its used to find any visual studio related installations on the system, including full visual studio ide installations, visual studio build tools installations, and other related components - Nex if (CHECK_VSTUDIO && Compiler.getBuildTarget().toLowerCase() == "windows" && new Process('"C:/Program Files (x86)/Microsoft Visual Studio/Installer/vswhere.exe" -property catalog_productDisplayVersion').exitCode(true) == 1) { @@ -142,3 +264,24 @@ typedef Library = { var ?ref:String; var ?url:String; } + +typedef Event = { + var type:EventType; + var data:Dynamic; +} + +typedef CmdData = { + var ?inLib:String; + var lines:Array; +} + +typedef PrintData = { + var text:String; + var ?pretty:Bool; +} + +enum abstract EventType(Int) { + var INSTALL = 0; + var CMD = 1; + var PRINT = 2; +} \ No newline at end of file diff --git a/libs.xml b/libs.xml index f3d27d0f..9f3f5ede 100644 --- a/libs.xml +++ b/libs.xml @@ -1,22 +1,43 @@ - - - + + Preparing installation... - - - + + + - - - - - + + + - - - - - + + + + + + + + + + + + + + + + + + + + Rebuilding Lime... + + + + + cd tools + haxe tools.hxml + cd ..s + + diff --git a/project.xml b/project.xml index 77ae6af6..232f6159 100644 --- a/project.xml +++ b/project.xml @@ -69,7 +69,7 @@ - + diff --git a/setup-dev-branch.xml b/setup-dev-branch.xml new file mode 100644 index 00000000..ed3eb905 --- /dev/null +++ b/setup-dev-branch.xml @@ -0,0 +1,30 @@ + + + + Switching to branch 'time-fix'... + + + + + + Done! Make sure to switch the branch on Codename Engine to 'time-fix' before compiling! + + + + Switching to branch 'dev'... + + + + + + Done! Make sure to switch the branch on Codename Engine to 'main' before compiling! + + + Rebuilding Lime... + + + cd tools + haxe tools.hxml + cd ..s + + diff --git a/setup-dev.xml b/setup-dev.xml new file mode 100644 index 00000000..dc2762ff --- /dev/null +++ b/setup-dev.xml @@ -0,0 +1,90 @@ + + + Setting up dev libs... + + + mkdir dev-libs + + + + + cd dev-libs + git clone https://github.com/FNF-CNE-Devs/openfl openfl + cd .. + haxelib dev openfl dev-libs/openfl + + + + + + cd dev-libs + git clone https://github.com/FNF-CNE-Devs/lime lime + cd .. + haxelib dev lime dev-libs/lime + + + + + + cd tools + haxe tools.hxml + cd ..s + + + + + + cd dev-libs + git clone https://github.com/FNF-CNE-Devs/flixel flixel + cd .. + haxelib dev flixel dev-libs/flixel + + + + + + cd dev-libs + git clone https://github.com/FNF-CNE-Devs/flixel-addons flixel-addons + cd .. + haxelib dev flixel-addons dev-libs/flixel-addons + + + + + + cd dev-libs + git clone https://github.com/FNF-CNE-Devs/hscript-improved hscript-improved + cd .. + haxelib dev hscript-improved dev-libs/hscript-improved + + + + + + cd dev-libs + git clone https://github.com/FNF-CNE-Devs/flxanimate flxanimate + cd .. + haxelib dev flxanimate dev-libs/flxanimate + + + + + + cd dev-libs + git clone https://github.com/FNF-CNE-Devs/hxdiscord_rpc hxdiscord_rpc + cd .. + haxelib dev hxdiscord_rpc dev-libs/hxdiscord_rpc + + + + + + cd dev-libs + git clone https://github.com/FNF-CNE-Devs/away3d away3d + cd .. + haxelib dev away3d dev-libs/away3d + + + + Setup for dev libs complete! + diff --git a/source/funkin/backend/assets/ModsFolderLibrary.hx b/source/funkin/backend/assets/ModsFolderLibrary.hx index be052548..c30b7270 100644 --- a/source/funkin/backend/assets/ModsFolderLibrary.hx +++ b/source/funkin/backend/assets/ModsFolderLibrary.hx @@ -18,7 +18,7 @@ class ModsFolderLibrary extends AssetLibrary implements IModsAssetLibrary { public var folderPath:String; public var modName:String; public var libName:String; - public var useImageCache:Bool = true; + //public var useImageCache:Bool = true; public var prefix = 'assets/'; public function new(folderPath:String, libName:String, ?modName:String) { diff --git a/source/funkin/backend/chart/EventsData.hx b/source/funkin/backend/chart/EventsData.hx index 9527c1b1..630f2269 100644 --- a/source/funkin/backend/chart/EventsData.hx +++ b/source/funkin/backend/chart/EventsData.hx @@ -48,7 +48,7 @@ class EventsData { } ], "Alt Animation Toggle" => [{name: "Enable On Sing Poses", type: TBool, defValue: true}, {name: "Enable On Idle", type: TBool, defValue: true}, {name: "Strumline", type: TStrumLine, defValue: 0}], - "Play Animation" => [{name: "Character", type: TStrumLine, defValue: 0}, {name: "Animation", type: TString, defValue: "animation"}], + "Play Animation" => [{name: "Character", type: TStrumLine, defValue: 0}, {name: "Animation", type: TString, defValue: "animation"}, {name: "Is forced?", type: TBool, defValue: true}], ]; public static var eventsList:Array = defaultEventsList.copy(); diff --git a/source/funkin/backend/chart/FNFLegacyParser.hx b/source/funkin/backend/chart/FNFLegacyParser.hx index 1b10c794..3bd0dfad 100644 --- a/source/funkin/backend/chart/FNFLegacyParser.hx +++ b/source/funkin/backend/chart/FNFLegacyParser.hx @@ -131,7 +131,7 @@ class FNFLegacyParser { if ((swagSection.mustHitSection && strumLine.type == OPPONENT) || (!swagSection.mustHitSection && strumLine.type == PLAYER)) sectionNote[1] += 4; - swagSection.sectionNotes.push(note); + swagSection.sectionNotes.push(sectionNote); } } diff --git a/source/funkin/backend/system/Conductor.hx b/source/funkin/backend/system/Conductor.hx index 21680774..8d4ef85a 100644 --- a/source/funkin/backend/system/Conductor.hx +++ b/source/funkin/backend/system/Conductor.hx @@ -168,7 +168,7 @@ class Conductor // update conductor songPosition = lastSongPos; } else { - songPosition = songPosition + songOffset + elapsed * 1000; + songPosition += songOffset + elapsed * 1000; } } diff --git a/source/funkin/backend/system/Controls.hx b/source/funkin/backend/system/Controls.hx index d1a11142..72cd2c46 100644 --- a/source/funkin/backend/system/Controls.hx +++ b/source/funkin/backend/system/Controls.hx @@ -8,53 +8,6 @@ import flixel.input.actions.FlxActionSet; import flixel.input.gamepad.FlxGamepadInputID; import flixel.input.keyboard.FlxKey; -enum abstract Action(String) to String from String { - var UP = "up"; - var LEFT = "left"; - var RIGHT = "right"; - var DOWN = "down"; - var UP_P = "up-press"; - var LEFT_P = "left-press"; - var RIGHT_P = "right-press"; - var DOWN_P = "down-press"; - var UP_R = "up-release"; - var LEFT_R = "left-release"; - var RIGHT_R = "right-release"; - var DOWN_R = "down-release"; - - - var NOTE_UP = "note-up"; - var NOTE_LEFT = "note-left"; - var NOTE_RIGHT = "note-right"; - var NOTE_DOWN = "note-down"; - var NOTE_UP_P = "note-up-press"; - var NOTE_LEFT_P = "note-left-press"; - var NOTE_RIGHT_P = "note-right-press"; - var NOTE_DOWN_P = "note-down-press"; - var NOTE_UP_R = "note-up-release"; - var NOTE_LEFT_R = "note-left-release"; - var NOTE_RIGHT_R = "note-right-release"; - var NOTE_DOWN_R = "note-down-release"; - - var ACCEPT = "accept"; - var BACK = "back"; - var PAUSE = "pause"; - var RESET = "reset"; - var CHEAT = "cheat"; - var SWITCHMOD = "switchmod"; -} - -enum Device -{ - Keys; - Gamepad(id:Int); -} - -/** - * Since, in many cases multiple actions should use similar keys, we don't want the - * rebinding UI to list every action. ActionBinders are what the user perceives as - * an input so, for instance, they can't set jump-press and jump-release to different keys. - */ enum Control { UP; @@ -69,7 +22,7 @@ enum Control ACCEPT; BACK; PAUSE; - CHEAT; + //CHEAT; SWITCHMOD; } @@ -85,327 +38,128 @@ enum KeyboardScheme * A list of actions that a player would invoke via some input device. * Uses FlxActions to funnel various inputs to a single action. */ +// Macro generated +// A and B are swapped for switch @:noCustomClass +@:nullSafety +@:build(funkin.backend.system.macros.ControlsMacro.build()) class Controls extends FlxActionSet { - var _up = new FlxActionDigital(Action.UP); - var _left = new FlxActionDigital(Action.LEFT); - var _right = new FlxActionDigital(Action.RIGHT); - var _down = new FlxActionDigital(Action.DOWN); - var _upP = new FlxActionDigital(Action.UP_P); - var _leftP = new FlxActionDigital(Action.LEFT_P); - var _rightP = new FlxActionDigital(Action.RIGHT_P); - var _downP = new FlxActionDigital(Action.DOWN_P); - var _upR = new FlxActionDigital(Action.UP_R); - var _leftR = new FlxActionDigital(Action.LEFT_R); - var _rightR = new FlxActionDigital(Action.RIGHT_R); - var _downR = new FlxActionDigital(Action.DOWN_R); - - var _noteUp = new FlxActionDigital(Action.NOTE_UP); - var _noteLeft = new FlxActionDigital(Action.NOTE_LEFT); - var _noteRight = new FlxActionDigital(Action.NOTE_RIGHT); - var _noteDown = new FlxActionDigital(Action.NOTE_DOWN); - var _noteUpP = new FlxActionDigital(Action.NOTE_UP_P); - var _noteLeftP = new FlxActionDigital(Action.NOTE_LEFT_P); - var _noteRightP = new FlxActionDigital(Action.NOTE_RIGHT_P); - var _noteDownP = new FlxActionDigital(Action.NOTE_DOWN_P); - var _noteUpR = new FlxActionDigital(Action.NOTE_UP_R); - var _noteLeftR = new FlxActionDigital(Action.NOTE_LEFT_R); - var _noteRightR = new FlxActionDigital(Action.NOTE_RIGHT_R); - var _noteDownR = new FlxActionDigital(Action.NOTE_DOWN_R); - - var _accept = new FlxActionDigital(Action.ACCEPT); - var _back = new FlxActionDigital(Action.BACK); - var _pause = new FlxActionDigital(Action.PAUSE); - var _reset = new FlxActionDigital(Action.RESET); - var _cheat = new FlxActionDigital(Action.CHEAT); - var _switchMod = new FlxActionDigital(Action.SWITCHMOD); - - #if (haxe >= "4.0.0") - var byName:Map = []; + // Menus + #if !switch + @:rawGamepad([DPAD_UP, LEFT_STICK_DIGITAL_UP]) #else - var byName:Map = new Map(); + @:rawGamepad([DPAD_UP, LEFT_STICK_DIGITAL_UP, RIGHT_STICK_DIGITAL_UP]) #end + @:pressed("up") public var UP(get, set): Bool; + @:justPressed("up") public var UP_P(get, set): Bool; + @:justReleased("up") public var UP_R(get, set): Bool; + + #if !switch + @:rawGamepad([DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT]) + #else + @:rawGamepad([DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT, RIGHT_STICK_DIGITAL_LEFT]) + #end + @:pressed("left") public var LEFT(get, set): Bool; + @:justPressed("left") public var LEFT_P(get, set): Bool; + @:justReleased("left") public var LEFT_R(get, set): Bool; + + #if !switch + @:rawGamepad([DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT]) + #else + @:rawGamepad([DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT, RIGHT_STICK_DIGITAL_RIGHT]) + #end + @:pressed("right") public var RIGHT(get, set): Bool; + @:justPressed("right") public var RIGHT_P(get, set): Bool; + @:justReleased("right") public var RIGHT_R(get, set): Bool; + + #if !switch + @:rawGamepad([DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN]) + #else + @:rawGamepad([DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN, RIGHT_STICK_DIGITAL_DOWN]) + #end + @:pressed("down") public var DOWN(get, set): Bool; + @:justPressed("down") public var DOWN_P(get, set): Bool; + @:justReleased("down") public var DOWN_R(get, set): Bool; + + // Note Controls + + #if !switch + @:rawGamepad([DPAD_UP, LEFT_STICK_DIGITAL_UP]) + #else + @:rawGamepad([DPAD_UP, LEFT_STICK_DIGITAL_UP, RIGHT_STICK_DIGITAL_UP]) + #end + @:pressed("note-up") public var NOTE_UP(get, set): Bool; + @:justPressed("note-up") public var NOTE_UP_P(get, set): Bool; + @:justReleased("note-up") public var NOTE_UP_R(get, set): Bool; + + #if !switch + @:rawGamepad([DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT]) + #else + @:rawGamepad([DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT, RIGHT_STICK_DIGITAL_LEFT]) + #end + @:pressed("note-left") public var NOTE_LEFT(get, set): Bool; + @:justPressed("note-left") public var NOTE_LEFT_P(get, set): Bool; + @:justReleased("note-left") public var NOTE_LEFT_R(get, set): Bool; + + #if !switch + @:rawGamepad([DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT]) + #else + @:rawGamepad([DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT, RIGHT_STICK_DIGITAL_RIGHT]) + #end + @:pressed("note-right") public var NOTE_RIGHT(get, set): Bool; + @:justPressed("note-right") public var NOTE_RIGHT_P(get, set): Bool; + @:justReleased("note-right") public var NOTE_RIGHT_R(get, set): Bool; + + #if !switch + @:rawGamepad([DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN]) + #else + @:rawGamepad([DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN, RIGHT_STICK_DIGITAL_DOWN]) + #end + @:pressed("note-down") public var NOTE_DOWN(get, set): Bool; + @:justPressed("note-down") public var NOTE_DOWN_P(get, set): Bool; + @:justReleased("note-down") public var NOTE_DOWN_R(get, set): Bool; + + @:gamepad([A]) + @:justPressed("accept") public var ACCEPT(get, set): Bool; + @:pressed("accept") public var ACCEPT_HOLD(get, set): Bool; + @:justReleased("accept") public var ACCEPT_R(get, set): Bool; + + @:gamepad([B]) + @:justPressed("back") public var BACK(get, set): Bool; + @:pressed("back") public var BACK_HOLD(get, set): Bool; + @:justReleased("back") public var BACK_R(get, set): Bool; + + @:gamepad([START]) + @:justPressed("pause") public var PAUSE(get, set): Bool; + @:pressed("pause") public var PAUSE_HOLD(get, set): Bool; + @:justReleased("pause") public var PAUSE_R(get, set): Bool; + + @:gamepad([Y]) + @:justPressed("reset") public var RESET(get, set): Bool; + @:pressed("reset") public var RESET_HOLD(get, set): Bool; + @:justReleased("reset") public var RESET_R(get, set): Bool; + + //@:gamepad([]) + //@:justPressed("cheat") public var CHEAT(get, set): Bool; + //@:pressed("cheat") public var CHEAT_HOLD(get, set): Bool; + //@:justReleased("cheat") public var CHEAT_R(get, set): Bool; + + @:gamepad([FlxGamepadInputID.BACK]) // select button + @:justPressed("switchmod") public var SWITCHMOD(get, set): Bool; + @:pressed("switchmod") public var SWITCHMOD_HOLD(get, set): Bool; + @:justReleased("switchmod") public var SWITCHMOD_R(get, set): Bool; + + var byName:Map = []; public var gamepadsAdded:Array = []; - public var keyboardScheme = KeyboardScheme.None; - - public var UP(get, set):Bool; - - inline function get_UP() - return _up.check(); - - inline function set_UP(val) - return @:privateAccess _up._checked = val; - - public var LEFT(get, set):Bool; - - inline function get_LEFT() - return _left.check(); - - inline function set_LEFT(val) - return @:privateAccess _left._checked = val; - - public var RIGHT(get, set):Bool; - - inline function get_RIGHT() - return _right.check(); - - inline function set_RIGHT(val) - return @:privateAccess _right._checked = val; - - public var DOWN(get, set):Bool; - - inline function get_DOWN() - return _down.check(); - - inline function set_DOWN(val) - return @:privateAccess _down._checked = val; - - public var UP_P(get, set):Bool; - - inline function get_UP_P() - return _upP.check(); - - inline function set_UP_P(val) - return @:privateAccess _upP._checked = val; - - public var LEFT_P(get, set):Bool; - - inline function get_LEFT_P() - return _leftP.check(); - - inline function set_LEFT_P(val) - return @:privateAccess _leftP._checked = val; - - public var RIGHT_P(get, set):Bool; - - inline function get_RIGHT_P() - return _rightP.check(); - - inline function set_RIGHT_P(val) - return @:privateAccess _rightP._checked = val; - - public var DOWN_P(get, set):Bool; - - inline function get_DOWN_P() - return _downP.check(); - - inline function set_DOWN_P(val) - return @:privateAccess _downP._checked = val; - - public var UP_R(get, set):Bool; - - inline function get_UP_R() - return _upR.check(); - - inline function set_UP_R(val) - return @:privateAccess _upR._checked = val; - - public var LEFT_R(get, set):Bool; - - inline function get_LEFT_R() - return _leftR.check(); - - inline function set_LEFT_R(val) - return @:privateAccess _leftR._checked = val; - - public var RIGHT_R(get, set):Bool; - - inline function get_RIGHT_R() - return _rightR.check(); - - inline function set_RIGHT_R(val) - return @:privateAccess _rightR._checked = val; - - public var DOWN_R(get, set):Bool; - - inline function get_DOWN_R() - return _downR.check(); - - inline function set_DOWN_R(val) - return @:privateAccess _downR._checked = val; - - public var NOTE_UP(get, set):Bool; - - inline function get_NOTE_UP() - return _noteUp.check(); - - inline function set_NOTE_UP(val) - return @:privateAccess _noteUp._checked = val; - - public var NOTE_LEFT(get, set):Bool; - - inline function get_NOTE_LEFT() - return _noteLeft.check(); - - inline function set_NOTE_LEFT(val) - return @:privateAccess _noteLeft._checked = val; - - public var NOTE_RIGHT(get, set):Bool; - - inline function get_NOTE_RIGHT() - return _noteRight.check(); - - inline function set_NOTE_RIGHT(val) - return @:privateAccess _noteRight._checked = val; - - public var NOTE_DOWN(get, set):Bool; - - inline function get_NOTE_DOWN() - return _noteDown.check(); - - inline function set_NOTE_DOWN(val) - return @:privateAccess _noteDown._checked = val; - - public var NOTE_UP_P(get, set):Bool; - - inline function get_NOTE_UP_P() - return _noteUpP.check(); - - inline function set_NOTE_UP_P(val) - return @:privateAccess _noteUpP._checked = val; - - public var NOTE_LEFT_P(get, set):Bool; - - inline function get_NOTE_LEFT_P() - return _noteLeftP.check(); - - inline function set_NOTE_LEFT_P(val) - return @:privateAccess _noteLeftP._checked = val; - - public var NOTE_RIGHT_P(get, set):Bool; - - inline function get_NOTE_RIGHT_P() - return _noteRightP.check(); - - inline function set_NOTE_RIGHT_P(val) - return @:privateAccess _noteRightP._checked = val; - - public var NOTE_DOWN_P(get, set):Bool; - - inline function get_NOTE_DOWN_P() - return _noteDownP.check(); - - inline function set_NOTE_DOWN_P(val) - return @:privateAccess _noteDownP._checked = val; - - public var NOTE_UP_R(get, set):Bool; - - inline function get_NOTE_UP_R() - return _noteUpR.check(); - - inline function set_NOTE_UP_R(val) - return @:privateAccess _noteUpR._checked = val; - - public var NOTE_LEFT_R(get, set):Bool; - - inline function get_NOTE_LEFT_R() - return _noteLeftR.check(); - - inline function set_NOTE_LEFT_R(val) - return @:privateAccess _noteLeftR._checked = val; - - public var NOTE_RIGHT_R(get, set):Bool; - - inline function get_NOTE_RIGHT_R() - return _noteRightR.check(); - - inline function set_NOTE_RIGHT_R(val) - return @:privateAccess _noteRightR._checked = val; - - public var NOTE_DOWN_R(get, set):Bool; - - inline function get_NOTE_DOWN_R() - return _noteDownR.check(); - - inline function set_NOTE_DOWN_R(val) - return @:privateAccess _noteDownR._checked = val; - - public var ACCEPT(get, set):Bool; - - inline function get_ACCEPT() - return _accept.check(); - - inline function set_ACCEPT(val) - return @:privateAccess _accept._checked = val; - - public var BACK(get, set):Bool; - - inline function get_BACK() - return _back.check(); - - inline function set_BACK(val) - return @:privateAccess _back._checked = val; - - public var PAUSE(get, set):Bool; - - inline function get_PAUSE() - return _pause.check(); - - inline function set_PAUSE(val) - return @:privateAccess _pause._checked = val; - - public var RESET(get, set):Bool; - - inline function get_RESET() - return _reset.check(); - - inline function set_RESET(val) - return @:privateAccess _reset._checked = val; - - public var CHEAT(get, set):Bool; - - inline function get_CHEAT() - return _cheat.check(); - - inline function set_CHEAT(val) - return @:privateAccess _cheat._checked = val; - - public var SWITCHMOD(get, set):Bool; - - inline function get_SWITCHMOD() - return _switchMod.check(); - - inline function set_SWITCHMOD(val) - return @:privateAccess _switchMod._checked = val; + public var keyboardScheme:KeyboardScheme = None; public function new(name, scheme = None) { super(name); - add(_up); - add(_left); - add(_right); - add(_down); - add(_upP); - add(_leftP); - add(_rightP); - add(_downP); - add(_upR); - add(_leftR); - add(_rightR); - add(_downR); - - add(_noteUp); - add(_noteLeft); - add(_noteRight); - add(_noteDown); - add(_noteUpP); - add(_noteLeftP); - add(_noteRightP); - add(_noteDownP); - add(_noteUpR); - add(_noteLeftR); - add(_noteRightR); - add(_noteDownR); - - add(_accept); - add(_back); - add(_pause); - add(_reset); - add(_cheat); - add(_switchMod); + macro_addKeysToActions(); for (action in digitalActions) byName[action.name] = action; @@ -413,224 +167,56 @@ class Controls extends FlxActionSet setKeyboardScheme(scheme, false); } - override function update() + public function getKeyName(control:Control, idx:Int = 0):String { - super.update(); - } - - // inline - public function checkByName(name:Action):Bool - { - #if debug - if (!byName.exists(name)) - throw 'Invalid name: $name'; - #end - return byName[name].check(); - } - - public function getDialogueName(action:FlxActionDigital):String - { - var input = action.inputs[0]; + var action = macro_getActionFromControl(control); + var input = action.inputs[idx]; return switch input.device { - case KEYBOARD: return '[${(input.inputID : FlxKey)}]'; - case GAMEPAD: return '(${(input.inputID : FlxGamepadInputID)})'; + case KEYBOARD: return '${(input.inputID : FlxKey)}'; + case GAMEPAD: return '${(input.inputID : FlxGamepadInputID)}'; case device: throw 'unhandled device: $device'; } } - public function getDialogueNameFromToken(token:String):String - { - return getDialogueName(getActionFromControl(Control.createByName(token.toUpperCase()))); - } - - function getActionFromControl(control:Control):FlxActionDigital - { - return switch (control) - { - case UP: _up; - case DOWN: _down; - case LEFT: _left; - case RIGHT: _right; - case NOTE_UP: _noteUp; - case NOTE_DOWN: _noteDown; - case NOTE_LEFT: _noteLeft; - case NOTE_RIGHT: _noteRight; - case ACCEPT: _accept; - case BACK: _back; - case PAUSE: _pause; - case RESET: _reset; - case CHEAT: _cheat; - case SWITCHMOD: _switchMod; - } - } - - static function init():Void - { - var actions = new FlxActionManager(); - FlxG.inputs.add(actions); - } - - /** - * Calls a function passing each action bound by the specified control - * @param control - * @param func - * @return ->Void) - */ - function forEachBound(control:Control, func:FlxActionDigital->FlxInputState->Void) - { - switch (control) - { - case NOTE_UP: - func(_noteUp, PRESSED); - func(_noteUpP, JUST_PRESSED); - func(_noteUpR, JUST_RELEASED); - case NOTE_LEFT: - func(_noteLeft, PRESSED); - func(_noteLeftP, JUST_PRESSED); - func(_noteLeftR, JUST_RELEASED); - case NOTE_RIGHT: - func(_noteRight, PRESSED); - func(_noteRightP, JUST_PRESSED); - func(_noteRightR, JUST_RELEASED); - case NOTE_DOWN: - func(_noteDown, PRESSED); - func(_noteDownP, JUST_PRESSED); - func(_noteDownR, JUST_RELEASED); - case UP: - func(_up, PRESSED); - func(_upP, JUST_PRESSED); - func(_upR, JUST_RELEASED); - case LEFT: - func(_left, PRESSED); - func(_leftP, JUST_PRESSED); - func(_leftR, JUST_RELEASED); - case RIGHT: - func(_right, PRESSED); - func(_rightP, JUST_PRESSED); - func(_rightR, JUST_RELEASED); - case DOWN: - func(_down, PRESSED); - func(_downP, JUST_PRESSED); - func(_downR, JUST_RELEASED); - case ACCEPT: - func(_accept, JUST_PRESSED); - case BACK: - func(_back, JUST_PRESSED); - case PAUSE: - func(_pause, JUST_PRESSED); - case RESET: - func(_reset, JUST_PRESSED); - case CHEAT: - func(_cheat, JUST_PRESSED); - case SWITCHMOD: - func(_switchMod, JUST_PRESSED); - } - } - - public function replaceBinding(control:Control, device:Device, ?toAdd:Int, ?toRemove:Int) + public function replaceBindingKeyboard(control:Control, ?toAdd:Int, ?toRemove:Int) { if (toAdd == toRemove) return; - switch (device) - { - case Keys: - if (toRemove != null) - unbindKeys(control, [toRemove]); - if (toAdd != null) - bindKeys(control, [toAdd]); - - case Gamepad(id): - if (toRemove != null) - unbindButtons(control, id, [toRemove]); - if (toAdd != null) - bindButtons(control, id, [toAdd]); - } + if (toRemove != null) + unbindKeys(control, [toRemove]); + if (toAdd != null) + bindKeys(control, [toAdd]); } - public function copyFrom(controls:Controls, ?device:Device) + public function replaceBindingGamepad(control:Control, deviceID:Int, ?toAdd:Int, ?toRemove:Int) { - #if (haxe >= "4.0.0") - for (name => action in controls.byName) - { - for (input in action.inputs) - { - if (device == null || isDevice(input, device)) - byName[name].add(cast input); - } - } - #else - for (name in controls.byName.keys()) - { - var action = controls.byName[name]; - for (input in action.inputs) - { - if (device == null || isDevice(input, device)) - byName[name].add(cast input); - } - } - #end + if (toAdd == toRemove) + return; - switch (device) - { - case null: - // add all - for (gamepad in controls.gamepadsAdded) - gamepadsAdded.pushOnce(gamepad); - - mergeKeyboardScheme(controls.keyboardScheme); - - case Gamepad(id): - gamepadsAdded.push(id); - case Keys: - mergeKeyboardScheme(controls.keyboardScheme); - } - } - - inline public function copyTo(controls:Controls, ?device:Device) - { - controls.copyFrom(this, device); - } - - function mergeKeyboardScheme(scheme:KeyboardScheme):Void - { - if (scheme != None) - { - switch (keyboardScheme) - { - case None: - keyboardScheme = scheme; - default: - keyboardScheme = Custom; - } - } + if (toRemove != null) + unbindButtons(control, deviceID, [toRemove]); + if (toAdd != null) + bindButtons(control, deviceID, [toAdd]); } /** * Sets all actions that pertain to the binder to trigger when the supplied keys are used. * If binder is a literal you can inline this */ - public function bindKeys(control:Control, keys:Array) + public inline function bindKeys(control:Control, keys:Array) { - #if (haxe >= "4.0.0") - inline forEachBound(control, (action, state) -> addKeys(action, keys, state)); - #else - forEachBound(control, function(action, state) addKeys(action, keys, state)); - #end + macro_forEachBound(control, (action, state) -> addKeys(action, keys, state)); } /** * Sets all actions that pertain to the binder to trigger when the supplied keys are used. * If binder is a literal you can inline this */ - public function unbindKeys(control:Control, keys:Array) + public inline function unbindKeys(control:Control, keys:Array) { - #if (haxe >= "4.0.0") - inline forEachBound(control, (action, _) -> removeKeys(action, keys)); - #else - forEachBound(control, function(action, _) removeKeys(action, keys)); - #end + macro_forEachBound(control, (action, _) -> removeKeys(action, keys)); } inline static function addKeys(action:FlxActionDigital, keys:Array, state:FlxInputState) @@ -657,53 +243,7 @@ class Controls extends FlxActionSet keyboardScheme = scheme; - switch (scheme) - { - case Solo: - inline bindKeys(Control.UP, Options.SOLO_UP); - inline bindKeys(Control.DOWN, Options.SOLO_DOWN); - inline bindKeys(Control.LEFT, Options.SOLO_LEFT); - inline bindKeys(Control.RIGHT, Options.SOLO_RIGHT); - inline bindKeys(Control.NOTE_UP, Options.SOLO_NOTE_UP); - inline bindKeys(Control.NOTE_DOWN, Options.SOLO_NOTE_DOWN); - inline bindKeys(Control.NOTE_LEFT, Options.SOLO_NOTE_LEFT); - inline bindKeys(Control.NOTE_RIGHT, Options.SOLO_NOTE_RIGHT); - inline bindKeys(Control.ACCEPT, Options.SOLO_ACCEPT); - inline bindKeys(Control.BACK, Options.SOLO_BACK); - inline bindKeys(Control.PAUSE, Options.SOLO_PAUSE); - inline bindKeys(Control.RESET, Options.SOLO_RESET); - inline bindKeys(Control.SWITCHMOD, Options.SOLO_SWITCHMOD); - case Duo(true): - inline bindKeys(Control.UP, Options.P1_UP); - inline bindKeys(Control.DOWN, Options.P1_DOWN); - inline bindKeys(Control.LEFT, Options.P1_LEFT); - inline bindKeys(Control.RIGHT, Options.P1_RIGHT); - inline bindKeys(Control.NOTE_UP, Options.P1_NOTE_UP); - inline bindKeys(Control.NOTE_DOWN, Options.P1_NOTE_DOWN); - inline bindKeys(Control.NOTE_LEFT, Options.P1_NOTE_LEFT); - inline bindKeys(Control.NOTE_RIGHT, Options.P1_NOTE_RIGHT); - inline bindKeys(Control.ACCEPT, Options.P1_ACCEPT); - inline bindKeys(Control.BACK, Options.P1_BACK); - inline bindKeys(Control.PAUSE, Options.P1_PAUSE); - inline bindKeys(Control.RESET, Options.P1_RESET); - inline bindKeys(Control.SWITCHMOD, Options.P1_SWITCHMOD); - case Duo(false): - inline bindKeys(Control.UP, Options.P2_UP); - inline bindKeys(Control.DOWN, Options.P2_DOWN); - inline bindKeys(Control.LEFT, Options.P2_LEFT); - inline bindKeys(Control.RIGHT, Options.P2_RIGHT); - inline bindKeys(Control.NOTE_UP, Options.P2_NOTE_UP); - inline bindKeys(Control.NOTE_DOWN, Options.P2_NOTE_DOWN); - inline bindKeys(Control.NOTE_LEFT, Options.P2_NOTE_LEFT); - inline bindKeys(Control.NOTE_RIGHT, Options.P2_NOTE_RIGHT); - inline bindKeys(Control.ACCEPT, Options.P2_ACCEPT); - inline bindKeys(Control.BACK, Options.P2_BACK); - inline bindKeys(Control.PAUSE, Options.P2_PAUSE); - inline bindKeys(Control.RESET, Options.P2_RESET); - inline bindKeys(Control.SWITCHMOD, Options.P2_SWITCHMOD); - case None: // nothing - case Custom: // nothing - } + macro_bindControls(scheme); } function removeKeyboard() @@ -720,30 +260,12 @@ class Controls extends FlxActionSet } } - public function addGamepad(id:Int, ?buttonMap:Map>):Void + public function addGamepad(id:Int, buttonMap:Map>):Void { gamepadsAdded.push(id); - #if (haxe >= "4.0.0") for (control => buttons in buttonMap) - inline bindButtons(control, id, buttons); - #else - for (control in buttonMap.keys()) - bindButtons(control, id, buttonMap[control]); - #end - } - - inline function addGamepadLiteral(id:Int, ?buttonMap:Map>):Void - { - gamepadsAdded.push(id); - - #if (haxe >= "4.0.0") - for (control => buttons in buttonMap) - inline bindButtons(control, id, buttons); - #else - for (control in buttonMap.keys()) - bindButtons(control, id, buttonMap[control]); - #end + bindButtons(control, id, buttons); } public function removeGamepad(deviceID:Int = FlxInputDeviceID.ALL):Void @@ -754,7 +276,7 @@ class Controls extends FlxActionSet while (i-- > 0) { var input = action.inputs[i]; - if (input.device == GAMEPAD && (deviceID == FlxInputDeviceID.ALL || input.deviceID == deviceID)) + if (isGamepad(input, deviceID)) action.remove(input); } } @@ -762,60 +284,22 @@ class Controls extends FlxActionSet gamepadsAdded.remove(deviceID); } - public function addDefaultGamepad(id):Void + /** + * Sets all actions that pertain to the binder to trigger when the supplied keys are used. + * If binder is a literal you can inline this + */ + public inline function bindButtons(control:Control, id, buttons) { - #if !switch - addGamepadLiteral(id, [ - Control.ACCEPT => [A], - Control.BACK => [B], - Control.UP => [DPAD_UP, LEFT_STICK_DIGITAL_UP], - Control.DOWN => [DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN], - Control.LEFT => [DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT], - Control.RIGHT => [DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT], - Control.PAUSE => [START], - Control.RESET => [Y] - ]); - #else - addGamepadLiteral(id, [ - //Swap A and B for switch - Control.ACCEPT => [B], - Control.BACK => [A], - Control.UP => [DPAD_UP, LEFT_STICK_DIGITAL_UP, RIGHT_STICK_DIGITAL_UP], - Control.DOWN => [DPAD_DOWN, LEFT_STICK_DIGITAL_DOWN, RIGHT_STICK_DIGITAL_DOWN], - Control.LEFT => [DPAD_LEFT, LEFT_STICK_DIGITAL_LEFT, RIGHT_STICK_DIGITAL_LEFT], - Control.RIGHT => [DPAD_RIGHT, LEFT_STICK_DIGITAL_RIGHT, RIGHT_STICK_DIGITAL_RIGHT], - Control.PAUSE => [START], - //Swap Y and X for switch - Control.RESET => [Y], - Control.CHEAT => [X] - ]); - #end + macro_forEachBound(control, (action, state) -> addButtons(action, buttons, state, id)); } /** * Sets all actions that pertain to the binder to trigger when the supplied keys are used. * If binder is a literal you can inline this */ - public function bindButtons(control:Control, id, buttons) + public inline function unbindButtons(control:Control, gamepadID:Int, buttons) { - #if (haxe >= "4.0.0") - inline forEachBound(control, (action, state) -> addButtons(action, buttons, state, id)); - #else - forEachBound(control, function(action, state) addButtons(action, buttons, state, id)); - #end - } - - /** - * Sets all actions that pertain to the binder to trigger when the supplied keys are used. - * If binder is a literal you can inline this - */ - public function unbindButtons(control:Control, gamepadID:Int, buttons) - { - #if (haxe >= "4.0.0") - inline forEachBound(control, (action, _) -> removeButtons(action, gamepadID, buttons)); - #else - forEachBound(control, function(action, _) removeButtons(action, gamepadID, buttons)); - #end + macro_forEachBound(control, (action, _) -> removeButtons(action, gamepadID, buttons)); } inline static function addButtons(action:FlxActionDigital, buttons:Array, state, id) @@ -835,49 +319,6 @@ class Controls extends FlxActionSet } } - public function getInputsFor(control:Control, device:Device, ?list:Array):Array - { - if (list == null) - list = []; - - switch (device) - { - case Keys: - for (input in getActionFromControl(control).inputs) - { - if (input.device == KEYBOARD) - list.push(input.inputID); - } - case Gamepad(id): - for (input in getActionFromControl(control).inputs) - { - if (input.deviceID == id) - list.push(input.inputID); - } - } - return list; - } - - public function removeDevice(device:Device) - { - switch (device) - { - case Keys: - setKeyboardScheme(None); - case Gamepad(id): - removeGamepad(id); - } - } - - static function isDevice(input:FlxActionInput, device:Device) - { - return switch device - { - case Keys: input.device == KEYBOARD; - case Gamepad(id): isGamepad(input, id); - } - } - inline static function isGamepad(input:FlxActionInput, deviceID:Int) { return input.device == GAMEPAD && (deviceID == FlxInputDeviceID.ALL || input.deviceID == deviceID); diff --git a/source/funkin/backend/system/MainState.hx b/source/funkin/backend/system/MainState.hx index 32a75569..adc5ae00 100644 --- a/source/funkin/backend/system/MainState.hx +++ b/source/funkin/backend/system/MainState.hx @@ -66,9 +66,6 @@ class MainState extends FlxState { betaWarningShown = true; } - #if sys - sys.FileSystem.createDirectory('./.temp/'); - #if windows new funkin.backend.utils.native.HiddenProcess("attrib +h .temp"); #end - #end + CoolUtil.safeAddAttributes('./.temp/', NativeAPI.FileAttribute.HIDDEN); } } \ No newline at end of file diff --git a/source/funkin/backend/system/framerate/FramerateCounter.hx b/source/funkin/backend/system/framerate/FramerateCounter.hx index 0b3ed07b..e07a2e02 100644 --- a/source/funkin/backend/system/framerate/FramerateCounter.hx +++ b/source/funkin/backend/system/framerate/FramerateCounter.hx @@ -1,17 +1,28 @@ package funkin.backend.system.framerate; +import haxe.ds.Vector; import openfl.display.Sprite; import openfl.text.TextField; import openfl.text.TextFormat; +inline final FRAME_TIME_HISTORY = 20; + class FramerateCounter extends Sprite { public var fpsNum:TextField; public var fpsLabel:TextField; - public var lastFPS:Float = 0; + + public var fpsHistoryIndex:Int = 0; + public var fpsHistory:Vector; public function new() { super(); + fpsHistory = new Vector(FRAME_TIME_HISTORY); + // Initialize to 60 FPS, so that the initial estimation until we get enough data is always reasonable. + for(i in 0...FRAME_TIME_HISTORY) { + fpsHistory[i] = 1000.0 / 60.0; + } + fpsNum = new TextField(); fpsLabel = new TextField(); @@ -30,8 +41,20 @@ class FramerateCounter extends Sprite { if (alpha <= 0.05) return; super.__enterFrame(t); - lastFPS = CoolUtil.fpsLerp(lastFPS, FlxG.elapsed == 0 ? 0 : (1 / FlxG.elapsed), 0.25); - fpsNum.text = Std.string(Math.floor(lastFPS)); + // todo use gpu time + fpsHistory[fpsHistoryIndex] = FlxG.elapsed * 1000; + fpsHistoryIndex = (fpsHistoryIndex + 1) % FRAME_TIME_HISTORY; + + // Calculate average CPU time. + // Code based on Godot's FPS counter. + var cpuTime = 0.0; + for(i in 0...FRAME_TIME_HISTORY) { + cpuTime += fpsHistory[i]; + } + cpuTime /= FRAME_TIME_HISTORY; + cpuTime = Math.max(0.01, cpuTime); // Prevent unrealistically low values. + + fpsNum.text = Std.string(Math.floor(1000.0 / cpuTime)); fpsLabel.x = fpsNum.x + fpsNum.width; fpsLabel.y = (fpsNum.y + fpsNum.height) - fpsLabel.height; } diff --git a/source/funkin/backend/system/macros/BuildInfo.hx b/source/funkin/backend/system/macros/BuildInfo.hx new file mode 100644 index 00000000..f86d67e2 --- /dev/null +++ b/source/funkin/backend/system/macros/BuildInfo.hx @@ -0,0 +1,43 @@ +package funkin.backend.system.macros; + +using StringTools; + +#if macro +class BuildInfo { + public static function printBuildInfo() { + var haxeVersion = haxe.macro.Context.definedValue("haxe"); + Sys.println('[ BUILD INFO ]'); + Sys.println('Haxe Version: ${haxeVersion}'); + try { + var lastBuiltWith:Null = null; + var compiling = #if final "final" #elseif debug "debug" #else "release" #end; + var target = #if windows "windows" #elseif mac "macos" #elseif linux "linux" #elseif android "android" #elseif ios "ios" #elseif html5 "html5" #else "" #end; + if(target == "") throw "Unknown target"; + var exportPath = Sys.getCwd() + "/export/" + compiling + "/" + target + "/"; + exportPath += "obj/Options.txt"; + + var options = sys.io.File.getContent(exportPath); + for(option in options.split("\n")) { + if(option.startsWith("haxe=")) { + lastBuiltWith = option.substr(5); + break; + } + } + + if(lastBuiltWith != null && lastBuiltWith != haxeVersion) + Sys.println('Last Built With Haxe: ${lastBuiltWith} [!!!! MAKE SURE IF YOU SWITCHED VERSIONS YOU DELETE EXPORT FOLDERS !!!!]'); + } catch(e) {} + Sys.println('Target Platform: ${ + #if windows "Windows" + #elseif mac "Mac" + #elseif linux "Linux" + #elseif android "Android" + #elseif ios "iOS" + #else "Unknown" + #end + }'); + Sys.println('Build Date: ${Date.now().toString()}'); + Sys.println(''); + } +} +#end \ No newline at end of file diff --git a/source/funkin/backend/system/macros/ControlsMacro.macro.hx b/source/funkin/backend/system/macros/ControlsMacro.macro.hx new file mode 100644 index 00000000..49cb0a65 --- /dev/null +++ b/source/funkin/backend/system/macros/ControlsMacro.macro.hx @@ -0,0 +1,369 @@ +package funkin.backend.system.macros; + + +import haxe.macro.Context; +import haxe.macro.Expr; + +using StringTools; + +using haxe.macro.Tools; + + +// Macro made by Ne_Eo +class ControlsMacro +{ + static var _allControls: Array = null; + static var _allInternalControls: Array = null; + static var _currentControls: Map> = null; + static var _currentGamepadControls: Map = null; + static var _keySet: Map = null; + static var _internalMap: Map = null; + + public static macro function build(): Array + { + var fields = Context.getBuildFields(); + var clRef = Context.getLocalClass(); + if (clRef == null) + return fields; + var cl = clRef.get(); + + _allControls = []; + _allInternalControls = []; + _currentControls = []; + _currentGamepadControls = []; + _keySet = []; + _internalMap = []; + var fields = Context.getBuildFields(); + for (field in fields.copy()) + { + switch (field.kind) + { + case FProp(g, s, t, e): + var controlFields = handleControl(field, g, s, t, e); + for (field in controlFields) + if (field != null) + fields.push(field); + default: + } + } + + // Public fields + fields.push({ + name: "addDefaultGamepad", + access: [APublic], + kind: FFun({ + ret: macro : Void, + params: [], + expr: generateGamepadCode(), + args: [{name: "id", type: macro : Int}] + }), + pos: Context.currentPos(), + doc: null, + meta: [] + }); + + // Private fields, are prefixed with macro_, for readability + fields.push({ + name: "macro_addKeysToActions", + access: [APublic, AInline], + kind: FFun({ + ret: macro : Void, + params: [], + expr: macro $b{_allInternalControls.map((s) -> macro add($i{s}))}, + args: [] + }), + pos: Context.currentPos(), + doc: null, + meta: [] + }); + + function buildBindControl(s:String, prefix:String) { + var prefixxed = prefix + s; + + return macro bindKeys(Control.$s, Options.$prefixxed); + } + + fields.push({ + name: "macro_bindControls", + access: [], + kind: FFun({ + ret: macro : Void, + params: [], + expr: macro switch(keyScheme) { + case Solo: + $a{_allControls.map(buildBindControl.bind(_, "SOLO_"))}; + case Duo(true): + $a{_allControls.map(buildBindControl.bind(_, "P1_"))}; + case Duo(false): + $a{_allControls.map(buildBindControl.bind(_, "P2_"))}; + case None: // nothing + case Custom: // nothing + }, + args: [{ + name: "keyScheme", + type: macro : funkin.backend.system.Controls.KeyboardScheme + }] + }), + pos: Context.currentPos(), + doc: null, + meta: [] + }); + + fields.push({ + name: "macro_forEachBound", + access: [], + kind: FFun({ + ret: macro : Void, + params: [], + expr: generateForEachBoundCode(macro control), + args: [ + { + name: "control", + type: macro : Control + }, + { + name: "func", + type: macro : FlxActionDigital -> FlxInputState -> Void + } + ] + }), + pos: Context.currentPos(), + doc: null, + meta: [] + }); + + fields.push({ + name: "macro_getActionFromControl", + access: [APrivate], + kind: FFun({ + ret: macro : FlxActionDigital, + params: [], + expr: generateGetActionFromControlCode(macro control), + args: [{ + name: "control", + type: macro : Control + }] + }), + pos: Context.currentPos(), + doc: null, + meta: [] + }); + + // for (field in fields) + // trace(new haxe.macro.Printer().printField(field)); + + _allControls = null; + _allInternalControls = null; + _currentControls = null; + _currentGamepadControls = null; + _keySet = null; + _internalMap = null; + + return fields; + } + + static function generateSwitchCase(expr:Expr, cases:Array, defaultCase:Expr): Expr + { + return { + expr: ESwitch(expr, cases, defaultCase), + pos: Context.currentPos() + } + } + + static function generateGetActionFromControlCode(value:Expr): Expr + { + return macro return ${generateSwitchCase(value, [ + for (short => internal in _internalMap) + { + values: [macro Control.$short], + expr: macro $i{internal} + } + ], macro null)}; + } + + static function generateForEachBoundCode(value:Expr): Expr + { + return generateSwitchCase(value, [ + for (field => code in _currentControls) + { + values: [macro Control.$field], + expr: macro $b{code} + } + ], macro {}); + } + + static function generateGamepadCode(): Expr + { + var map: Array = []; + for (name in _allControls) + { + var expr = _currentGamepadControls.get(name); + if(expr == null) continue; + map.push(macro @:pos(expr.pos) Control.$name => ${expr}); + } + + return macro addGamepad(id, $a{map}); + } + + static function extractString(e: Expr): String + { + switch (e.expr) + { + case EConst(CString(s)): + return s; + default: + Context.error("Expected a string", e.pos); + throw "Expected a String"; + } + } + + static function camelCase(s: String): String + { + s = s.split("_").map((s) -> + { + return s.charAt(0).toUpperCase() + s.substr(1).toLowerCase(); + }).join(""); + + return s.charAt(0).toLowerCase() + s.substr(1); + } + + static function swapAB(e: Expr): Expr + { + return switch (e.expr) + { + case EConst(CIdent('A')): macro B; + case EConst(CIdent('B')): macro A; + default: e.map(swapAB); + } + } + + static function handleControl(field: Field, get: String, set: String, _: ComplexType, e: Expr): Array + { + var name = field.name; + var shortName = name; + var type = ""; + if (shortName.endsWith(type = "_P")) + shortName = shortName.substr(0, shortName.length - 2); + else if (shortName.endsWith(type = "_R")) + shortName = shortName.substr(0, shortName.length - 2); + else if (shortName.endsWith(type = "_H")) + shortName = shortName.substr(0, shortName.length - 2); + else if (shortName.endsWith(type = "_HOLD")) + shortName = shortName.substr(0, shortName.length - 5); + else + type = ""; + + var internalName = "_" + camelCase(shortName); + var internalNameNoType = internalName; + if (type != "") + internalName += type.substr(1); + + var keyset: Null = null; + var expr: Expr = null; + var metasToRemove = []; + for (meta in field.meta) + { + var shouldRemove = true; + switch (meta.name) + { + case ":gamepad" | ":rawGamepad": + if (!_currentGamepadControls.exists(shortName)) + { + var expr = meta.params[0]; + var shouldRemap = meta.name != ":rawGamepad"; + if (shouldRemap && Context.defined("switch")) + { + expr = swapAB(expr); + } + _currentGamepadControls.set(shortName, expr); + } + case ":pressed": + keyset = extractString(meta.params[0]); + expr = macro func($i{internalName}, PRESSED); + case ":justPressed": + keyset = extractString(meta.params[0]); + expr = macro func($i{internalName}, JUST_PRESSED); + case ":released": + keyset = extractString(meta.params[0]); + expr = macro func($i{internalName}, RELEASED); + case ":justReleased": + keyset = extractString(meta.params[0]); + expr = macro func($i{internalName}, JUST_RELEASED); + default: + shouldRemove = false; + } + + if (shouldRemove) + metasToRemove.push(meta); + } + + for (meta in metasToRemove) + field.meta.remove(meta); + + if (_currentControls.exists(shortName)) + _currentControls.get(shortName).push(expr); + else + _currentControls.set(shortName, [expr]); + + if (!_allInternalControls.contains(internalName)) + _allInternalControls.push(internalName); + if (!_allControls.contains(shortName)) + _allControls.push(shortName); + + _keySet.set(shortName, keyset); + if (!_internalMap.exists(internalNameNoType)) + _internalMap.set(shortName, internalNameNoType); + + // Generated Code: var _uiUp = new FlxActionDigital("_uiUp"); + var internalField: Field = { + name: internalName, + access: [APrivate], + kind: FVar(macro : FlxActionDigital, macro new FlxActionDigital($v{internalName})), + pos: field.pos, + doc: null, + meta: [] + }; + + // Generated Code: + // inline function get_UI_UP(): Bool + // return _uiUp.check(); + var getField: Field = { + name: "get_" + name, + access: [APrivate, AInline], + kind: FFun({ + ret: macro : Bool, + params: [], + expr: macro + { + return $i{internalName}.check(); + }, + args: [] + }), + pos: field.pos, + doc: field.doc, + meta: [] + }; + + // Generated Code: + // inline function set_UI_UP(val: Bool): Bool + // return @:privateAccess _uiUp._checked = val; + var setField: Field = { + name: "set_" + name, + access: [APrivate, AInline], + kind: FFun({ + ret: macro : Bool, + params: [], + expr: macro + { + return @:privateAccess $i{internalName}._checked = val; + }, + args: [{name: "val", type: macro : Bool}] + }), + pos: field.pos, + doc: field.doc, + meta: [] + }; + + return [internalField, getField, set == "set" ? setField : null]; + } +} diff --git a/source/funkin/backend/system/macros/NewHaxeWarning.hx b/source/funkin/backend/system/macros/NewHaxeWarning.hx deleted file mode 100644 index e6a98991..00000000 --- a/source/funkin/backend/system/macros/NewHaxeWarning.hx +++ /dev/null @@ -1,16 +0,0 @@ -package funkin.backend.system.macros; - -#if macro -class NewHaxeWarning { - public static function warn() { - #if (haxe >= "4.3.0" && !display) - Sys.println("===================="); - Sys.println("[ WARNING ]"); - Sys.println("Compiling with Haxe 4.3.0 isnt fully recommended yet, but it does work."); - Sys.println("We recommend building the project using Haxe 4.2.5."); - Sys.println("You can download it here -> https://haxe.org/download/version/4.2.5/"); - Sys.println("===================="); - #end - } -} -#end \ No newline at end of file diff --git a/source/funkin/backend/utils/CoolUtil.hx b/source/funkin/backend/utils/CoolUtil.hx index bbfd02fa..77c1918a 100644 --- a/source/funkin/backend/utils/CoolUtil.hx +++ b/source/funkin/backend/utils/CoolUtil.hx @@ -1,5 +1,23 @@ package funkin.backend.utils; +#if sys +import sys.FileSystem; +#end +import flixel.text.FlxText; +import funkin.backend.utils.XMLUtil.TextFormat; +import flixel.util.typeLimit.OneOfTwo; +import flixel.util.typeLimit.OneOfThree; +import flixel.tweens.FlxTween; +import flixel.system.frontEnds.SoundFrontEnd; +import flixel.sound.FlxSound; +import funkin.backend.system.Conductor; +import flixel.sound.FlxSoundGroup; +import haxe.Json; +import haxe.io.Path; +import haxe.io.Bytes; +import haxe.xml.Access; +import flixel.input.keyboard.FlxKey; +import lime.utils.Assets; import flixel.animation.FlxAnimation; import flixel.input.keyboard.FlxKey; import flixel.sound.FlxSound; @@ -62,18 +80,15 @@ class CoolUtil */ @:noUsing public static function deleteFolder(delete:String) { #if sys - if (!sys.FileSystem.exists(delete)) return; - var files:Array = sys.FileSystem.readDirectory(delete); + if (!FileSystem.exists(delete)) return; + var files:Array = FileSystem.readDirectory(delete); for(file in files) { - if (sys.FileSystem.isDirectory(delete + "/" + file)) { + if (FileSystem.isDirectory(delete + "/" + file)) { deleteFolder(delete + "/" + file); - sys.FileSystem.deleteDirectory(delete + "/" + file); + FileSystem.deleteDirectory(delete + "/" + file); } else { - try { - sys.FileSystem.deleteFile(delete + "/" + file); - } catch(e) { - Logs.trace("Could not delete " + delete + "/" + file, WARNING); - } + try FileSystem.deleteFile(delete + "/" + file) + catch(e) Logs.trace("Could not delete " + delete + "/" + file, WARNING); } } #end @@ -98,6 +113,70 @@ class CoolUtil #end } + /** + * Gets file attributes from a file or a folder adding eventual missing folders in the path + * (WARNING: Only works on `windows` for now. On other platforms the attributes' value it's always going to be `0` -thanks to the wrapper you can also use `isNothing` for checking- but still creates eventual missing folders if the platforms allows it to). + * @param path Path to the file or folder + * @param useAbsol If it should use the absolute path (By default it's `true` but if it's `false` you can use files outside from this program's directory for example) + * @return The attributes through the `FileAttributeWrapper` + */ + @:noUsing public static inline function safeGetAttributes(path:String, useAbsol:Bool = true):FileAttributeWrapper { + addMissingFolders(Path.directory(path)); + + var result = NativeAPI.getFileAttributes(path, useAbsol); + if(result.isNothing) Logs.trace('The file where it has been tried to get the attributes from, might be corrupted or inexistent (code: ${result.getValue()})', WARNING); + return result; + } + + /** + * Sets file attributes to a file or a folder adding eventual missing folders in the path + * (WARNING: Only works on `windows` for now. On other platforms the return code it's always going to be `0` but still creates eventual missing folders if the platforms allows it to). + * @param path Path to the file or folder + * @param attrib The attribute(s) to set (WARNING: There are some non settable attributes, such as the `COMPRESSED` one) + * @param useAbsol If it should use the absolute path (By default it's `true` but if it's `false` you can use files outside from this program's directory for example) + * @return The result code: `0` means that it failed setting + */ + @:noUsing public static inline function safeSetAttributes(path:String, attrib:OneOfThree, useAbsol:Bool = true):Int { + // yes, i'm aware that FileAttribute is also an Int so need to include it too, but at least like this we don't have to make cast sometimes while passing the arguments - Nex + addMissingFolders(Path.directory(path)); + + var result = NativeAPI.setFileAttributes(path, attrib, useAbsol); + if(result == 0) Logs.trace('Failed to set attributes to $path with a code of: $result', WARNING); + return result; + } + + /** + * Adds one (or more) file attributes to a file or a folder adding eventual missing folders in the path + * (WARNING: Only works on `windows` for now. On other platforms the return code it's always going to be `0` but still creates eventual missing folders if the platforms allows it to). + * @param path Path to the file or folder + * @param attrib The attribute(s) to add (WARNING: There are some non settable attributes, such as the `COMPRESSED` one) + * @param useAbsol If it should use the absolute path (By default it's `true` but if it's `false` you can use files outside from this program's directory for example) + * @return The result code: `0` means that it failed setting + */ + @:noUsing public static inline function safeAddAttributes(path:String, attrib:OneOfTwo, useAbsol:Bool = true):Int { + addMissingFolders(Path.directory(path)); + + var result = NativeAPI.addFileAttributes(path, attrib, useAbsol); + if(result == 0) Logs.trace('Failed to add attributes to $path with a code of: $result', WARNING); + return result; + } + + /** + * Removes one (or more) file attributes to a file or a folder adding eventual missing folders in the path + * (WARNING: Only works on `windows` for now. On other platforms the return code it's always going to be `0` but still creates eventual missing folders if the platforms allows it to). + * @param path Path to the file or folder + * @param attrib The attribute(s) to remove (WARNING: There are some non settable attributes, such as the `COMPRESSED` one) + * @param useAbsol If it should use the absolute path (By default it's `true` but if it's `false` you can use files outside from this program's directory for example) + * @return The result code: `0` means that it failed setting + */ + @:noUsing public static inline function safeRemoveAttributes(path:String, attrib:OneOfTwo, useAbsol:Bool = true):Int { + addMissingFolders(Path.directory(path)); + + var result = NativeAPI.removeFileAttributes(path, attrib, useAbsol); + if(result == 0) Logs.trace('Failed to remove attributes to $path with a code of: $result', WARNING); + return result; + } + /** * Creates eventual missing folders to the specified `path` * @@ -113,9 +192,8 @@ class CoolUtil for (folder in folders) { currentPath += folder + "/"; - if (!sys.FileSystem.exists(currentPath)) { - sys.FileSystem.createDirectory(currentPath); - } + if (!FileSystem.exists(currentPath)) + FileSystem.createDirectory(currentPath); } #end return path; @@ -757,6 +835,16 @@ class CoolUtil return array.indexOf(element) != -1; } #end + + /* + * Returns the filename of a path, without the extension. + * @param path Path to get the filename from + * @return Filename + */ + @:noUsing public static inline function getFilename(file:String) { + var file = new haxe.io.Path(file); + return file.file; + } } /** diff --git a/source/funkin/backend/utils/FileAttributeWrapper.hx b/source/funkin/backend/utils/FileAttributeWrapper.hx new file mode 100644 index 00000000..7d7e26f4 --- /dev/null +++ b/source/funkin/backend/utils/FileAttributeWrapper.hx @@ -0,0 +1,283 @@ +package funkin.backend.utils; + +import flixel.util.FlxStringUtil; +import funkin.backend.utils.NativeAPI.FileAttribute; + +/** + * Currently only for Windows, but planned to work on other platforms later. + */ +class FileAttributeWrapper +{ + private var flags:Int; + inline public function getValue():Int + { + return flags; + } + + public function new(flags:Int) + { + this.flags = flags == -1 ? 0 : flags; + } + + /** + * Returns a string representation of the attributes. + */ + inline public function toString():String + { + return FlxStringUtil.getDebugString([ + for (field in Reflect.fields(this)) + { + LabelValuePair.weak(field, Reflect.getProperty(this, field)); + } + ]); + } + + // Settables + public var isArchived(get, set):Bool; + private function get_isArchived():Bool + { + #if windows + return (flags & FileAttribute.ARCHIVE) != 0; + #else + return false; + #end + } + private function set_isArchived(value:Bool):Bool + { + #if windows + if (value) + flags |= FileAttribute.ARCHIVE; + else + flags &= ~FileAttribute.ARCHIVE; + return value; + #else + return false; + #end + } + + public var isHidden(get, set):Bool; + private function get_isHidden():Bool + { + #if windows + return (flags & FileAttribute.HIDDEN) != 0; + #else + return false; + #end + } + private function set_isHidden(value:Bool):Bool + { + #if windows + if (value) + flags |= FileAttribute.HIDDEN; + else + flags &= ~FileAttribute.HIDDEN; + return value; + #else + return false; + #end + } + + public var isNormal(get, set):Bool; + private function get_isNormal():Bool + { + #if windows + return (flags & FileAttribute.NORMAL) != 0; + #else + return false; + #end + } + private function set_isNormal(value:Bool):Bool + { + #if windows + if (value) + flags |= FileAttribute.NORMAL; + else + flags &= ~FileAttribute.NORMAL; + return value; + #else + return false; + #end + } + + public var isNotContentIndexed(get, set):Bool; + private function get_isNotContentIndexed():Bool + { + #if windows + return (flags & FileAttribute.NOT_CONTENT_INDEXED) != 0; + #else + return false; + #end + } + private function set_isNotContentIndexed(value:Bool):Bool + { + #if windows + if (value) + flags |= FileAttribute.NOT_CONTENT_INDEXED; + else + flags &= ~FileAttribute.NOT_CONTENT_INDEXED; + return value; + #else + return false; + #end + } + + public var isOffline(get, set):Bool; + private function get_isOffline():Bool + { + #if windows + return (flags & FileAttribute.OFFLINE) != 0; + #else + return false; + #end + } + private function set_isOffline(value:Bool):Bool + { + #if windows + if (value) + flags |= FileAttribute.OFFLINE; + else + flags &= ~FileAttribute.OFFLINE; + return value; + #else + return false; + #end + } + + public var isReadOnly(get, set):Bool; + private function get_isReadOnly():Bool + { + #if windows + return (flags & FileAttribute.READONLY) != 0; + #else + return false; + #end + } + private function set_isReadOnly(value:Bool):Bool + { + #if windows + if (value) + flags |= FileAttribute.READONLY; + else + flags &= ~FileAttribute.READONLY; + return value; + #else + return false; + #end + } + + public var isSystem(get, set):Bool; + private function get_isSystem():Bool + { + #if windows + return (flags & FileAttribute.SYSTEM) != 0; + #else + return false; + #end + } + private function set_isSystem(value:Bool):Bool + { + #if windows + if (value) + flags |= FileAttribute.SYSTEM; + else + flags &= ~FileAttribute.SYSTEM; + return value; + #else + return false; + #end + } + + public var isTemporary(get, set):Bool; + private function get_isTemporary():Bool + { + #if windows + return (flags & FileAttribute.TEMPORARY) != 0; + #else + return false; + #end + } + private function set_isTemporary(value:Bool):Bool + { + #if windows + if (value) + flags |= FileAttribute.TEMPORARY; + else + flags &= ~FileAttribute.TEMPORARY; + return value; + #else + return false; + #end + } + + // Non Settables + public var isCompressed(get, never):Bool; + private function get_isCompressed():Bool + { + #if windows + return (flags & FileAttribute.COMPRESSED) != 0; + #else + return false; + #end + } + + public var isDevice(get, never):Bool; + private function get_isDevice():Bool + { + #if windows + return (flags & FileAttribute.DEVICE) != 0; + #else + return false; + #end + } + + public var isDirectory(get, never):Bool; + private function get_isDirectory():Bool + { + #if windows + return (flags & FileAttribute.DIRECTORY) != 0; + #else + return false; + #end + } + + public var isEncrypted(get, never):Bool; + private function get_isEncrypted():Bool + { + #if windows + return (flags & FileAttribute.ENCRYPTED) != 0; + #else + return false; + #end + } + + public var isReparsePoint(get, never):Bool; + private function get_isReparsePoint():Bool + { + #if windows + return (flags & FileAttribute.REPARSE_POINT) != 0; + #else + return false; + #end + } + + public var isSparseFile(get, never):Bool; + private function get_isSparseFile():Bool + { + #if windows + return (flags & FileAttribute.SPARSE_FILE) != 0; + #else + return false; + #end + } + + // For checking + public var isNothing(get, never):Bool; + private function get_isNothing():Bool + { + #if windows + return flags == 0; + #else + return true; + #end + } +} diff --git a/source/funkin/backend/utils/FunkinParentDisabler.hx b/source/funkin/backend/utils/FunkinParentDisabler.hx index 4a7efc3b..07e71a2a 100644 --- a/source/funkin/backend/utils/FunkinParentDisabler.hx +++ b/source/funkin/backend/utils/FunkinParentDisabler.hx @@ -41,7 +41,9 @@ class FunkinParentDisabler extends FlxBasic { } } - public override function update(elapsed:Float) {} + public override function update(elapsed:Float) { + @:privateAccess for(c in __cameras) c.updateFlashSpritePosition(); + } public override function draw() {} public function reset() { diff --git a/source/funkin/backend/utils/NativeAPI.hx b/source/funkin/backend/utils/NativeAPI.hx index e1393be8..b599b090 100644 --- a/source/funkin/backend/utils/NativeAPI.hx +++ b/source/funkin/backend/utils/NativeAPI.hx @@ -4,6 +4,8 @@ import haxe.macro.Expr.Case; import openfl.ui.Mouse; import openfl.ui.MouseCursor; import funkin.backend.utils.native.*; +import flixel.util.typeLimit.OneOfTwo; +import flixel.util.typeLimit.OneOfThree; /** * Class for functions that talk to a lower level than haxe, such as message boxes, and more. @@ -32,6 +34,59 @@ class NativeAPI { #end } + /** + * Gets the specified file's (or folder) attributes. + */ + public static function getFileAttributesRaw(path:String, useAbsol:Bool = true):Int { + #if windows + if(useAbsol) path = sys.FileSystem.absolutePath(path); + return Windows.getFileAttributes(path); + #else + return -1; + #end + } + + /** + * Gets the specified file's (or folder) attributes and passes it to `FileAttributeWrapper`. + */ + public static function getFileAttributes(path:String, useAbsol:Bool = true):FileAttributeWrapper { + return new FileAttributeWrapper(getFileAttributesRaw(path, useAbsol)); + } + + /** + * Sets the specified file's (or folder) attributes. If it fails, the return value is `0`. + */ + public static function setFileAttributes(path:String, attrib:OneOfThree, useAbsol:Bool = true):Int { + #if windows + if(useAbsol) path = sys.FileSystem.absolutePath(path); + return Windows.setFileAttributes(path, attrib is FileAttributeWrapper ? cast(attrib, FileAttributeWrapper).getValue() : cast(attrib, Int)); + #else + return 0; + #end + } + + /** + * Removes from the specified file's (or folder) one (or more) specific attribute. + */ + public static function addFileAttributes(path:String, attrib:OneOfTwo, useAbsol:Bool = true):Int { + #if windows + return setFileAttributes(path, getFileAttributesRaw(path, useAbsol) | cast(attrib, Int), useAbsol); + #else + return 0; + #end + } + + /** + * Removes from the specified file's (or folder) one (or more) specific attribute. + */ + public static function removeFileAttributes(path:String, attrib:OneOfTwo, useAbsol:Bool = true):Int { + #if windows + return setFileAttributes(path, getFileAttributesRaw(path, useAbsol) & ~cast(attrib, Int), useAbsol); + #else + return 0; + #end + } + public static function setDarkMode(title:String, enable:Bool) { #if windows Windows.setDarkMode(title, enable); @@ -64,15 +119,13 @@ class NativeAPI { var fg = cast(foregroundColor, Int); var bg = cast(backgroundColor, Int); Windows.setConsoleColors((bg * 16) + fg); - #else - #if sys + #elseif sys Sys.print("\x1b[0m"); if(foregroundColor != NONE) Sys.print("\x1b[" + Std.int(consoleColorToANSI(foregroundColor)) + "m"); if(backgroundColor != NONE) Sys.print("\x1b[" + Std.int(consoleColorToANSI(backgroundColor) + 10) + "m"); #end - #end } /** @@ -129,6 +182,26 @@ class NativeAPI { } } +enum abstract FileAttribute(Int) from Int to Int { + // Settables + var ARCHIVE = 0x20; + var HIDDEN = 0x2; + var NORMAL = 0x80; + var NOT_CONTENT_INDEXED = 0x2000; + var OFFLINE = 0x1000; + var READONLY = 0x1; + var SYSTEM = 0x4; + var TEMPORARY = 0x100; + + // Non Settables + var COMPRESSED = 0x800; + var DEVICE = 0x40; + var DIRECTORY = 0x10; + var ENCRYPTED = 0x4000; + var REPARSE_POINT = 0x400; + var SPARSE_FILE = 0x200; +} + enum abstract ConsoleColor(Int) { var BLACK = 0; var DARKBLUE = 1; diff --git a/source/funkin/backend/utils/native/Windows.hx b/source/funkin/backend/utils/native/Windows.hx index 07312d8d..a536c75f 100644 --- a/source/funkin/backend/utils/native/Windows.hx +++ b/source/funkin/backend/utils/native/Windows.hx @@ -1,6 +1,7 @@ package funkin.backend.utils.native; #if windows +import funkin.backend.utils.NativeAPI.FileAttribute; import funkin.backend.utils.NativeAPI.MessageBoxIcon; @:buildXml(' @@ -153,6 +154,22 @@ class Windows { public static function allocConsole() { } + @:functionCode(' + return GetFileAttributes(path); + ') + public static function getFileAttributes(path:String):FileAttribute + { + return NORMAL; + } + + @:functionCode(' + return SetFileAttributes(path, attrib); + ') + public static function setFileAttributes(path:String, attrib:FileAttribute):Int + { + return 0; + } + @:functionCode(' HANDLE console = GetStdHandle(STD_OUTPUT_HANDLE); diff --git a/source/funkin/editors/character/CharacterEditor.hx b/source/funkin/editors/character/CharacterEditor.hx index 87705290..d05614e7 100644 --- a/source/funkin/editors/character/CharacterEditor.hx +++ b/source/funkin/editors/character/CharacterEditor.hx @@ -355,10 +355,6 @@ class CharacterEditor extends UIState { } function buildCharacter():String { - if (character.isPlayer != character.playerOffsets) { - character.switchOffset('singLEFT', 'singRIGHT'); - character.switchOffset('singLEFTmiss', 'singRIGHTmiss'); - } var charXML:Xml = character.buildXML([ for (button in characterAnimsWindow.buttons.members) button.anim diff --git a/source/funkin/game/Character.hx b/source/funkin/game/Character.hx index 8b6857ab..f1cb355f 100644 --- a/source/funkin/game/Character.hx +++ b/source/funkin/game/Character.hx @@ -55,12 +55,16 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset @:noCompletion var __stunnedTime:Float = 0; @:noCompletion var __lockAnimThisFrame:Bool = false; - public function new(x:Float, y:Float, ?character:String = "bf", isPlayer:Bool = false, switchAnims:Bool = true, disableScripts:Bool = false) { + @:noCompletion var __switchAnims:Bool = true; + + public function new(x:Float, y:Float, ?character:String = "bf", isPlayer:Bool = false, switchAnims:Bool = true, disableScripts:Bool = false) + { super(x, y); animOffsets = new Map(); curCharacter = character; this.isPlayer = isPlayer; + __switchAnims = switchAnims; antialiasing = true; @@ -91,10 +95,12 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset __autoInterval = autoInterval; // character is flipped - if (isPlayer != playerOffsets && switchAnims) + if (isPlayer != playerOffsets && switchAnims) swapLeftRightAnimations(); - - frameOffset.set(getAnimOffset(getAnimName()).x, getAnimOffset(getAnimName()).y); + + var o:FlxPoint = getAnimOffset(getAnimName()); + frameOffset.set(o.x, o.y); + o.put(); if (isPlayer) flipX = !flipX; __baseFlipped = flipX; } @@ -213,7 +219,7 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset public function drawHitbox() { if (_matrix == null || frame == null) return; - + for (camera in cameras) { var gfx:Graphics = FlxG.renderBlit ? { FlxSpriteUtil.flashGfx.clear(); @@ -257,11 +263,29 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset } public var singAnims = ["singLEFT", "singDOWN", "singUP", "singRIGHT"]; - public function playSingAnim(direction:Int, suffix:String = "", Context:PlayAnimContext = SING, Force:Bool = true, Reversed:Bool = false, Frame:Int = 0) { - var event = EventManager.get(DirectionAnimEvent).recycle(singAnims[direction % singAnims.length] + suffix, direction, suffix, Context, Reversed, Frame, Force); + public inline function getSingAnim(direction:Int, suffix:String = ""):String + { + return singAnims[direction % singAnims.length] + suffix; + } + + /** + * Like `playSingAnimUnsafe` but checks if the character has the animation with the suffix part, otherwise it plays the animation without the suffix part. + */ + public function playSingAnim(direction:Int, suffix:String = "", Context:PlayAnimContext = SING, Force:Bool = true, Reversed:Bool = false, Frame:Int = 0) + { + var event = EventManager.get(DirectionAnimEvent).recycle(getSingAnim(direction, suffix), direction, suffix, Context, Reversed, Frame, Force); script.call("onPlaySingAnim", [event]); - if (!event.cancelled) - playAnim(event.animName, event.force, event.context, event.reversed, event.frame); + if (event.cancelled) return; + + playSingAnimUnsafe(event.direction, hasAnimation(event.animName) ? event.suffix : "", event.context, event.force, event.reversed, event.frame); + } + + public function playSingAnimUnsafe(direction:Int, suffix:String = "", Context:PlayAnimContext = SING, Force:Bool = true, Reversed:Bool = false, Frame:Int = 0) { + var event = EventManager.get(DirectionAnimEvent).recycle(getSingAnim(direction, suffix), direction, suffix, Context, Reversed, Frame, Force); + script.call("playSingAnimUnsafe", [event]); + if (event.cancelled) return; + + playAnim(event.animName, event.force, event.context, event.reversed, event.frame); } public override function playAnim(AnimName:String, Force:Bool = false, Context:PlayAnimContext = NONE, Reversed:Bool = false, Frame:Int = 0) { @@ -288,6 +312,10 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset } public override function destroy() { + if(script != null) { + script.call('destroy'); + script.destroy(); + } super.destroy(); cameraOffset.put(); @@ -367,22 +395,23 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset if (!characterProperties.contains(attribute)) extra[attribute] = xml.x.get(attribute); - fixChar(true, !hasInterval); + fixChar(__switchAnims, !hasInterval); dance(); } public static var characterProperties:Array = [ - "x", "y", "sprite", "scale", "antialiasing", - "flipX", "camx", "camy", "isPlayer", "icon", + "x", "y", "sprite", "scale", "antialiasing", + "flipX", "camx", "camy", "isPlayer", "icon", "color", "gameOverChar", "holdTime" ]; public static var characterAnimProperties:Array = [ "name", "anim", "x", "y", "fps", "loop", "indices" ]; + public inline function buildXML(?animsOrder:Array):Xml { var xml:Xml = Xml.createElement("character"); xml.attributeOrder = characterProperties.copy(); - + if (globalOffset.x != 0) xml.set("x", Std.string(FlxMath.roundDecimal(globalOffset.x, 2))); if (globalOffset.y != 0) xml.set("y", Std.string(FlxMath.roundDecimal(globalOffset.y, 2))); @@ -473,7 +502,7 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset var xmlPath:String = Paths.xml('characters/$character'); if (!Assets.exists(xmlPath)) { character = FALLBACK_CHARACTER; - if (char != null) + if (char != null) char.curCharacter = character; continue; } @@ -487,7 +516,7 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset Logs.trace('Error while loading character ${character}: ${e}', ERROR); character = FALLBACK_CHARACTER; - if (char != null) + if (char != null) char.curCharacter = character; continue; } diff --git a/source/funkin/game/GameOverSubstate.hx b/source/funkin/game/GameOverSubstate.hx index 3e425804..9b8d01e5 100644 --- a/source/funkin/game/GameOverSubstate.hx +++ b/source/funkin/game/GameOverSubstate.hx @@ -112,7 +112,7 @@ class GameOverSubstate extends MusicBeatSubstate if (controls.BACK) { if (PlayState.chartingMode && Charter.undos.unsaved) - PlayState.instance.saveWarn(false); + game.saveWarn(false); else { PlayState.resetSongInfos(); if (Charter.instance != null) Charter.instance.__clearStatics(); diff --git a/source/funkin/game/PlayState.hx b/source/funkin/game/PlayState.hx index dcf56813..12e0189f 100644 --- a/source/funkin/game/PlayState.hx +++ b/source/funkin/game/PlayState.hx @@ -210,9 +210,13 @@ class PlayState extends MusicBeatState */ public var canAccessDebugMenus:Bool = true; /** - * Wether or not to show the secret gitaroo pause. + * Whether or not to show the secret gitaroo pause. */ public var allowGitaroo:Bool = true; + /** + * Whether or not to bop the icons on beat. + */ + public var doIconBop:Bool = true; /** * Whenever cam zooming is enabled, enables on a note hit if not cancelled. @@ -354,11 +358,19 @@ class PlayState extends MusicBeatState * Camera zoom at which the game lerps to. */ public var defaultCamZoom:Float = 1.05; - + /** + * Speed at which the game camera zoom lerps to. + */ + public var camGameZoomLerp:Float = 0.05; + /** * Camera zoom at which the hud lerps to. */ public var defaultHudZoom:Float = 1.0; + /** + * Speed at which the hud camera zoom lerps to. + */ + public var camHUDZoomLerp:Float = 0.05; /** * Zoom for the pixel assets. @@ -1232,12 +1244,13 @@ class PlayState extends MusicBeatState } } - iconP1.scale.set(lerp(iconP1.scale.x, 1, 0.33), lerp(iconP1.scale.y, 1, 0.33)); - iconP2.scale.set(lerp(iconP2.scale.x, 1, 0.33), lerp(iconP2.scale.y, 1, 0.33)); - - iconP1.updateHitbox(); - iconP2.updateHitbox(); + if (doIconBop) { + iconP1.scale.set(lerp(iconP1.scale.x, 1, 0.33), lerp(iconP1.scale.y, 1, 0.33)); + iconP2.scale.set(lerp(iconP2.scale.x, 1, 0.33), lerp(iconP2.scale.y, 1, 0.33)); + iconP1.updateHitbox(); + iconP2.updateHitbox(); + } updateIconPositions(); if (startingSong) @@ -1286,8 +1299,8 @@ class PlayState extends MusicBeatState if (camZooming) { - FlxG.camera.zoom = lerp(FlxG.camera.zoom, defaultCamZoom, 0.05); - camHUD.zoom = lerp(camHUD.zoom, defaultHudZoom, 0.05); + FlxG.camera.zoom = lerp(FlxG.camera.zoom, defaultCamZoom, camGameZoomLerp); + camHUD.zoom = lerp(camHUD.zoom, defaultHudZoom, camHUDZoomLerp); } // RESET = Quick Game Over Screen @@ -1787,11 +1800,14 @@ class PlayState extends MusicBeatState camHUD.zoom += 0.03 * camZoomingStrength; } - iconP1.scale.set(1.2, 1.2); - iconP2.scale.set(1.2, 1.2); + if (doIconBop) + { + iconP1.scale.set(1.2, 1.2); + iconP2.scale.set(1.2, 1.2); - iconP1.updateHitbox(); - iconP2.updateHitbox(); + iconP1.updateHitbox(); + iconP2.updateHitbox(); + } scripts.call("beatHit", [curBeat]); } diff --git a/source/funkin/game/StrumLine.hx b/source/funkin/game/StrumLine.hx index 037f9744..d743dd79 100644 --- a/source/funkin/game/StrumLine.hx +++ b/source/funkin/game/StrumLine.hx @@ -29,9 +29,9 @@ class StrumLine extends FlxTypedGroup { */ public var onNoteUpdate:FlxTypedSignalVoid> = new FlxTypedSignalVoid>(); /** - * Signal that triggers whenever a note is being updated. Similar to onNoteUpdate, except strumline specific. + * Signal that triggers whenever a note is being deleted. Similar to onNoteDelete, except strumline specific. * To add a listener, do - * `strumLine.onNoteUpdate.add(function(e:NoteUpdateEvent) {});` + * `strumLine.onNoteDelete.add(function(e:SimpleNoteEvent) {});` */ public var onNoteDelete:FlxTypedSignalVoid> = new FlxTypedSignalVoid>(); /** diff --git a/source/funkin/menus/MainMenuState.hx b/source/funkin/menus/MainMenuState.hx index 171f7959..2f5ea12c 100644 --- a/source/funkin/menus/MainMenuState.hx +++ b/source/funkin/menus/MainMenuState.hx @@ -70,7 +70,7 @@ class MainMenuState extends MusicBeatState FlxG.camera.follow(camFollow, null, 0.06); - var versionShit:FunkinText = new FunkinText(5, FlxG.height - 2, 0, 'Codename Engine v${Application.current.meta.get('version')}\nCommit ${funkin.backend.system.macros.GitCommitMacro.commitNumber} (${funkin.backend.system.macros.GitCommitMacro.commitHash})\n[TAB] Open Mods menu\n'); + var versionShit:FunkinText = new FunkinText(5, FlxG.height - 2, 0, 'Codename Engine v${Application.current.meta.get('version')}\nCommit ${funkin.backend.system.macros.GitCommitMacro.commitNumber} (${funkin.backend.system.macros.GitCommitMacro.commitHash})\n[${controls.getKeyName(SWITCHMOD)}] Open Mods menu\n'); versionShit.y -= versionShit.height; versionShit.scrollFactor.set(); add(versionShit); diff --git a/source/funkin/menus/PauseSubState.hx b/source/funkin/menus/PauseSubState.hx index 53dc65bb..ff45f20a 100644 --- a/source/funkin/menus/PauseSubState.hx +++ b/source/funkin/menus/PauseSubState.hx @@ -106,7 +106,7 @@ class PauseSubState extends MusicBeatSubstate pauseScript.call("postCreate"); - PlayState.instance.updateDiscordPresence(); + game.updateDiscordPresence(); } override function update(elapsed:Float) @@ -146,7 +146,7 @@ class PauseSubState extends MusicBeatSubstate close(); case "Restart Song": parentDisabler.reset(); - PlayState.instance.registerSmoothTransition(); + game.registerSmoothTransition(); FlxG.resetState(); case "Change Controls": persistentDraw = false; @@ -157,7 +157,7 @@ class PauseSubState extends MusicBeatSubstate FlxG.switchState(new funkin.editors.charter.Charter(PlayState.SONG.meta.name, PlayState.difficulty, false)); case "Exit to menu": if (PlayState.chartingMode && Charter.undos.unsaved) - PlayState.instance.saveWarn(false); + game.saveWarn(false); else { PlayState.resetSongInfos(); if (Charter.instance != null) Charter.instance.__clearStatics(); diff --git a/source/funkin/menus/ui/Alphabet.hx b/source/funkin/menus/ui/Alphabet.hx index bd98a1d2..663fa1b1 100644 --- a/source/funkin/menus/ui/Alphabet.hx +++ b/source/funkin/menus/ui/Alphabet.hx @@ -50,7 +50,7 @@ class Alphabet extends FlxSpriteGroup // TODO: fix this shit refreshing public function refreshAlphabetXML(path:String) { - AlphaCharacter.__alphaPath = path; + AlphaCharacter.__alphaPath = Paths.getAssetsRoot() + path; try { var xml = new Access(Xml.parse(Assets.getText(path)).firstElement()); AlphaCharacter.boldAnims = []; @@ -85,7 +85,7 @@ class Alphabet extends FlxSpriteGroup isBold = bold; var alphabetPath = Paths.xml("alphabet"); - if (alphabetPath != AlphaCharacter.__alphaPath) { + if (Paths.getAssetsRoot() + alphabetPath != AlphaCharacter.__alphaPath) { refreshAlphabetXML(alphabetPath); } #if MOD_SUPPORT else { diff --git a/source/funkin/options/OptionsMenu.hx b/source/funkin/options/OptionsMenu.hx index dff76067..facfcafc 100644 --- a/source/funkin/options/OptionsMenu.hx +++ b/source/funkin/options/OptionsMenu.hx @@ -48,8 +48,6 @@ class OptionsMenu extends TreeMenu { bg.antialiasing = true; add(bg); - Framerate.offset.y = 60; - main = new OptionsScreen("Options", "Select a category to continue.", [for(o in mainOptions) new TextOption(o.name, o.desc, function() { if (o.substate != null) { persistentUpdate = false; diff --git a/source/funkin/options/TreeMenu.hx b/source/funkin/options/TreeMenu.hx index 6fb4a8a5..4faa8cd0 100644 --- a/source/funkin/options/TreeMenu.hx +++ b/source/funkin/options/TreeMenu.hx @@ -7,6 +7,7 @@ import funkin.backend.FunkinText; import funkin.editors.ui.UIState; import funkin.menus.MainMenuState; import funkin.options.type.OptionType; +import funkin.backend.system.framerate.Framerate; class TreeMenu extends UIState { public var main:OptionsScreen; @@ -97,6 +98,8 @@ class TreeMenu extends UIState { var menuChangeTween:FlxTween; public override function update(elapsed:Float) { super.update(elapsed); + + Framerate.offset.y = pathBG.height; // in case path gets so long it goes offscreen pathLabel.x = lerp(pathLabel.x, Math.max(0, FlxG.width - 4 - pathLabel.width), 0.125); diff --git a/source/lime/system/System.hx b/source/lime/system/System.hx index 59b71a83..98efafe3 100644 --- a/source/lime/system/System.hx +++ b/source/lime/system/System.hx @@ -25,6 +25,9 @@ import js.Browser; import sys.io.Process; #end +/** + Access operating system level settings and operations. +**/ #if !lime_debug @:fileXml('tags="haxe,release"') @:noDebug @@ -44,21 +47,68 @@ extern "C" { #end class System { + /** + Determines if the screen saver is allowed to start or not. + **/ public static var allowScreenTimeout(get, set):Bool; + + /** + The path to the directory where the application is installed, along with + its supporting files. In many cases, this directory is read-only, and + attempts to write to files, create new files, or delete files in this + directory are likely fail. + **/ public static var applicationDirectory(get, never):String; + + /** + The application's dedicated storage directory, which unique to each + application and user. Useful for storing settings on a user-specific + and application-specific basis. + + This directory may or may not be removed when the application is + uninstalled, and it depends on the platform and installer technology + that is used. + **/ public static var applicationStorageDirectory(get, never):String; + + /** + The path to the directory containing the user's desktop. + **/ public static var desktopDirectory(get, never):String; + public static var deviceModel(get, never):String; public static var deviceVendor(get, never):String; public static var disableCFFI:Bool; + + /** + The path to the directory containing the user's documents. + **/ public static var documentsDirectory(get, never):String; + + /** + The platform's default endianness for bytes. + **/ public static var endianness(get, never):Endian; + + /** + The path to the directory where fonts are installed. + **/ public static var fontsDirectory(get, never):String; + + /** + The number of available video displays. + **/ public static var numDisplays(get, never):Int; + public static var platformLabel(get, never):String; public static var platformName(get, never):String; public static var platformVersion(get, never):String; + + /** + The path to the user's home directory. + **/ public static var userDirectory(get, never):String; + @:noCompletion private static var __applicationDirectory:String; @:noCompletion private static var __applicationEntryPoint:Map; @:noCompletion private static var __applicationStorageDirectory:String; @@ -84,7 +134,7 @@ class System { var htmlElement:Element = null; - if (Std.is(element, String)) + if ((element is String)) { htmlElement = cast Browser.document.getElementById(element); } @@ -115,7 +165,7 @@ class System if (config == null) config = {}; - if (Reflect.hasField(config, "background") && Std.is(config.background, String)) + if (Reflect.hasField(config, "background") && (config.background is String)) { var background = StringTools.replace(Std.string(config.background), "#", ""); @@ -139,6 +189,10 @@ class System #end #if (!lime_doc_gen || sys) + /** + Attempts to exit the application. Dispatches `onExit`, and will not + exit if the event is canceled. + **/ public static function exit(code:Int):Void { var currentApp = Application.current; @@ -167,6 +221,9 @@ class System } #end + /** + Returns information about the video display with the specified ID. + **/ public static function getDisplay(id:Int):Display { #if (lime_cffi && !macro) @@ -265,11 +322,12 @@ class System return null; } + /** + The number of milliseconds since the application was initialized. + **/ public static function getTimer():Int { - #if (kha && !macro) - return Std.int(kha.System.time * 1000); - #elseif flash + #if flash return flash.Lib.getTimer(); #elseif ((js && !nodejs) || electron) return Std.int(Browser.window.performance.now()); @@ -295,6 +353,11 @@ class System } #end + /** + Opens a file with the suste, default application. + + In a web browser, opens a URL with target `_blank`. + **/ public static function openFile(path:String):Void { if (path != null) @@ -304,7 +367,7 @@ class System #elseif mac Sys.command("/usr/bin/open", [path]); #elseif linux - Sys.command("/usr/bin/xdg-open", [path, "&"]); + Sys.command("/usr/bin/xdg-open", [path]); #elseif (js && html5) Browser.window.open(path, "_blank"); #elseif flash @@ -318,6 +381,9 @@ class System } } + /** + Opens a URL with the specified target web browser window. + **/ public static function openURL(url:String, target:String = "_blank"):Void { if (url != null) @@ -430,6 +496,8 @@ class System #if sys private static function __parseArguments(attributes:WindowAttributes):Void { + // TODO: Handle default arguments, like --window-fps=60 + var arguments = Sys.args(); var stripQuotes = ~/^['"](.*)['"]$/; var equals, argValue, parameters = null; @@ -825,7 +893,7 @@ class System } } -enum abstract SystemDirectory(Int) from Int to Int from UInt to UInt +#if (haxe_ver >= 4.0) enum #else @:enum #end abstract SystemDirectory(Int) from Int to Int from UInt to UInt { var APPLICATION = 0; var APPLICATION_STORAGE = 1; diff --git a/source/lime/utils/Log.hx b/source/lime/utils/Log.hx index 633cc71c..de13c040 100644 --- a/source/lime/utils/Log.hx +++ b/source/lime/utils/Log.hx @@ -12,17 +12,17 @@ import funkin.backend.system.Logs as FunkinLogs; class Log { public static var level:LogLevel; + public static var throwErrors:Bool = false; public static function debug(message:Dynamic, ?info:PosInfos):Void { if (level >= LogLevel.DEBUG) { #if js - untyped __js__("console").debug("[" + info.className + "] " + message); + untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").debug("[" + info.className + "] " + message); #else println("[" + info.className + "] " + Std.string(message)); #end - } } @@ -30,23 +30,32 @@ class Log { if (level >= LogLevel.ERROR) { - var message = '[${info.className}] $message'; - - #if !macro - FunkinLogs.trace(message, ERROR, RED); - #else - trace(message); - #end + if (throwErrors) + { + #if webassembly + println(message); + #end + throw message; + } + else + { + #if !macro + FunkinLogs.trace('[${info.className}] $message', ERROR, RED); + #else + println("[" + info.className + "] ERROR: " + message); + #end + } } } public static function info(message:Dynamic, ?info:PosInfos):Void { - if (level >= LogLevel.INFO) { + if (level >= LogLevel.INFO) + { #if !macro FunkinLogs.trace('[${info.className}] $message', INFO, RED); #else - trace('[${info.className}] $message'); + println("[" + info.className + "] " + Std.string(message)); #end } } @@ -58,7 +67,7 @@ class Log #elseif flash untyped __global__["trace"](Std.string(message)); #elseif js - untyped __js__("console").log(message); + untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").log(message); #else trace(message); #end @@ -71,7 +80,7 @@ class Log #elseif flash untyped __global__["trace"](Std.string(message)); #elseif js - untyped __js__("console").log(message); + untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").log(message); #else trace(Std.string(message)); #end @@ -79,11 +88,12 @@ class Log public static function verbose(message:Dynamic, ?info:PosInfos):Void { - if (level >= LogLevel.VERBOSE) { + if (level >= LogLevel.VERBOSE) + { #if !macro FunkinLogs.trace('[${info.className}] $message', VERBOSE); #else - trace('[${info.className}] $message'); + println("[" + info.className + "] " + message); #end } } @@ -95,7 +105,7 @@ class Log #if !macro FunkinLogs.trace('[${info.className}] $message', WARNING, YELLOW); #else - trace('[${info.className}] $message'); + println("[" + info.className + "] WARNING: " + Std.string(message)); #end } } @@ -125,13 +135,13 @@ class Log #end #if js - if (untyped __js__("typeof console") == "undefined") + if (untyped #if haxe4 js.Syntax.code #else __js__ #end ("typeof console") == "undefined") { - untyped __js__("console = {}"); + untyped #if haxe4 js.Syntax.code #else __js__ #end ("console = {}"); } - if (untyped __js__("console").log == null) + if (untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").log == null) { - untyped __js__("console").log = function() {}; + untyped #if haxe4 js.Syntax.code #else __js__ #end ("console").log = function() {}; } #end } diff --git a/source/openfl/utils/Assets.hx b/source/openfl/utils/Assets.hx index e08852cd..db92e530 100644 --- a/source/openfl/utils/Assets.hx +++ b/source/openfl/utils/Assets.hx @@ -91,7 +91,7 @@ class Assets @usage var bitmap = new Bitmap (Assets.getBitmapData ("image.png")); @param id The ID or asset path for the bitmap @param useCache (Optional) Whether to allow use of the asset cache (Default: true) - @param useCache Whenever the image should be immediately pushed to GPU. + @param pushToGPU Whenever the image should be immediately pushed to GPU. @return A new BitmapData object **/ public static function getBitmapData(id:String, useCache:Bool = true, pushToGPU:Bool = true):BitmapData