From 30d3be8d0143e23fb38f40314cce32223575ceda Mon Sep 17 00:00:00 2001 From: lunarcleint <88809950+lunarcleint@users.noreply.github.com> Date: Fri, 12 Apr 2024 21:35:36 -0700 Subject: [PATCH] clean up character.hx (+BETTER BUILD XML) --- source/Xml.hx | 410 ++++++++++++++++++++++++++++++ source/funkin/game/Character.hx | 433 +++++++++++--------------------- source/haxe/xml/Printer.hx | 137 ++++++++++ 3 files changed, 696 insertions(+), 284 deletions(-) create mode 100644 source/Xml.hx create mode 100644 source/haxe/xml/Printer.hx 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/game/Character.hx b/source/funkin/game/Character.hx index fee410de..ad11614a 100644 --- a/source/funkin/game/Character.hx +++ b/source/funkin/game/Character.hx @@ -1,5 +1,6 @@ package funkin.game; +import flixel.util.typeLimit.OneOfTwo; import flixel.graphics.frames.FlxFrame; import flixel.math.FlxPoint; import flixel.math.FlxRect; @@ -26,13 +27,7 @@ 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 curCharacter:String = 'bf'; public var sprite:String = 'bf'; @@ -46,39 +41,19 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset public var iconColor:Null = null; public var gameOverCharacter:String = "bf-dead"; - public var cameraOffset:FlxPoint = new FlxPoint(0, 0); - public var globalOffset:FlxPoint = new FlxPoint(0, 0); + public var cameraOffset:FlxPoint = FlxPoint.get(); + public var globalOffset:FlxPoint = FlxPoint.get(); public var script:Script; public var xml:Access; - public var shadowFrame:CharacterShadowFrame; public var idleSuffix:String = ""; + public var stunned(default, set):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 __stunnedTime:Float = 0; + @:noCompletion var __lockAnimThisFrame:Bool = false; - 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 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) { super(x, y); animOffsets = new Map(); @@ -87,82 +62,26 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset 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); + + script = Script.create(Paths.script(Path.withoutExtension(Paths.xml('characters/$curCharacter')), null, true)); + 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) - { + public function fixChar(switchAnims:Bool = false, autoInterval:Bool = false) { if ((isDanceLeftDanceRight = hasAnimation("danceLeft") && hasAnimation("danceRight")) && autoInterval) beatInterval = 1; - // 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 evedince :skull: - if (isPlayer != playerOffsets && switchAnims) - { + if (isPlayer != playerOffsets && switchAnims) { // character is flipped CoolUtil.switchAnimFrames(animation.getByName('singRIGHT'), animation.getByName('singLEFT')); CoolUtil.switchAnimFrames(animation.getByName('singRIGHTmiss'), animation.getByName('singLEFTmiss')); @@ -176,15 +95,13 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset __baseFlipped = flipX; } - var __baseFlipped:Bool = false; - var isDanceLeftDanceRight:Bool = false; + @:noCompletion var __baseFlipped:Bool = false; + @:noCompletion var isDanceLeftDanceRight:Bool = false; - override function update(elapsed:Float) - { + override function update(elapsed:Float) { super.update(elapsed); script.call("update", [elapsed]); - if (stunned) - { + if (stunned) { __stunnedTime += elapsed; if (__stunnedTime > 5 / 60) stunned = false; @@ -198,33 +115,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) @@ -244,76 +148,32 @@ 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() { + public function isFlippedOffsets() return (isPlayer != playerOffsets) != (flipX != __baseFlipped); - } - - var __drawingShadowFrame = false; - var __oldColorTransform = new ColorTransform(); 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; @@ -323,17 +183,22 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset 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); @@ -342,46 +207,51 @@ 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 + animation.destroyAnimations(); + animDatas.clear(); + + 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"); @@ -395,7 +265,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(); } @@ -405,45 +275,39 @@ 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", "x", "y", "gameOverChar", "camx", "camy", "holdTime", "flipX", "icon", "color", "scale", "antialiasing", "sprite", "interval"]; - var atts = xml.x.attributes(); - 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); dance(); } - public function buildXML(?animsOrder:Array):Xml { - var xml = Xml.createElement("character"); - xml.set("isPlayer", playerOffsets == 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)); + public inline function buildXML(?animsOrder:Array):Xml { + var xml:Xml = Xml.createElement("character"); + + xml.set("x", Std.string(FlxMath.roundDecimal(globalOffset.x, 2))); + xml.set("y", Std.string(FlxMath.roundDecimal(globalOffset.y, 2))); + + xml.set("camx", Std.string(FlxMath.roundDecimal(cameraOffset.x, 2))); + xml.set("camy", Std.string(FlxMath.roundDecimal(cameraOffset.y, 2))); + + xml.set("holdTime", Std.string(FlxMath.roundDecimal(holdTime, 4))); + 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); - for (prop=>val in extra) { - xml.set(prop, Std.string(val)); - } + xml.set("gameOverChar", gameOverCharacter); + if (iconColor != null) xml.set("color", iconColor.toWebString()); + + xml.set("sprite", sprite); + xml.set("scale", Std.string(FlxMath.roundDecimal(scale.x, 4))); + xml.set("antialiasing", antialiasing == true ? "true" : "false"); + + xml.set("isPlayer", playerOffsets == true ? "true" : "false"); + + xml.attributeOrder = ["x", "y", "sprite", "scale", "antialiasing", "flipX", "camx", "camy", "isPlayer", "icon", "color", "gameOverChar", "holdTime"]; var anims:Array = []; if (animsOrder != null) { @@ -452,20 +316,24 @@ class Character extends FunkinSprite implements IBeatReceiver implements IOffset } else anims = Lambda.array(animDatas); - for (anim in anims) - { + for (anim in anims) { var animXml:Xml = Xml.createElement('anim'); 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)); - offset.putWeak(); + animXml.set("x", Std.string(FlxMath.roundDecimal(offset.x, 2))); + animXml.set("y", Std.string(FlxMath.roundDecimal(offset.y, 2))); + if (anim.indices.length > 0) animXml.set("indices", anim.indices.join(",")); + + animXml.attributeOrder = ["name", "anim", "x", "y", "fps", "loop", "indices"]; xml.addChild(animXml); + + offset.putWeak(); } this.xml = new Access(xml); @@ -475,74 +343,71 @@ 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 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)) ]; - } -} - -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