diff --git a/source/Xml.hx b/source/Xml.hx new file mode 100644 index 00000000..82613dcd --- /dev/null +++ b/source/Xml.hx @@ -0,0 +1,410 @@ +/* + * Copyright (C)2005-2019 Haxe Foundation + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. + */ + +/** + Xml node types. + + @see https://haxe.org/manual/std-Xml.html +**/ +enum abstract XmlType(Int) { + /** + Represents an XML element type. + **/ + var Element = 0; + + /** + Represents XML parsed character data type. + **/ + var PCData = 1; + + /** + Represents XML character data type. + **/ + var CData = 2; + + /** + Represents an XML comment type. + **/ + var Comment = 3; + + /** + Represents an XML doctype element type. + **/ + var DocType = 4; + + /** + Represents an XML processing instruction type. + **/ + var ProcessingInstruction = 5; + + /** + Represents an XML document type. + **/ + var Document = 6; + + public function toString():String { + return switch (cast this : XmlType) { + case Element: "Element"; + case PCData: "PCData"; + case CData: "CData"; + case Comment: "Comment"; + case DocType: "DocType"; + case ProcessingInstruction: "ProcessingInstruction"; + case Document: "Document"; + }; + } +} + +/** + Cross-platform Xml API. + + @see https://haxe.org/manual/std-Xml.html +**/ +class Xml { + /** + XML element type. + **/ + static public var Element(default, never) = XmlType.Element; + + /** + XML parsed character data type. + **/ + static public var PCData(default, never) = XmlType.PCData; + + /** + XML character data type. + **/ + static public var CData(default, never) = XmlType.CData; + + /** + XML comment type. + **/ + static public var Comment(default, never) = XmlType.Comment; + + /** + XML doctype element type. + **/ + static public var DocType(default, never) = XmlType.DocType; + + /** + XML processing instruction type. + **/ + static public var ProcessingInstruction(default, never) = XmlType.ProcessingInstruction; + + /** + XML document type. + **/ + static public var Document(default, never) = XmlType.Document; + + /** + Parses the String into an Xml document. + **/ + static public function parse(str:String):Xml { + return haxe.xml.Parser.parse(str); + } + + /** + Returns the type of the Xml Node. This should be used before + accessing other functions since some might raise an exception + if the node type is not correct. + **/ + public var nodeType(default, null):XmlType; + + /** + Returns the node name of an Element. + **/ + @:isVar public var nodeName(get, set):String; + + /** + Returns the node value. Only works if the Xml node is not an Element or a Document. + **/ + @:isVar public var nodeValue(get, set):String; + + /** + Returns the parent object in the Xml hierarchy. + The parent can be `null`, an Element or a Document. + **/ + public var parent(default, null):Xml; + + var children:Array; + var attributeMap:Map; + + public var attributeOrder:Array; + + #if !cppia inline #end function get_nodeName() { + if (nodeType != Element) { + throw 'Bad node type, expected Element but found $nodeType'; + } + return nodeName; + } + + #if !cppia inline #end function set_nodeName(v) { + if (nodeType != Element) { + throw 'Bad node type, expected Element but found $nodeType'; + } + return this.nodeName = v; + } + + #if !cppia inline #end function get_nodeValue() { + if (nodeType == Document || nodeType == Element) { + throw 'Bad node type, unexpected $nodeType'; + } + return nodeValue; + } + + #if !cppia inline #end function set_nodeValue(v) { + if (nodeType == Document || nodeType == Element) { + throw 'Bad node type, unexpected $nodeType'; + } + return this.nodeValue = v; + } + + /** + Creates a node of the given type. + **/ + static public function createElement(name:String):Xml { + var xml = new Xml(Element); + xml.nodeName = name; + return xml; + } + + /** + Creates a node of the given type. + **/ + static public function createPCData(data:String):Xml { + var xml = new Xml(PCData); + xml.nodeValue = data; + return xml; + } + + /** + Creates a node of the given type. + **/ + static public function createCData(data:String):Xml { + var xml = new Xml(CData); + xml.nodeValue = data; + return xml; + } + + /** + Creates a node of the given type. + **/ + static public function createComment(data:String):Xml { + var xml = new Xml(Comment); + xml.nodeValue = data; + return xml; + } + + /** + Creates a node of the given type. + **/ + static public function createDocType(data:String):Xml { + var xml = new Xml(DocType); + xml.nodeValue = data; + return xml; + } + + /** + Creates a node of the given type. + **/ + static public function createProcessingInstruction(data:String):Xml { + var xml = new Xml(ProcessingInstruction); + xml.nodeValue = data; + return xml; + } + + /** + Creates a node of the given type. + **/ + static public function createDocument():Xml { + return new Xml(Document); + } + + /** + Get the given attribute of an Element node. Returns `null` if not found. + Attributes are case-sensitive. + **/ + public function get(att:String):String { + if (nodeType != Element) { + throw 'Bad node type, expected Element but found $nodeType'; + } + return attributeMap[att]; + } + + /** + Set the given attribute value for an Element node. + Attributes are case-sensitive. + **/ + public function set(att:String, value:String):Void { + if (nodeType != Element) { + throw 'Bad node type, expected Element but found $nodeType'; + } + attributeMap.set(att, value); + } + + /** + Removes an attribute for an Element node. + Attributes are case-sensitive. + **/ + public function remove(att:String):Void { + if (nodeType != Element) { + throw 'Bad node type, expected Element but found $nodeType'; + } + attributeMap.remove(att); + } + + /** + Tells if the Element node has a given attribute. + Attributes are case-sensitive. + **/ + public function exists(att:String):Bool { + if (nodeType != Element) { + throw 'Bad node type, expected Element but found $nodeType'; + } + return attributeMap.exists(att); + } + + /** + Returns an `Iterator` on all the attribute names. + **/ + public function attributes():Iterator { + if (nodeType != Element) { + throw 'Bad node type, expected Element but found $nodeType'; + } + return attributeMap.keys(); + } + + /** + Returns an iterator of all child nodes. + Only works if the current node is an Element or a Document. + **/ + public #if !cppia inline #end function iterator():Iterator { + ensureElementType(); + return children.iterator(); + } + + /** + Returns an iterator of all child nodes which are Elements. + Only works if the current node is an Element or a Document. + **/ + public function elements():Iterator { + ensureElementType(); + var ret = [for (child in children) if (child.nodeType == Element) child]; + return ret.iterator(); + } + + /** + Returns an iterator of all child nodes which are Elements with the given nodeName. + Only works if the current node is an Element or a Document. + **/ + public function elementsNamed(name:String):Iterator { + ensureElementType(); + var ret = [ + for (child in children) + if (child.nodeType == Element && child.nodeName == name) child + ]; + return ret.iterator(); + } + + /** + Returns the first child node. + **/ + public #if !cppia inline #end function firstChild():Xml { + ensureElementType(); + return children[0]; + } + + /** + Returns the first child node which is an Element. + **/ + public function firstElement():Xml { + ensureElementType(); + for (child in children) { + if (child.nodeType == Element) { + return child; + } + } + return null; + } + + /** + Adds a child node to the Document or Element. + A child node can only be inside one given parent node, which is indicated by the `parent` property. + If the child is already inside this Document or Element, it will be moved to the last position among the Document or Element's children. + If the child node was previously inside a different node, it will be moved to this Document or Element. + **/ + public function addChild(x:Xml):Void { + ensureElementType(); + if (x.parent != null) { + x.parent.removeChild(x); + } + children.push(x); + x.parent = this; + } + + /** + Removes a child from the Document or Element. + Returns true if the child was successfuly removed. + **/ + public function removeChild(x:Xml):Bool { + ensureElementType(); + if (children.remove(x)) { + x.parent = null; + return true; + } + return false; + } + + /** + Inserts a child at the given position among the other childs. + A child node can only be inside one given parent node, which is indicated by the [parent] property. + If the child is already inside this Document or Element, it will be moved to the new position among the Document or Element's children. + If the child node was previously inside a different node, it will be moved to this Document or Element. + **/ + public function insertChild(x:Xml, pos:Int):Void { + ensureElementType(); + if (x.parent != null) { + x.parent.children.remove(x); + } + children.insert(pos, x); + x.parent = this; + } + + /** + Returns a String representation of the Xml node. + **/ + public #if !cppia inline #end function toString():String { + return haxe.xml.Printer.print(this); + } + + function new(nodeType:XmlType) { + this.nodeType = nodeType; + children = []; + attributeMap = new Map(); + } + + inline function ensureElementType() { + if (nodeType != Document && nodeType != Element) { + throw 'Bad node type, expected Element or Document but found $nodeType'; + } + } +} \ No newline at end of file diff --git a/source/funkin/backend/utils/CoolUtil.hx b/source/funkin/backend/utils/CoolUtil.hx index 8cf268e6..9448b05a 100644 --- a/source/funkin/backend/utils/CoolUtil.hx +++ b/source/funkin/backend/utils/CoolUtil.hx @@ -718,6 +718,16 @@ class CoolUtil @:noUsing public static inline function flxeaseFromString(mainEase:String, suffix:String) return Reflect.field(FlxEase, mainEase + (mainEase == "linear" ? "" : suffix)); + + /* + * 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/editors/character/CharacterInfoScreen.hx b/source/funkin/editors/character/CharacterInfoScreen.hx index 28425c2e..882df52b 100644 --- a/source/funkin/editors/character/CharacterInfoScreen.hx +++ b/source/funkin/editors/character/CharacterInfoScreen.hx @@ -119,7 +119,7 @@ class CharacterInfoScreen extends UISubstateWindow { add(isPlayerCheckbox); addLabelOn(isPlayerCheckbox, "Is Player"); - isGFCheckbox = new UICheckbox(isPlayerCheckbox.x + 128, positionXStepper.y + 10 + 32 + 28, "isGF", character.isGF); + isGFCheckbox = new UICheckbox(isPlayerCheckbox.x + 128, positionXStepper.y + 10 + 32 + 28, "isGF", false); add(isGFCheckbox); addLabelOn(isGFCheckbox, "Is GF"); @@ -168,7 +168,6 @@ class CharacterInfoScreen extends UISubstateWindow { var xml = Xml.createElement("character"); xml.set("isPlayer", isPlayerCheckbox.checked ? "true" : "false"); - xml.set("isGF", isGFCheckbox.checked ? "true" : "false"); xml.set("x", Std.string(positionXStepper.value)); xml.set("y", Std.string(positionYStepper.value)); xml.set("gameOverChar", gameOverCharTextBox.label.text); diff --git a/source/funkin/game/Character.hx b/source/funkin/game/Character.hx index 69afc69e..c2faaafc 100644 --- a/source/funkin/game/Character.hx +++ b/source/funkin/game/Character.hx @@ -1,37 +1,34 @@ package funkin.game; -import flixel.util.FlxColor; -import funkin.backend.FunkinSprite; +import flixel.util.typeLimit.OneOfTwo; import flixel.graphics.frames.FlxFrame; import flixel.math.FlxPoint; +import flixel.math.FlxRect; +import flixel.util.FlxColor; +import funkin.backend.FunkinSprite; +import funkin.backend.scripting.DummyScript; +import funkin.backend.scripting.Script; +import funkin.backend.scripting.events.DanceEvent; +import funkin.backend.scripting.events.DirectionAnimEvent; +import funkin.backend.scripting.events.PlayAnimEvent; +import funkin.backend.scripting.events.PlayAnimEvent.PlayAnimContext; +import funkin.backend.scripting.events.PointEvent; +import funkin.backend.system.Conductor; import funkin.backend.system.interfaces.IBeatReceiver; import funkin.backend.system.interfaces.IOffsetCompatible; import funkin.backend.utils.XMLUtil; -import flixel.math.FlxRect; -import haxe.xml.Access; import haxe.Exception; import haxe.io.Path; -import funkin.backend.system.Conductor; +import haxe.xml.Access; import openfl.geom.ColorTransform; -import funkin.backend.scripting.DummyScript; -import funkin.backend.scripting.Script; -import funkin.backend.scripting.events.*; -import funkin.backend.scripting.events.PlayAnimEvent.PlayAnimContext; using StringTools; @:allow(funkin.desktop.editors.CharacterEditor) @:allow(funkin.game.StrumLine) @:allow(funkin.game.PlayState) -class Character extends FunkinSprite implements IBeatReceiver implements IOffsetCompatible -{ - private var __stunnedTime:Float = 0; - private var __lockAnimThisFrame:Bool = false; - - public var stunned(default, set):Bool = false; - +class Character extends FunkinSprite implements IBeatReceiver implements IOffsetCompatible { public var isPlayer:Bool = false; - public var isGF:Bool = false; public var curCharacter:String = 'bf'; public var sprite:String = 'bf'; @@ -42,163 +39,84 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset public var icon:String = null; public var iconColor:Null = null; - public var gameOverCharacter:String = "bf-dead"; + public var gameOverCharacter:String = Character.FALLBACK_DEAD_CHARACTER; - public var cameraOffset:FlxPoint = new FlxPoint(0, 0); - public var globalOffset:FlxPoint = new FlxPoint(0, 0); + public var cameraOffset:FlxPoint = FlxPoint.get(0, 0); + public var globalOffset:FlxPoint = FlxPoint.get(0, 0); public var script:Script; public var xml:Access; - public var shadowFrame:CharacterShadowFrame; public var idleSuffix:String = ""; + public var stunned(default, set):Bool = false; - public var anims = ["singLEFT", "singDOWN", "singUP", "singRIGHT"]; // Not making these inline so theyre editable through scripts! - Nex + @:noCompletion var __stunnedTime:Float = 0; + @:noCompletion var __lockAnimThisFrame:Bool = false; - public inline function getCameraPosition() - { - var midpoint = getMidpoint(); - var event = EventManager.get(PointEvent).recycle( - midpoint.x + (isPlayer ? -100 : 150) + globalOffset.x + cameraOffset.x, - midpoint.y - 100 + globalOffset.y + cameraOffset.y); - script.call("onGetCamPos", [event]); - midpoint.put(); - // this event cannot be cancelled - return new FlxPoint(event.x, event.y); - } + @:noCompletion var __switchAnims:Bool = true; - public inline function getSingAnim(direction:Int, suffix:String = ""):String - { - return anims[direction] + suffix; - } - - /** - * Like `playSingAnimUnsafe` but checks if the character has the animation with the suffix part, otherwhise tries to play 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) - 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("onPlaySingAnimUnsafe", [event]); - if (!event.cancelled) - playAnim(event.animName, event.force, event.context, event.reversed, event.frame); - } - - public function new(x:Float, y:Float, ?character:String = "bf", isPlayer:Bool = false, 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; - while (true) - { - switch (curCharacter) - { - // case 'your-char': // To hardcode characters - default: - // load xml - var xmlPath = Paths.xml('characters/$curCharacter'); - if (!Assets.exists(xmlPath)) - { - curCharacter = "bf"; - continue; - } + xml = getXMLFromCharName(this); + + if(!disableScripts) + script = Script.create(Paths.script(Path.withoutExtension(Paths.xml('characters/$curCharacter')), null, true)); + else + script = new DummyScript(curCharacter); + script.setParent(this); + script.load(); + + buildCharacter(xml); + script.call("create"); - var plainXML = Assets.getText(xmlPath); - try - { - var charXML = Xml.parse(plainXML).firstElement(); - if (charXML == null) throw new Exception("Missing \"character\" node in XML."); - xml = new Access(charXML); - } catch (e) { - Logs.trace('Error while loading character ${curCharacter}: ${e}', ERROR); - curCharacter = "bf"; - continue; - } - // Loads the script - script = Script.create(Paths.script(Path.withoutExtension(xmlPath), null, true)); - script.setParent(this); - script.load(); - applyXML(xml); - script.call("create"); - } - break; - } if (script == null) script = new DummyScript(curCharacter); - /** - NON CONVERTED CHARACTERS - DO NOT REMOVE - **/ - // case 'bf-pixel-dead': - // frames = Paths.getSparrowAtlas('weeb/bfPixelsDEAD'); - // animation.addByPrefix('singUP', "BF Dies pixel", 24, false); - // animation.addByPrefix('firstDeath', "BF Dies pixel", 24, false); - // animation.addByPrefix('deathLoop', "Retry Loop", 24, true); - // animation.addByPrefix('deathConfirm', "RETRY CONFIRM", 24, false); - // animation.play('firstDeath'); - - // addOffset('firstDeath'); - // addOffset('deathLoop', -37); - // addOffset('deathConfirm', -37); - // playAnim('firstDeath'); - // // pixel bullshit - // setGraphicSize(Std.int(width * 6)); - // updateHitbox(); - // antialiasing = false; - // flipX = true; - script.call("postCreate"); } - public function fixChar(switchAnims:Bool = false, autoInterval:Bool = false) - { + @:noCompletion var __swappedLeftRightAnims:Bool = false; + @:noCompletion var __autoInterval:Bool = false; + + public function fixChar(switchAnims:Bool = false, autoInterval:Bool = false) { if ((isDanceLeftDanceRight = hasAnimation("danceLeft") && hasAnimation("danceRight")) && autoInterval) beatInterval = 1; + __autoInterval = autoInterval; - // alternative to xor operator - // for people who dont believe it, heres the truth table - // [ a ][ b ][ a!= b ] - // [ true ][ true ][ false ] - // [ true ][ false ][ true ] - // [ false ][ true ][ true ] - // [ true ][ true ][ false ] - // bros provided evidence :skull: - if (isPlayer != playerOffsets && switchAnims) - { - // character is flipped - CoolUtil.switchAnimFrames(animation.getByName('singRIGHT'), animation.getByName('singLEFT')); - CoolUtil.switchAnimFrames(animation.getByName('singRIGHTmiss'), animation.getByName('singLEFTmiss')); - - switchOffset('singLEFT', 'singRIGHT'); - switchOffset('singLEFTmiss', 'singRIGHTmiss'); - } + // character is flipped + if (isPlayer != playerOffsets && switchAnims) + swapLeftRightAnimations(); + frameOffset.set(getAnimOffset(getAnimName()).x, getAnimOffset(getAnimName()).y); - if (isPlayer) - flipX = !flipX; + if (isPlayer) flipX = !flipX; __baseFlipped = flipX; } - var __baseFlipped:Bool = false; - var isDanceLeftDanceRight:Bool = false; + public function swapLeftRightAnimations() { + CoolUtil.switchAnimFrames(animation.getByName('singRIGHT'), animation.getByName('singLEFT')); + CoolUtil.switchAnimFrames(animation.getByName('singRIGHTmiss'), animation.getByName('singLEFTmiss')); - override function update(elapsed:Float) - { + switchOffset('singLEFT', 'singRIGHT'); + switchOffset('singLEFTmiss', 'singRIGHTmiss'); + + __swappedLeftRightAnims = true; + } + + @:noCompletion var __baseFlipped:Bool = false; + @:noCompletion var isDanceLeftDanceRight:Bool = false; + + override function update(elapsed:Float) { super.update(elapsed); script.call("update", [elapsed]); - if (stunned) - { + if (stunned) { __stunnedTime += elapsed; if (__stunnedTime > 5 / 60) stunned = false; @@ -212,33 +130,20 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset private var danced:Bool = false; - /** - * FOR GF DANCING SHIT - */ - public function dance() - { + public function dance() { if(debugMode) return; var event = EventManager.get(DanceEvent).recycle(danced); script.call("onDance", [event]); - if (event.cancelled) - return; + if (event.cancelled) return; - switch (curCharacter) - { - // hardcode custom dance animations here - default: - if (isDanceLeftDanceRight) - { - playAnim(((danced = !danced) ? 'danceLeft' : 'danceRight') + idleSuffix, DANCE); - } - else - playAnim('idle' + idleSuffix, DANCE); - } + if (isDanceLeftDanceRight) + playAnim(((danced = !danced) ? 'danceLeft' : 'danceRight') + idleSuffix, DANCE); + else + playAnim('idle' + idleSuffix, DANCE); } - public function tryDance() - { + public function tryDance() { switch (lastAnimContext) { case SING | MISS: if (lastHit + (Conductor.stepCrochet * holdTime) < Conductor.songPosition) @@ -258,96 +163,61 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset * Whenever the character should dance on beat or not. Set to false for `gf`, since the dance animation is automatically handled by PlayState. */ public var danceOnBeat:Bool = true; - public override function beatHit(curBeat:Int) { script.call("beatHit", [curBeat]); if (danceOnBeat && (curBeat + beatOffset) % beatInterval == 0 && !__lockAnimThisFrame) - { tryDance(); - } } - public override function stepHit(curStep:Int) { + public override function stepHit(curStep:Int) script.call("stepHit", [curStep]); - // nothing - } - - var __reverseDrawProcedure:Bool = false; + @:noCompletion var __reverseDrawProcedure:Bool = false; public override function getScreenBounds(?newRect:FlxRect, ?camera:FlxCamera):FlxRect { - if (__reverseDrawProcedure) - { + if (__reverseDrawProcedure) { scale.x *= -1; - var bounds = super.getScreenBounds(newRect, camera); + var bounds:FlxRect = super.getScreenBounds(newRect, camera); scale.x *= -1; return bounds; } return super.getScreenBounds(newRect, camera); } - public function isFlippedOffsets() { - return (isPlayer != playerOffsets) != (flipX != __baseFlipped); + public override function isOnScreen(?camera:FlxCamera):Bool { + if (debugMode) return true; + return super.isOnScreen(camera); } - var __drawingShadowFrame = false; - var __oldColorTransform = new ColorTransform(); + public function isFlippedOffsets() + return (isPlayer != playerOffsets) != (flipX != __baseFlipped); public override function draw() { - if (!__drawingShadowFrame && shadowFrame != null) { - __drawingShadowFrame = true; - - var oldFrame = _frame; - var oldPos = FlxPoint.get(frameOffset.x, frameOffset.y); - - __oldColorTransform.copyColorTransform(colorTransform); - - colorTransform.alphaMultiplier = 1; - colorTransform.alphaOffset = 0; - colorTransform.blueMultiplier = 0; - colorTransform.blueOffset = 25; - colorTransform.greenMultiplier = 0; - colorTransform.greenOffset = 25; - colorTransform.redMultiplier = 0; - colorTransform.redOffset = 25; - - _frame = shadowFrame.frame; - var o = getAnimOffset(shadowFrame.anim); - frameOffset.set(o.x, o.y); - super.draw(); - - _frame = oldFrame; - frameOffset.set(oldPos.x, oldPos.y); - - colorTransform.copyColorTransform(__oldColorTransform); - - oldPos.put(); - - __drawingShadowFrame = false; - } - - if (isFlippedOffsets()) - { + if (isFlippedOffsets()) { __reverseDrawProcedure = true; - flipX = !flipX; scale.x *= -1; + super.draw(); + flipX = !flipX; scale.x *= -1; - __reverseDrawProcedure = false; - } - else - super.draw(); + } else super.draw(); } - public override function playAnim(AnimName:String, Force:Bool = false, Context:PlayAnimContext = NONE, Reversed:Bool = false, Frame:Int = 0):Void - { + 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); + script.call("onPlaySingAnim", [event]); + if (!event.cancelled) + 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) { var event = EventManager.get(PlayAnimEvent).recycle(AnimName, Force, Reversed, Frame, Context); script.call("onPlayAnim", [event]); - if (event.cancelled) - return; + if (event.cancelled) return; super.playAnim(event.animName, event.force, event.context, event.reverse, event.startingFrame); @@ -356,50 +226,63 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset lastHit = Conductor.songPosition; } - public override function destroy() - { + public inline function getCameraPosition() { + var midpoint:FlxPoint = getMidpoint(); + var event = EventManager.get(PointEvent).recycle( + midpoint.x + (isPlayer ? -100 : 150) + globalOffset.x + cameraOffset.x, + midpoint.y - 100 + globalOffset.y + cameraOffset.y); + script.call("onGetCamPos", [event]); + + midpoint.put(); + return new FlxPoint(event.x, event.y); + } + + public override function destroy() { super.destroy(); cameraOffset.put(); globalOffset.put(); } - // FlxTrail Stuff for fixing position + @:noCompletion var __reverseTrailProcedure:Bool = false; - var __reverseTrailProcedure:Bool = false; - - /** - * When using trails on characters you should do `trail.beforeCache = char.beforeTrailCache;` - **/ - dynamic function beforeTrailCache() { - if (isFlippedOffsets()) - { + // When using trails on characters you should do `trail.beforeCache = char.beforeTrailCache;` + public dynamic function beforeTrailCache() + if (isFlippedOffsets()) { flipX = !flipX; scale.x *= -1; __reverseTrailProcedure = true; } - } - /** - * When using trails on characters you should do `trail.afterCache = char.afterTrailCache;` - **/ - dynamic function afterTrailCache() { - if (__reverseTrailProcedure) - { + // When using trails on characters you should do `trail.afterCache = char.afterTrailCache;` + public dynamic function afterTrailCache() + if (__reverseTrailProcedure) { flipX = !flipX; scale.x *= -1; __reverseTrailProcedure = false; } + + public function applyXML(xml:Access) { // just for now till i remake the dumb editor + gameOverCharacter = Character.FALLBACK_DEAD_CHARACTER; + cameraOffset.set(0, 0); + globalOffset.set(0, 0); + playerOffsets = false; + flipX = false; + holdTime = 4; + iconColor = null; + + animation.destroyAnimations(); + animDatas.clear(); + + __baseFlipped = false; + buildCharacter(xml); } - // Character editor and loading - - public function applyXML(xml:Access) { - this.xml = xml; // modders wassup + public inline function buildCharacter(xml:Access) { + this.xml = xml; // Modders wassup :D sprite = curCharacter; if (xml.x.exists("isPlayer")) playerOffsets = (xml.x.get("isPlayer") == "true"); - if (xml.x.exists("isGF")) isGF = (xml.x.get("isGF") == "true"); if (xml.x.exists("x")) globalOffset.x = Std.parseFloat(xml.x.get("x")); if (xml.x.exists("y")) globalOffset.y = Std.parseFloat(xml.x.get("y")); if (xml.x.exists("gameOverChar")) gameOverCharacter = xml.x.get("gameOverChar"); @@ -410,7 +293,7 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset if (xml.x.exists("icon")) icon = xml.x.get("icon"); if (xml.x.exists("color")) iconColor = FlxColor.fromString(xml.x.get("color")); if (xml.x.exists("scale")) { - var scale = Std.parseFloat(xml.x.get("scale")).getDefault(1); + var scale:Float = Std.parseFloat(xml.x.get("scale")).getDefault(1); this.scale.set(scale, scale); updateHitbox(); } @@ -420,71 +303,85 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset var hasInterval:Bool = xml.x.exists("interval"); if (hasInterval) beatInterval = Std.parseInt(xml.x.get("interval")); - var tempList = ["isPlayer", "isGF", "x", "y", "gameOverChar", "camx", "camy", "holdTime", "flipX", "icon", "color", "scale", "antialiasing", "sprite", "interval"]; - var atts = [for (i in xml.x.attributes()) i]; - for (i in atts) - if (!tempList.contains(i)) { - extra[i] = xml.x.get(i); - } - loadSprite(Paths.image('characters/$sprite')); - animation.destroyAnimations(); - animDatas.clear(); for (anim in xml.nodes.anim) - { XMLUtil.addXMLAnimation(this, anim); - } - fixChar(true, !hasInterval); + for (attribute in xml.x.attributes()) + if (!characterProperties.contains(attribute)) + extra[attribute] = xml.x.get(attribute); + + fixChar(__switchAnims, !hasInterval); dance(); } - public function buildXML(?animsOrder:Array):Xml { - var xml = Xml.createElement("character"); - xml.set("isPlayer", playerOffsets == true ? "true" : "false"); - xml.set("isGF", isGF == true ? "true" : "false"); - xml.set("x", Std.string(globalOffset.x)); - xml.set("y", Std.string(globalOffset.y)); - xml.set("gameOverChar", gameOverCharacter); - xml.set("camx", Std.string(cameraOffset.x)); - xml.set("camy", Std.string(cameraOffset.y)); - xml.set("holdTime", Std.string(holdTime)); - xml.set("flipX", Std.string(flipX)); - xml.set("icon", getIcon()); - if (iconColor != null) - xml.set("color", iconColor.toWebString()); - xml.set("scale", Std.string(scale.x)); - xml.set("antialiasing", antialiasing == true ? "true" : "false"); - xml.set("sprite", sprite); + public static var characterProperties:Array = [ + "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" + ]; - for (prop=>val in extra) { - xml.set(prop, Std.string(val)); - } + 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))); + + if (cameraOffset.x != 0) xml.set("camx", Std.string(FlxMath.roundDecimal(cameraOffset.x, 2))); + if (cameraOffset.y != 0) xml.set("camy", Std.string(FlxMath.roundDecimal(cameraOffset.y, 2))); + + if (holdTime != 4) xml.set("holdTime", Std.string(FlxMath.roundDecimal(holdTime, 4))); + + if (flipX) xml.set("flipX", Std.string(flipX)); + xml.set("icon", getIcon()); + + if (gameOverCharacter != Character.FALLBACK_DEAD_CHARACTER) xml.set("gameOverChar", gameOverCharacter); + if (iconColor != null) xml.set("color", iconColor.toWebString()); + + xml.set("sprite", sprite); + if (scale.x != 1) xml.set("scale", Std.string(FlxMath.roundDecimal(scale.x, 4))); + if (!antialiasing) xml.set("antialiasing", antialiasing == true ? "true" : "false"); + + if (playerOffsets) xml.set("isPlayer", playerOffsets == true ? "true" : "false"); var anims:Array = []; if (animsOrder != null) { for (name in animsOrder) if (animDatas.exists(name)) anims.push(animDatas.get(name)); } else - anims = [for (anim in animDatas) anim]; + anims = Lambda.array(animDatas); - for (anim in anims) - { + for (anim in anims) { var animXml:Xml = Xml.createElement('anim'); + animXml.attributeOrder = characterAnimProperties; + animXml.set("name", anim.name); animXml.set("anim", anim.anim); animXml.set("loop", Std.string(anim.loop)); - animXml.set("fps", Std.string(anim.fps)); + animXml.set("fps", Std.string(FlxMath.roundDecimal(anim.fps, 2))); + var offset:FlxPoint = getAnimOffset(anim.name); - animXml.set("x", Std.string(offset.x)); - animXml.set("y", Std.string(offset.y)); + animXml.set("x", Std.string(FlxMath.roundDecimal(offset.x, 2))); + animXml.set("y", Std.string(FlxMath.roundDecimal(offset.y, 2))); offset.putWeak(); + if (anim.indices.length > 0) animXml.set("indices", anim.indices.join(",")); + xml.addChild(animXml); } + for (name => val in extra) + if (!xml.attributeOrder.contains(name)) { + xml.attributeOrder.push(name); + xml.set(name, Std.string(val)); + } + this.xml = new Access(xml); return xml; } @@ -492,74 +389,72 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset public inline function getIcon() return (icon != null) ? icon : curCharacter; - public function getAnimOrder() { + public function getAnimOrder() return [for(a in xml.nodes.anim) if(a.has.name) a.att.name]; - } - // Getters / Setters - - @:noCompletion private function set_stunned(b:Bool) - { + @:noCompletion private function set_stunned(b:Bool) { __stunnedTime = 0; return stunned = b; } - // Backwards Compat - - /** - * Interval at which the character will dance (higher number = slower dance) - */ + // Interval at which the character will dance (higher number = slower dance) @:noCompletion public var danceInterval(get, set):Int; @:noCompletion private function set_danceInterval(v:Int) return beatInterval = v; @:noCompletion private function get_danceInterval() return beatInterval; - // Statics - public static function getIconFromCharName(?curCharacter:String) { - if(curCharacter == null) return "face"; - var icon = curCharacter; - while(true) { - switch (curCharacter) { - // case 'your-char': // To hardcode characters icons - default: - // load xml - var xmlPath = Paths.xml('characters/$curCharacter'); - if (!Assets.exists(xmlPath)) { - curCharacter = "bf"; - continue; - } + public static var FALLBACK_CHARACTER:String = "bf"; + public static var FALLBACK_DEAD_CHARACTER:String = "bf-dead"; + public static function getXMLFromCharName(character:OneOfTwo):Access { + var char:Character = null; + if (character is Character) { + char = cast(character, Character); + character = char.curCharacter; + } - var xml = null; - var plainXML = Assets.getText(xmlPath); - try { - var charXML = Xml.parse(plainXML).firstElement(); - if (charXML == null) throw new Exception("Missing \"character\" node in XML."); - xml = new Access(charXML); - } catch(e) { - Logs.trace('Error while loading character ${curCharacter}: ${e}', ERROR); - curCharacter = "bf"; - continue; - } + var xml:Access = null; + while (true) { + var xmlPath:String = Paths.xml('characters/$character'); + if (!Assets.exists(xmlPath)) { + character = FALLBACK_CHARACTER; + if (char != null) + char.curCharacter = character; + continue; + } - if (xml.x.exists("icon")) icon = xml.x.get("icon"); - } + var plainXML:String = Assets.getText(xmlPath); + try { + var charXML:Xml = Xml.parse(plainXML).firstElement(); + if (charXML == null) throw new Exception("Missing \"character\" node in XML."); + xml = new Access(charXML); + } catch (e) { + Logs.trace('Error while loading character ${character}: ${e}', ERROR); + + character = FALLBACK_CHARACTER; + if (char != null) + char.curCharacter = character; + continue; + } break; } + return xml; + } + + public static function getIconFromCharName(?character:String) { + if(character == null) return "face"; + var icon:String = character; + + var xml:Access = getXMLFromCharName(character); + if (xml != null && xml.x.exists("icon")) icon = xml.x.get("icon"); + return icon; } - public static function getList(?mods:Bool = false):Array { + public static function getList(?mods:Bool = false):Array return [ for (path in Paths.getFolderContent('data/characters/', true, mods ? MODS : BOTH)) - if (Path.extension(path) == "xml") Path.withoutDirectory(Path.withoutExtension(path)) + if (Path.extension(path) == "xml") CoolUtil.getFilename(path) ]; - } -} - -typedef CharacterShadowFrame = -{ - var anim:String; - var frame:FlxFrame; -} +} \ No newline at end of file diff --git a/source/haxe/xml/Printer.hx b/source/haxe/xml/Printer.hx new file mode 100644 index 00000000..ab2e4cde --- /dev/null +++ b/source/haxe/xml/Printer.hx @@ -0,0 +1,137 @@ +/* +* Copyright (C)2005-2019 Haxe Foundation +* +* Permission is hereby granted, free of charge, to any person obtaining a +* copy of this software and associated documentation files (the "Software"), +* to deal in the Software without restriction, including without limitation +* the rights to use, copy, modify, merge, publish, distribute, sublicense, +* and/or sell copies of the Software, and to permit persons to whom the +* Software is furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in +* all copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +* DEALINGS IN THE SOFTWARE. +*/ + +package haxe.xml; + +using StringTools; + +/** + This class provides utility methods to convert Xml instances to + String representation. +**/ +class Printer { + /** + Convert `Xml` to string representation. + + Set `pretty` to `true` to prettify the result. + **/ + static public function print(xml:Xml, ?pretty = false) { + var printer = new Printer(pretty); + printer.writeNode(xml, ""); + return printer.output.toString(); + } + + var output:StringBuf; + var pretty:Bool; + + function new(pretty) { + output = new StringBuf(); + this.pretty = pretty; + } + + function writeNode(value:Xml, tabs:String) { + switch (value.nodeType) { + case CData: + write(tabs + ""); + newline(); + case Comment: + var commentContent:String = value.nodeValue; + commentContent = ~/[\n\r\t]+/g.replace(commentContent, ""); + commentContent = ""; + write(tabs); + write(StringTools.trim(commentContent)); + newline(); + case Document: + for (child in value) { + writeNode(child, tabs); + } + case Element: + write(tabs + "<"); + write(value.nodeName); + + var attributes:Array = value.attributeOrder; + if (attributes == null) + attributes = [for (att in value.attributes()) att]; + + for (attribute in attributes) { + if (!value.exists(attribute) || value.get(attribute).trim() == "") continue; + + write(" " + attribute + "=\""); + write(StringTools.htmlEscape(value.get(attribute), true)); + write("\""); + } + if (hasChildren(value)) { + write(">"); + newline(); + for (child in value) { + writeNode(child, pretty ? tabs + "\t" : tabs); + } + write(tabs + ""); + newline(); + } else { + write("/>"); + newline(); + } + case PCData: + var nodeValue:String = value.nodeValue; + if (nodeValue.length != 0) { + write(tabs + StringTools.htmlEscape(nodeValue)); + newline(); + } + case ProcessingInstruction: + write(""); + newline(); + case DocType: + write(""); + newline(); + } + } + + inline function write(input:String) { + output.add(input); + } + + inline function newline() { + if (pretty) { + output.add("\n"); + } + } + + function hasChildren(value:Xml):Bool { + for (child in value) { + switch (child.nodeType) { + case Element, PCData: + return true; + case CData, Comment: + if (StringTools.ltrim(child.nodeValue).length != 0) { + return true; + } + case _: + } + } + return false; + } +} \ No newline at end of file