Cleaned up some code

This commit is contained in:
NeeEoo
2023-03-20 20:34:50 +01:00
parent 7c091445c2
commit c95c1e2975
28 changed files with 1390 additions and 1361 deletions
+2 -1
View File
@@ -2,5 +2,6 @@ export/
dump/
latest/windows/obj/
latest/windows/haxe/
.vscode/
.vscode/*
!.vscode/settings.json
.haxelib/
+4
View File
@@ -0,0 +1,4 @@
{
"editor.detectIndentation": false,
"editor.insertSpaces": false
}
+103 -103
View File
@@ -51,12 +51,12 @@ class Stage3DProxy extends EventDispatcher
public var bufferClear(get, set):Bool;
public var mouse3DManager(get, set):Mouse3DManager;
public var touch3DManager(get, set):Touch3DManager;
private static var _frameEventDriver:Shape = new Shape();
@:allow(away3d) private var _context3D:Context3D;
@:allow(away3d) private var _stage3DIndex:Int = -1;
private var _usesSoftwareRendering:Bool;
private var _profile:String;
private var _stage3D:Stage3D;
@@ -83,46 +83,46 @@ class Stage3DProxy extends EventDispatcher
private var _bufferClear:Bool;
private var _mouse3DManager:Mouse3DManager;
private var _touch3DManager:Touch3DManager;
private function notifyViewportUpdated():Void
{
if (_viewportDirty)
return;
_viewportDirty = true;
if (!hasEventListener(Stage3DEvent.VIEWPORT_UPDATED))
return;
//TODO: investigate bug causing coercion error
//if (!_viewportUpdated)
_viewportUpdated = new Stage3DEvent(Stage3DEvent.VIEWPORT_UPDATED);
dispatchEvent(_viewportUpdated);
}
private function notifyEnterFrame():Void
{
if (!hasEventListener(Event.ENTER_FRAME))
return;
if (_enterFrame == null)
_enterFrame = new Event(Event.ENTER_FRAME);
dispatchEvent(_enterFrame);
}
private function notifyExitFrame():Void
{
if (!hasEventListener(Event.EXIT_FRAME))
return;
if (_exitFrame == null)
_exitFrame = new Event(Event.EXIT_FRAME);
dispatchEvent(_exitFrame);
}
/**
* Creates a Stage3DProxy object. This method should not be called directly. Creation of Stage3DProxy objects should
* be handled by Stage3DManager.
@@ -134,7 +134,7 @@ class Stage3DProxy extends EventDispatcher
public function new(stage3DIndex:Int, stage3D:Stage3D, stage3DManager:Stage3DManager, forceSoftware:Bool = false, profile:String = "baseline")
{
vertexBufferCount = indexBufferCount = drawTriangleCount = 0;
_stage3DIndex = stage3DIndex;
_stage3D = stage3D;
_stage3D.x = 0;
@@ -143,15 +143,15 @@ class Stage3DProxy extends EventDispatcher
_stage3DManager = stage3DManager;
_viewPort = new Rectangle();
_enableDepthAndStencil = true;
super();
// whatever happens, be sure this has highest priority
_stage3D.addEventListener(Event.CONTEXT3D_CREATE, onContext3DUpdate, false, 1000, false);
this.forceSoftware = forceSoftware;
this._profile = profile;
if (_stage3D.context3D != null) {
onContext3DUpdate(null);
}
@@ -159,14 +159,14 @@ class Stage3DProxy extends EventDispatcher
requestContext(forceSoftware, _profile);
}
}
private var forceSoftware:Bool;
private function get_profile():String
{
return _profile;
}
/**
* Disposes the Stage3DProxy object, freeing the Context3D attached to the Stage3D.
*/
@@ -193,22 +193,22 @@ class Stage3DProxy extends EventDispatcher
if(backBufferHeight<50) backBufferHeight = 50;
var oldWidth:Int = _backBufferWidth;
var oldHeight:Int = _backBufferHeight;
_backBufferWidth = backBufferWidth;
_backBufferHeight = backBufferHeight;
_viewPort.width = backBufferWidth;
_viewPort.height = backBufferHeight;
if (oldWidth != _backBufferWidth || oldHeight != _backBufferHeight)
notifyViewportUpdated();
_antiAlias = antiAlias;
_enableDepthAndStencil = enableDepthAndStencil;
if (_context3D != null)
_context3D.configureBackBuffer(backBufferWidth, backBufferHeight, antiAlias, enableDepthAndStencil, true, true);
}
/*
* Indicates whether the depth and stencil buffer is used
*/
@@ -216,24 +216,24 @@ class Stage3DProxy extends EventDispatcher
{
return _enableDepthAndStencil;
}
private function set_enableDepthAndStencil(enableDepthAndStencil:Bool):Bool
{
_enableDepthAndStencil = enableDepthAndStencil;
_backBufferDirty = true;
return enableDepthAndStencil;
}
private function get_renderTarget():TextureBase
{
return _renderTarget;
}
private function get_renderSurfaceSelector():Int
{
return _renderSurfaceSelector;
}
public function setRenderTarget(target:TextureBase, enableDepthAndStencil:Bool = false, surfaceSelector:Int = 0):Void
{
if (_renderTarget == target && surfaceSelector == _renderSurfaceSelector && _enableDepthAndStencil == enableDepthAndStencil)
@@ -241,13 +241,13 @@ class Stage3DProxy extends EventDispatcher
_renderTarget = target;
_renderSurfaceSelector = surfaceSelector;
_enableDepthAndStencil = enableDepthAndStencil;
if (target != null)
_context3D.setRenderToTexture(target, enableDepthAndStencil, _antiAlias, surfaceSelector);
else
_context3D.setRenderToBackBuffer();
}
/*
* Clear and reset the back buffer when using a shared context
*/
@@ -255,21 +255,21 @@ class Stage3DProxy extends EventDispatcher
{
if (_context3D == null)
return;
if (_backBufferDirty) {
configureBackBuffer(_backBufferWidth, _backBufferHeight, _antiAlias, _enableDepthAndStencil);
_backBufferDirty = false;
}
_context3D.clear(
((_color >> 16) & 0xff)/255.0,
((_color >> 8) & 0xff)/255.0,
(_color & 0xff)/255.0,
((_color >> 24) & 0xff)/255.0);
_bufferClear = true;
}
/*
* Display the back rendering buffer
*/
@@ -277,15 +277,15 @@ class Stage3DProxy extends EventDispatcher
{
if (_context3D == null)
return;
_context3D.present();
_activeProgram3D = null;
if (_mouse3DManager != null)
_mouse3DManager.fireMouseEvents();
}
/**
* Registers an event listener object with an EventDispatcher object so that the listener receives notification of an event. Special case for enterframe and exitframe events - will switch Stage3DProxy into automatic render mode.
* You can register event listeners on all nodes in the display list for a specific type of event, phase, and priority.
@@ -299,11 +299,11 @@ class Stage3DProxy extends EventDispatcher
override public function addEventListener(type:String, listener:Dynamic -> Void, useCapture:Bool = false, priority:Int = 0, useWeakReference:Bool = false):Void
{
super.addEventListener(type, listener, useCapture, priority, useWeakReference);
if ((type == Event.ENTER_FRAME || type == Event.EXIT_FRAME) && !_frameEventDriver.hasEventListener(Event.ENTER_FRAME))
_frameEventDriver.addEventListener(Event.ENTER_FRAME, onEnterFrame, useCapture, priority, useWeakReference);
}
/**
* Removes a listener from the EventDispatcher object. Special case for enterframe and exitframe events - will switch Stage3DProxy out of automatic render mode.
* If there is no matching listener registered with the EventDispatcher object, a call to this method has no effect.
@@ -315,24 +315,24 @@ class Stage3DProxy extends EventDispatcher
override public function removeEventListener(type:String, listener:Dynamic -> Void, useCapture:Bool = false):Void
{
super.removeEventListener(type, listener, useCapture);
// Remove the main rendering listener if no EnterFrame listeners remain
if (!hasEventListener(Event.ENTER_FRAME) && !hasEventListener(Event.EXIT_FRAME) && _frameEventDriver.hasEventListener(Event.ENTER_FRAME))
_frameEventDriver.removeEventListener(Event.ENTER_FRAME, onEnterFrame, useCapture);
}
private function get_scissorRect():Rectangle
{
return _scissorRect;
}
private function set_scissorRect(value:Rectangle):Rectangle
{
_scissorRect = value;
_context3D.setScissorRectangle(_scissorRect);
return value;
}
/**
* The index of the Stage3D which is managed by this instance of Stage3DProxy.
*/
@@ -340,7 +340,7 @@ class Stage3DProxy extends EventDispatcher
{
return _stage3DIndex;
}
/**
* The base Stage3D object associated with this proxy.
*/
@@ -348,7 +348,7 @@ class Stage3DProxy extends EventDispatcher
{
return _stage3D;
}
/**
* The Context3D object associated with the given Stage3D object.
*/
@@ -356,7 +356,7 @@ class Stage3DProxy extends EventDispatcher
{
return _context3D;
}
/**
* The driver information as reported by the Context3D object (if any)
*/
@@ -364,7 +364,7 @@ class Stage3DProxy extends EventDispatcher
{
return (_context3D != null)? _context3D.driverInfo : null;
}
/**
* Indicates whether the Stage3D managed by this proxy is running in software mode.
* Remember to wait for the CONTEXT3D_CREATED event before checking this property,
@@ -374,7 +374,7 @@ class Stage3DProxy extends EventDispatcher
{
return _usesSoftwareRendering;
}
/**
* The x position of the Stage3D.
*/
@@ -382,18 +382,18 @@ class Stage3DProxy extends EventDispatcher
{
return _stage3D.x;
}
private function set_x(value:Float):Float
{
if (_viewPort.x == value)
return value;
_stage3D.x = _viewPort.x = value;
notifyViewportUpdated();
return value;
}
/**
* The y position of the Stage3D.
*/
@@ -401,18 +401,18 @@ class Stage3DProxy extends EventDispatcher
{
return _stage3D.y;
}
private function set_y(value:Float):Float
{
if (_viewPort.y == value)
return value;
_stage3D.y = _viewPort.y = value;
notifyViewportUpdated();
return value;
}
/**
* The width of the Stage3D.
*/
@@ -420,7 +420,7 @@ class Stage3DProxy extends EventDispatcher
{
return _backBufferWidth;
}
private function set_width(width:Int):Int
{
if (_viewPort.width == width)
@@ -433,7 +433,7 @@ class Stage3DProxy extends EventDispatcher
notifyViewportUpdated();
return width;
}
/**
* The height of the Stage3D.
*/
@@ -441,7 +441,7 @@ class Stage3DProxy extends EventDispatcher
{
return _backBufferHeight;
}
private function set_height(height:Int):Int
{
if (_viewPort.height == height)
@@ -450,11 +450,11 @@ class Stage3DProxy extends EventDispatcher
if(height<50) height = 50;
_viewPort.height = _backBufferHeight = height;
_backBufferDirty = true;
notifyViewportUpdated();
return height;
}
/**
* The antiAliasing of the Stage3D.
*/
@@ -462,24 +462,24 @@ class Stage3DProxy extends EventDispatcher
{
return _antiAlias;
}
private function set_antiAlias(antiAlias:Int):Int
{
_antiAlias = antiAlias;
_backBufferDirty = true;
return antiAlias;
}
/**
* A viewPort rectangle equivalent of the Stage3D size and position.
*/
private function get_viewPort():Rectangle
{
_viewportDirty = false;
return _viewPort;
}
/**
* The background color of the Stage3D.
*/
@@ -487,13 +487,13 @@ class Stage3DProxy extends EventDispatcher
{
return _color;
}
private function set_color(color:Int):Int
{
_color = color;
return color;
}
/**
* The visibility of the Stage3D.
*/
@@ -501,13 +501,13 @@ class Stage3DProxy extends EventDispatcher
{
return _stage3D.visible;
}
private function set_visible(value:Bool):Bool
{
_stage3D.visible = value;
return value;
}
/**
* The freshly cleared state of the backbuffer before any rendering
*/
@@ -515,13 +515,13 @@ class Stage3DProxy extends EventDispatcher
{
return _bufferClear;
}
private function set_bufferClear(newBufferClear:Bool):Bool
{
_bufferClear = newBufferClear;
return newBufferClear;
}
/*
* Access to fire mouseevents across multiple layered view3D instances
*/
@@ -529,24 +529,24 @@ class Stage3DProxy extends EventDispatcher
{
return _mouse3DManager;
}
private function set_mouse3DManager(value:Mouse3DManager):Mouse3DManager
{
_mouse3DManager = value;
return value;
}
private function get_touch3DManager():Touch3DManager
{
return _touch3DManager;
}
private function set_touch3DManager(value:Touch3DManager):Touch3DManager
{
_touch3DManager = value;
return value;
}
/**
* Frees the Context3D associated with this Stage3DProxy.
*/
@@ -554,11 +554,11 @@ class Stage3DProxy extends EventDispatcher
{
if (_context3D != null) {
dispatchEvent(new Stage3DEvent(Stage3DEvent.CONTEXT3D_DISPOSED));
_context3D.dispose();
_context3D.dispose();
}
_context3D = null;
}
/*
* Called whenever the Context3D is retrieved or lost.
* @param event The event dispatched.
@@ -569,7 +569,7 @@ class Stage3DProxy extends EventDispatcher
var hadContext:Bool = (_context3D != null);
_context3D = _stage3D.context3D;
_context3D.enableErrorChecking = Debug.active;
_usesSoftwareRendering = (_context3D.driverInfo.indexOf('Software') == 0);
// Only configure back buffer if width and height have been set,
@@ -577,15 +577,15 @@ class Stage3DProxy extends EventDispatcher
// invoked for the first time.
if (_backBufferWidth > 0 && _backBufferHeight > 0)
_context3D.configureBackBuffer(_backBufferWidth, _backBufferHeight, _antiAlias, _enableDepthAndStencil, true, true);
// Dispatch the appropriate event depending on whether context was
// created for the first time or recreated after a device loss.
dispatchEvent(new Stage3DEvent(hadContext? Stage3DEvent.CONTEXT3D_RECREATED : Stage3DEvent.CONTEXT3D_CREATED));
} else
throw new Error("Rendering context lost!");
}
/**
* Requests a Context3D object to attach to the managed Stage3D.
*/
@@ -598,7 +598,7 @@ class Stage3DProxy extends EventDispatcher
if (!_usesSoftwareRendering)
_usesSoftwareRendering = forceSoftware;
_profile = profile;
// ugly stuff for backward compatibility
var renderMode:Context3DRenderMode = forceSoftware? Context3DRenderMode.SOFTWARE : Context3DRenderMode.AUTO;
if (profile == "baseline")
@@ -610,10 +610,10 @@ class Stage3DProxy extends EventDispatcher
throw "An error occurred creating a context using the given profile. Profiles are not supported for the SDK this was compiled with.";
}
}
_contextRequested = true;
}
/**
* The Enter_Frame handler for processing the proxy.ENTER_FRAME and proxy.EXIT_FRAME event handlers.
* Typically the proxy.ENTER_FRAME listener would render the layers for this Stage3D instance.
@@ -622,20 +622,20 @@ class Stage3DProxy extends EventDispatcher
{
if (_context3D == null)
return;
// Clear the stage3D instance
clear();
//notify the enterframe listeners
notifyEnterFrame();
// Call the present() to render the frame
present();
//notify the exitframe listeners
notifyExitFrame();
}
public function recoverFromDisposal():Bool
{
if (_context3D == null)
@@ -647,29 +647,29 @@ class Stage3DProxy extends EventDispatcher
}
return true;
}
public function clearDepthBuffer():Void
{
if (_context3D == null)
return;
_context3D.clear(0, 0, 0, 1, 1, 0, cast Context3DClearMask.DEPTH);
}
/*
Moving all creation methods here, so we can trace the usages of vertexbuffers or indexbuffers.
Flash will throw the ERROR, when the vertexbuffer creation reached 4096..
*/
public static var vertexBufferCount(default, default) : UInt;
public static var indexBufferCount(default, default) : UInt;
public static var drawTriangleCount(default, default) : UInt;
private static var _vbUploadCount : UInt = 0;
private static var _ibUploadCount : UInt = 0;
private static var _bmpUploadCount : UInt = 0;
private static var _atfUploadCount : UInt = 0;
public function createVertexBuffer(numVertices:Int, data32PerVertex:Int):VertexBuffer3D
{
vertexBufferCount++;
@@ -681,31 +681,31 @@ class Stage3DProxy extends EventDispatcher
vb.dispose();
vertexBufferCount--;
}
public function createIndexBuffer(numIndices:Int):IndexBuffer3D
{
indexBufferCount++;
return _context3D.createIndexBuffer(numIndices);
}
public static function disposeIndexBuffer(ib:IndexBuffer3D):Void
{
ib.dispose();
indexBufferCount--;
}
public function drawTriangles(indexBuffer:IndexBuffer3D, firstIndex:Int = 0, numTriangles:Int = -1)
{
drawTriangleCount++;
_context3D.drawTriangles(indexBuffer, firstIndex, numTriangles);
}
public static function uploadVertexBufferFromVector(vb:VertexBuffer3D, data:Vector<Float>, startVertex:Int, numVertices:Int):Void
{
vb.uploadFromVector(data, startVertex, numVertices);
_vbUploadCount++;
}
public static function uploadIndexBufferFromVector(ib:IndexBuffer3D, data:Vector<UInt>, startOffset:Int, count:Int):Void
{
ib.uploadFromVector(data, startOffset, count);
-1
View File
@@ -40,7 +40,6 @@ class Flx3DCamera extends FlxCamera {
super(X, Y, Width, Height, DefaultZoom);
__cur3DStageID = __3DIDS++;
view = new View3D();
view.width = this.width;
view.height = this.height;
+1 -1
View File
@@ -7,7 +7,7 @@ import flixel.FlxG;
/**
* @author lunarclient
* @see https://twitter.com/lunarcleint
*
*
* Help from Ne_Eo
* @see https://twitter.com/Ne_Eo_Twitch
*/
+28 -28
View File
@@ -38,14 +38,14 @@ class FlxAnimateFrames extends FlxAtlasFrames
public var parents:Array<FlxGraphic>;
/**
* Parses the spritemaps into small sprites to use in the animation.
*
*
* @param Path Where the Sprites are, normally you use it once when calling FlxAnimate already
* @return new sliced limbs for you to use ;)
*/
public static function fromTextureAtlas(Path:String):FlxAtlasFrames
{
var frames:FlxAnimateFrames = new FlxAnimateFrames();
if (zip != null || haxe.io.Path.extension(Path) == "zip")
{
#if html5
@@ -54,7 +54,7 @@ class FlxAnimateFrames extends FlxAtlasFrames
#end
var imagemap:Map<String, Bytes> = new Map();
var jsonMap:Map<String, AnimateAtlas> = new Map();
var thing = (zip != null) ? zip : Zip.unzip(Zip.readZip(Assets.getBytes(Path)));
var thing = (zip != null) ? zip : Zip.unzip(Zip.readZip(Assets.getBytes(Path)));
for (list in thing)
{
if (haxe.io.Path.extension(list.fileName) == "json")
@@ -182,7 +182,7 @@ class FlxAnimateFrames extends FlxAtlasFrames
var rotated = (texture.has.rotated && texture.att.rotated == "true");
var flipX = (texture.has.flipX && texture.att.flipX == "true");
var flipY = (texture.has.flipY && texture.att.flipY == "true");
var rect = FlxRect.get(Std.parseFloat(texture.att.x), Std.parseFloat(texture.att.y), Std.parseFloat(width),
Std.parseFloat(height));
@@ -203,7 +203,7 @@ class FlxAnimateFrames extends FlxAtlasFrames
return frames;
}
/**
*
*
* @param Path the Json in specific, can be the path of it or the actual json
* @param Image the image which the file is referencing **WARNING:** if you set the path as a json, it's obligatory to set the image!
* @return A new instance of `FlxAtlasFrames`
@@ -294,7 +294,7 @@ class FlxAnimateFrames extends FlxAtlasFrames
return null;
}
}
var graphic:FlxGraphic = FlxG.bitmap.add(Image, false);
if (graphic == null)
@@ -438,7 +438,7 @@ class FlxAnimateFrames extends FlxAtlasFrames
Frames.addAtlasFrame(frameRect, sourceSize, offset, name, angle);
}
static function starlingHelper(FrameName:String, FrameData:Dynamic, Frames:FlxAtlasFrames):Void
{
var rotated:Bool = FrameData.rotated;
@@ -474,7 +474,7 @@ class FlxAnimateFrames extends FlxAtlasFrames
matrix.translate(0, height);
}
sprite.draw(SpriteMap, matrix);
@:privateAccess
var curFrame = new FlxFrame(FlxG.bitmap.add(sprite));
curFrame.name = limb.name;
@@ -482,7 +482,7 @@ class FlxAnimateFrames extends FlxAtlasFrames
curFrame.frame = new FlxRect(0,0, width, height);
return curFrame;
}
static function texturePackerHelper(FrameName:String, FrameData:Dynamic, Frames:FlxAtlasFrames):Void
{
var rotated:Bool = FrameData.rotated;
@@ -508,7 +508,7 @@ class FlxAnimateFrames extends FlxAtlasFrames
return a < b ? b : a;
}
// code made by noonat 11 years ago, not mine lol
class PropertyList
class PropertyList
{
static var _dateRegex:EReg = ~/(\d{4}-\d{2}-\d{2})(?:T(\d{2}:\d{2}:\d{2})Z)?/;
@@ -517,20 +517,20 @@ class PropertyList
* the property list is empty, an empty object will be returned.
* @param text Text contents of the property list file.
*/
static public function parse(text:String):Dynamic
static public function parse(text:String):Dynamic
{
var fast = new Access(Xml.parse(text).firstElement());
return fast.hasNode.dict ? parseDict(fast.node.dict) : {};
}
static function parseDate(text:String):Date
static function parseDate(text:String):Date
{
if (!_dateRegex.match(text))
if (!_dateRegex.match(text))
{
throw 'Invalid date "' + text + '" (only yyyy-mm-dd and yyyy-mm-ddThh:mm:ssZ supported)';
}
text = _dateRegex.matched(1);
if (_dateRegex.matched(2) != null)
if (_dateRegex.matched(2) != null)
{
text += ' ' + _dateRegex.matched(2);
}
@@ -541,12 +541,12 @@ class PropertyList
{
var key:String = null;
var result:Dynamic = {};
for (childNode in node.elements)
for (childNode in node.elements)
{
if (childNode.name == 'key')
if (childNode.name == 'key')
{
key = childNode.innerData;
} else if (key != null)
} else if (key != null)
{
Reflect.setField(result, key, parseValue(childNode));
}
@@ -557,21 +557,21 @@ class PropertyList
static function parseValue(node:Access):Dynamic
{
var value:Dynamic = null;
switch (node.name)
switch (node.name)
{
case 'array':
value = new Array<Dynamic>();
for (childNode in node.elements)
for (childNode in node.elements)
{
value.push(parseValue(childNode));
}
case 'dict':
value = parseDict(node);
case 'date':
value = parseDate(node.innerData);
case 'string':
var thing:Dynamic = node.innerData;
if (thing.charAt(0) == "{")
@@ -583,16 +583,16 @@ class PropertyList
value = thing;
case 'data':
value = node.innerData;
case 'true':
value = true;
case 'false':
value = false;
case 'real':
value = Std.parseFloat(node.innerData);
case 'integer':
value = Std.parseInt(node.innerData);
}
@@ -602,7 +602,7 @@ class PropertyList
typedef JSJson =
{
var images:Array<String>;
var frames:Array<Array<Int>>;
var frames:Array<Array<Int>>;
}
typedef FlxSparrow = OneOfTwo<String, Xml>;
typedef FlxJson = OneOfTwo<String, JsonNormal>;
@@ -612,7 +612,7 @@ typedef JsonNormal =
frames:Dynamic,
meta:Meta
}
typedef Plist =
typedef Plist =
{
frames:Dynamic,
metadata:Dynamic
+1 -2
View File
@@ -85,14 +85,13 @@ class Highscore
{
songScores = CoolUtil.getDefault(FlxG.save.data.songScores, new Map<String, SongScore>());
weekScores = CoolUtil.getDefault(FlxG.save.data.weekScores, new Map<String, SongScore>());
for(k=>e in songScores)
if (e is Int)
songScores.remove(k);
}
}
typedef SongScore = {
@:optional var score:Int;
@:optional var accuracy:Float;
+1 -1
View File
@@ -27,7 +27,7 @@ class ScriptsMacro {
#if !web
Compiler.include("haxe.extern");
#end
Compiler.include("scripting");
// FOR ABSTRACTS
+1 -1
View File
@@ -10,7 +10,7 @@ class Options
{
@:dox(hide) public static var __save:FlxSave;
@:dox(hide) private static var __eventAdded = false;
/**
* SETTINGS
*/
+18 -18
View File
@@ -6,28 +6,28 @@ import hscript.IHScriptCustomBehaviour;
/**
* Class for custom shaders.
*
*
* To create one, create a `shaders` folder in your assets/mod folder, then add a file named `my-shader.frag` or/and `my-shader.vert`.
*
*
* Non-existent shaders will only load the default one, and throw a warning in the console.
*
*
* To access the shader's uniform variables, use `shader.variable`
*/
class CustomShader extends FunkinShader {
/**
* Creates a new custom shader
* @param name Name of the frag and vert files.
* @param glslVersion GLSL version to use. Defaults to `120`.
*/
public function new(name:String, glslVersion:String = "120") {
var fragShaderPath = Paths.fragShader(name);
var vertShaderPath = Paths.vertShader(name);
var fragCode = Assets.exists(fragShaderPath) ? Assets.getText(fragShaderPath) : null;
var vertCode = Assets.exists(vertShaderPath) ? Assets.getText(vertShaderPath) : null;
/**
* Creates a new custom shader
* @param name Name of the frag and vert files.
* @param glslVersion GLSL version to use. Defaults to `120`.
*/
public function new(name:String, glslVersion:String = "120") {
var fragShaderPath = Paths.fragShader(name);
var vertShaderPath = Paths.vertShader(name);
var fragCode = Assets.exists(fragShaderPath) ? Assets.getText(fragShaderPath) : null;
var vertCode = Assets.exists(vertShaderPath) ? Assets.getText(vertShaderPath) : null;
if (fragCode == null && vertCode == null)
Logs.trace('Shader "$name" couldn\'t be found.', ERROR);
super(fragCode, vertCode, glslVersion);
}
if (fragCode == null && vertCode == null)
Logs.trace('Shader "$name" couldn\'t be found.', ERROR);
super(fragCode, vertCode, glslVersion);
}
}
File diff suppressed because it is too large Load Diff
+18 -18
View File
@@ -5,27 +5,27 @@ import flixel.system.FlxAssets.FlxShader;
class OverlayShader extends FlxShader
{
@:glFragmentSource('
#pragma header
uniform vec4 uBlendColor;
#pragma header
uniform vec4 uBlendColor;
vec3 blendLighten(base:Vec3, blend:Vec3) : Vec3 {
return mix(
1.0 - 2.0 * (1.0 - base) * (1.0 - blend),
2.0 * base * blend,
step( base, vec3(0.5) )
);
}
vec3 blendLighten(base:Vec3, blend:Vec3) : Vec3 {
return mix(
1.0 - 2.0 * (1.0 - base) * (1.0 - blend),
2.0 * base * blend,
step( base, vec3(0.5) )
);
}
vec4 blendLighten(vec4 base, vec4 blend, float opacity)
{
return (blendLighten(base, blend) * opacity + base * (1.0 - opacity));
}
vec4 blendLighten(vec4 base, vec4 blend, float opacity)
{
return (blendLighten(base, blend) * opacity + base * (1.0 - opacity));
}
void main()
{
vec4 base = texture2D(bitmap, openfl_TextureCoordv);
gl_FragColor = blendLighten(base, uBlendColor, uBlendColor.a);
}')
void main()
{
vec4 base = texture2D(bitmap, openfl_TextureCoordv);
gl_FragColor = blendLighten(base, uBlendColor, uBlendColor.a);
}')
public function new()
{
super();
+62 -62
View File
@@ -62,70 +62,70 @@ class WiggleEffect
class WiggleShader extends FlxShader
{
@:glFragmentSource('
#pragma header
//uniform float tx, ty; // x,y waves phase
uniform float uTime;
const int EFFECT_TYPE_DREAMY = 0;
const int EFFECT_TYPE_WAVY = 1;
const int EFFECT_TYPE_HEAT_WAVE_HORIZONTAL = 2;
const int EFFECT_TYPE_HEAT_WAVE_VERTICAL = 3;
const int EFFECT_TYPE_FLAG = 4;
uniform int effectType;
/**
* How fast the waves move over time
*/
uniform float uSpeed;
/**
* Number of waves over time
*/
uniform float uFrequency;
/**
* How much the pixels are going to stretch over the waves
*/
uniform float uWaveAmplitude;
#pragma header
//uniform float tx, ty; // x,y waves phase
uniform float uTime;
vec2 sineWave(vec2 pt)
{
float x = 0.0;
float y = 0.0;
if (effectType == EFFECT_TYPE_DREAMY)
{
float offsetX = sin(pt.y * uFrequency + uTime * uSpeed) * uWaveAmplitude;
pt.x += offsetX; // * (pt.y - 1.0); // <- Uncomment to stop bottom part of the screen from moving
}
else if (effectType == EFFECT_TYPE_WAVY)
{
float offsetY = sin(pt.x * uFrequency + uTime * uSpeed) * uWaveAmplitude;
pt.y += offsetY; // * (pt.y - 1.0); // <- Uncomment to stop bottom part of the screen from moving
}
else if (effectType == EFFECT_TYPE_HEAT_WAVE_HORIZONTAL)
{
x = sin(pt.x * uFrequency + uTime * uSpeed) * uWaveAmplitude;
}
else if (effectType == EFFECT_TYPE_HEAT_WAVE_VERTICAL)
{
y = sin(pt.y * uFrequency + uTime * uSpeed) * uWaveAmplitude;
}
else if (effectType == EFFECT_TYPE_FLAG)
{
y = sin(pt.y * uFrequency + 10.0 * pt.x + uTime * uSpeed) * uWaveAmplitude;
x = sin(pt.x * uFrequency + 5.0 * pt.y + uTime * uSpeed) * uWaveAmplitude;
}
return vec2(pt.x + x, pt.y + y);
}
const int EFFECT_TYPE_DREAMY = 0;
const int EFFECT_TYPE_WAVY = 1;
const int EFFECT_TYPE_HEAT_WAVE_HORIZONTAL = 2;
const int EFFECT_TYPE_HEAT_WAVE_VERTICAL = 3;
const int EFFECT_TYPE_FLAG = 4;
void main()
{
vec2 uv = sineWave(openfl_TextureCoordv);
gl_FragColor = texture2D(bitmap, uv);
}')
uniform int effectType;
/**
* How fast the waves move over time
*/
uniform float uSpeed;
/**
* Number of waves over time
*/
uniform float uFrequency;
/**
* How much the pixels are going to stretch over the waves
*/
uniform float uWaveAmplitude;
vec2 sineWave(vec2 pt)
{
float x = 0.0;
float y = 0.0;
if (effectType == EFFECT_TYPE_DREAMY)
{
float offsetX = sin(pt.y * uFrequency + uTime * uSpeed) * uWaveAmplitude;
pt.x += offsetX; // * (pt.y - 1.0); // <- Uncomment to stop bottom part of the screen from moving
}
else if (effectType == EFFECT_TYPE_WAVY)
{
float offsetY = sin(pt.x * uFrequency + uTime * uSpeed) * uWaveAmplitude;
pt.y += offsetY; // * (pt.y - 1.0); // <- Uncomment to stop bottom part of the screen from moving
}
else if (effectType == EFFECT_TYPE_HEAT_WAVE_HORIZONTAL)
{
x = sin(pt.x * uFrequency + uTime * uSpeed) * uWaveAmplitude;
}
else if (effectType == EFFECT_TYPE_HEAT_WAVE_VERTICAL)
{
y = sin(pt.y * uFrequency + uTime * uSpeed) * uWaveAmplitude;
}
else if (effectType == EFFECT_TYPE_FLAG)
{
y = sin(pt.y * uFrequency + 10.0 * pt.x + uTime * uSpeed) * uWaveAmplitude;
x = sin(pt.x * uFrequency + 5.0 * pt.y + uTime * uSpeed) * uWaveAmplitude;
}
return vec2(pt.x + x, pt.y + y);
}
void main()
{
vec2 uv = sineWave(openfl_TextureCoordv);
gl_FragColor = texture2D(bitmap, uv);
}')
public function new()
{
super();
+2
View File
@@ -107,6 +107,8 @@ class Main extends Sprite
// addChild(new FramerateField(10, 3, 0xFFFFFF));
addChild(new funkin.system.framerate.Framerate());
#end
trace("Hello", "World");
}
@:dox(hide)
+2 -2
View File
@@ -142,7 +142,7 @@ class Alphabet extends FlxSpriteGroup
letter.createLetter(character);
// anim not found
if (!letter.visible)
if (!letter.visible)
xPos += 40;
letter.setColor(color, isBold);
@@ -190,7 +190,7 @@ class Alphabet extends FlxSpriteGroup
override function update(elapsed:Float)
{
super.update(elapsed);
if (isMenuItem)
{
var scaledY = FlxMath.remapToRange(targetY, 0, 1, 0, 1.3);
+9 -9
View File
@@ -4,13 +4,13 @@ import flixel.util.FlxColor;
import flixel.text.FlxText;
class FunkinText extends FlxText {
public function new(X:Float = 0, Y:Float = 0, FieldWidth:Float = 0, ?Text:String, Size:Int = 16, Border:Bool = true) {
super(X, Y, FieldWidth, Text, Size);
setFormat(Paths.font("vcr.ttf"), Size, FlxColor.WHITE);
if (Border) {
borderStyle = OUTLINE;
borderSize = 1;
borderColor = 0xFF000000;
}
}
public function new(X:Float = 0, Y:Float = 0, FieldWidth:Float = 0, ?Text:String, Size:Int = 16, Border:Bool = true) {
super(X, Y, FieldWidth, Text, Size);
setFormat(Paths.font("vcr.ttf"), Size, FlxColor.WHITE);
if (Border) {
borderStyle = OUTLINE;
borderSize = 1;
borderColor = 0xFF000000;
}
}
}
+58 -58
View File
@@ -4,66 +4,66 @@ import openfl.display.BitmapData;
import flixel.util.FlxColor;
class BitmapUtil {
/**
* Returns the most present color in a Bitmap.
* @param bmap Bitmap
* @return FlxColor Color that is the most present.
*/
public static function getMostPresentColor(bmap:BitmapData):FlxColor {
// map containing all the colors and the number of times they've been assigned.
var colorMap:Map<FlxColor, Float> = [];
var color:FlxColor = 0;
var fixedColor:FlxColor = 0;
/**
* Returns the most present color in a Bitmap.
* @param bmap Bitmap
* @return FlxColor Color that is the most present.
*/
public static function getMostPresentColor(bmap:BitmapData):FlxColor {
// map containing all the colors and the number of times they've been assigned.
var colorMap:Map<FlxColor, Float> = [];
var color:FlxColor = 0;
var fixedColor:FlxColor = 0;
for(y in 0...bmap.height) {
for(x in 0...bmap.width) {
color = bmap.getPixel32(x, y);
fixedColor = 0xFF000000 + (color % 0x1000000);
if (colorMap[fixedColor] == null)
colorMap[fixedColor] = 0;
colorMap[fixedColor] += color.alphaFloat;
}
}
for(y in 0...bmap.height) {
for(x in 0...bmap.width) {
color = bmap.getPixel32(x, y);
fixedColor = 0xFF000000 + (color % 0x1000000);
if (colorMap[fixedColor] == null)
colorMap[fixedColor] = 0;
colorMap[fixedColor] += color.alphaFloat;
}
}
var mostPresentColor:FlxColor = 0;
var mostPresentColorCount:Float = -1;
for(c=>n in colorMap) {
if (n > mostPresentColorCount) {
mostPresentColorCount = n;
mostPresentColor = c;
}
}
return mostPresentColor;
}
/**
* Returns the most present saturated color in a Bitmap.
* @param bmap Bitmap
* @return FlxColor Color that is the most present.
*/
public static function getMostPresentSaturatedColor(bmap:BitmapData):FlxColor {
// map containing all the colors and the number of times they've been assigned.
var colorMap:Map<FlxColor, Float> = [];
var color:FlxColor = 0;
var fixedColor:FlxColor = 0;
var mostPresentColor:FlxColor = 0;
var mostPresentColorCount:Float = -1;
for(c=>n in colorMap) {
if (n > mostPresentColorCount) {
mostPresentColorCount = n;
mostPresentColor = c;
}
}
return mostPresentColor;
}
/**
* Returns the most present saturated color in a Bitmap.
* @param bmap Bitmap
* @return FlxColor Color that is the most present.
*/
public static function getMostPresentSaturatedColor(bmap:BitmapData):FlxColor {
// map containing all the colors and the number of times they've been assigned.
var colorMap:Map<FlxColor, Float> = [];
var color:FlxColor = 0;
var fixedColor:FlxColor = 0;
for(y in 0...bmap.height) {
for(x in 0...bmap.width) {
color = bmap.getPixel32(x, y);
fixedColor = 0xFF000000 + (color % 0x1000000);
if (colorMap[fixedColor] == null)
colorMap[fixedColor] = 0;
colorMap[fixedColor] += color.alphaFloat * 0.33 + (0.67 * (color.saturation * (2 * (color.lightness > 0.5 ? 0.5 - (color.lightness) : color.lightness))));
}
}
for(y in 0...bmap.height) {
for(x in 0...bmap.width) {
color = bmap.getPixel32(x, y);
fixedColor = 0xFF000000 + (color % 0x1000000);
if (colorMap[fixedColor] == null)
colorMap[fixedColor] = 0;
colorMap[fixedColor] += color.alphaFloat * 0.33 + (0.67 * (color.saturation * (2 * (color.lightness > 0.5 ? 0.5 - (color.lightness) : color.lightness))));
}
}
var mostPresentColor:FlxColor = 0;
var mostPresentColorCount:Float = -1;
for(c=>n in colorMap) {
if (n > mostPresentColorCount) {
mostPresentColorCount = n;
mostPresentColor = c;
}
}
return mostPresentColor;
}
var mostPresentColor:FlxColor = 0;
var mostPresentColorCount:Float = -1;
for(c=>n in colorMap) {
if (n > mostPresentColorCount) {
mostPresentColorCount = n;
mostPresentColor = c;
}
}
return mostPresentColor;
}
}
+111 -111
View File
@@ -11,142 +11,142 @@ import lime.app.Application;
#end
class DiscordUtil {
public static var currentID:String = null;
public static var discordThread:#if DISCORD_RPC Thread #else Dynamic #end = null;
public static var ready:Bool = false;
public static var data:DiscordJson = null;
public static var currentID:String = null;
public static var discordThread:#if DISCORD_RPC Thread #else Dynamic #end = null;
public static var ready:Bool = false;
public static var data:DiscordJson = null;
public static function init() {
#if DISCORD_RPC
reloadJsonData();
discordThread = Thread.create(function() {
while (true)
{
while(!ready) {
Sys.sleep(1/60);
}
trace("Processing Discord RPC...");
DiscordRpc.process();
Sys.sleep(2);
}
});
public static function init() {
#if DISCORD_RPC
reloadJsonData();
discordThread = Thread.create(function() {
while (true)
{
while(!ready) {
Sys.sleep(1/60);
}
trace("Processing Discord RPC...");
DiscordRpc.process();
Sys.sleep(2);
}
});
Application.current.onExit.add(function(exitCode) {
shutdown();
});
#end
}
#end
}
public static function reloadJsonData() {
#if DISCORD_RPC
data = {};
var jsonPath = Paths.json("config/discord");
if (Assets.exists(jsonPath)) {
try {
data = Json.parse(Assets.getText(jsonPath));
} catch(e) {
Logs.trace('Couldn\'t load Discord RPC configuration: ${e.toString()}', ERROR);
}
}
trace(data);
data.setFieldDefault("clientID", "1027994136193810442");
data.setFieldDefault("logoKey", "icon");
data.setFieldDefault("logoText", Application.current.meta.get('title'));
public static function reloadJsonData() {
#if DISCORD_RPC
data = {};
var jsonPath = Paths.json("config/discord");
if (Assets.exists(jsonPath)) {
try {
data = Json.parse(Assets.getText(jsonPath));
} catch(e) {
Logs.trace('Couldn\'t load Discord RPC configuration: ${e.toString()}', ERROR);
}
}
trace(data);
data.setFieldDefault("clientID", "1027994136193810442");
data.setFieldDefault("logoKey", "icon");
data.setFieldDefault("logoText", Application.current.meta.get('title'));
changeClientID(data.clientID);
#end
}
changeClientID(data.clientID);
#end
}
public static function changePresence(details:String, state:String, ?smallImageKey : String) {
#if DISCORD_RPC
changePresenceAdvanced({
state: state,
details: details,
smallImageKey: smallImageKey
});
#end
}
public static function changePresence(details:String, state:String, ?smallImageKey : String) {
#if DISCORD_RPC
changePresenceAdvanced({
state: state,
details: details,
smallImageKey: smallImageKey
});
#end
}
public static function changeSongPresence(details:String, state:String, audio:FlxSound, ?smallImageKey : String) {
#if DISCORD_RPC
var start:Float = 0;
var end:Float = 0;
public static function changeSongPresence(details:String, state:String, audio:FlxSound, ?smallImageKey : String) {
#if DISCORD_RPC
var start:Float = 0;
var end:Float = 0;
if (audio != null && audio.playing) {
start = Date.now().getTime();
end = start + (audio.length - audio.time);
}
if (audio != null && audio.playing) {
start = Date.now().getTime();
end = start + (audio.length - audio.time);
}
changePresenceAdvanced({
state: state,
details: details,
smallImageKey: smallImageKey,
startTimestamp: Std.int(start / 1000),
endTimestamp: Std.int(end / 1000)
});
#end
}
changePresenceAdvanced({
state: state,
details: details,
smallImageKey: smallImageKey,
startTimestamp: Std.int(start / 1000),
endTimestamp: Std.int(end / 1000)
});
#end
}
public static function changePresenceAdvanced(data:#if DISCORD_RPC DiscordPresenceOptions #else Dynamic #end) {
#if DISCORD_RPC
if (data == null) return;
public static function changePresenceAdvanced(data:#if DISCORD_RPC DiscordPresenceOptions #else Dynamic #end) {
#if DISCORD_RPC
if (data == null) return;
if (data.largeImageKey == null)
data.largeImageKey = DiscordUtil.data.logoKey;
if (data.largeImageText == null)
data.largeImageText = DiscordUtil.data.logoText;
#if GLOBAL_SCRIPT
var event = funkin.scripting.GlobalScript.event("onDiscordPresenceUpdate", EventManager.get(DiscordPresenceUpdateEvent).recycle(data));
if (event.cancelled) return;
#end
DiscordRpc.presence(data);
#end
}
public static function changeClientID(id:String) {
#if DISCORD_RPC
if (currentID != null) {
DiscordRpc.shutdown();
}
if (data.largeImageKey == null)
data.largeImageKey = DiscordUtil.data.logoKey;
if (data.largeImageText == null)
data.largeImageText = DiscordUtil.data.logoText;
ready = false;
#if GLOBAL_SCRIPT
var event = funkin.scripting.GlobalScript.event("onDiscordPresenceUpdate", EventManager.get(DiscordPresenceUpdateEvent).recycle(data));
if (event.cancelled) return;
DiscordRpc.start({
#end
DiscordRpc.presence(data);
#end
}
public static function changeClientID(id:String) {
#if DISCORD_RPC
if (currentID != null) {
DiscordRpc.shutdown();
}
ready = false;
DiscordRpc.start({
clientID: id,
onReady: function() {
Logs.trace('Discord RPC started');
ready = true;
},
Logs.trace('Discord RPC started');
ready = true;
},
onError: onError,
onDisconnected: onDisconnected
});
currentID = id;
currentID = id;
#end
}
#end
}
public static function shutdown() {
#if DISCORD_RPC
DiscordRpc.shutdown();
#end
}
public static function shutdown() {
#if DISCORD_RPC
DiscordRpc.shutdown();
#end
}
// HANDLERS
#if DISCORD_RPC
static function onError(_code:Int, _message:String) {
Logs.trace('Discord RPC Error: ${_message} (Code: $_code)', ERROR);
}
// HANDLERS
#if DISCORD_RPC
static function onError(_code:Int, _message:String) {
Logs.trace('Discord RPC Error: ${_message} (Code: $_code)', ERROR);
}
static function onDisconnected(_code:Int, _message:String) {
Logs.trace('Discord RPC Disconnected: ${_message} (Code: $_code)', WARNING);
}
#end
static function onDisconnected(_code:Int, _message:String) {
Logs.trace('Discord RPC Disconnected: ${_message} (Code: $_code)', WARNING);
}
#end
}
typedef DiscordJson = {
var ?clientID:String;
var ?logoKey:String;
var ?logoText:String;
var ?clientID:String;
var ?logoKey:String;
var ?logoText:String;
}
+8 -8
View File
@@ -4,12 +4,12 @@ import funkin.scripting.Script;
import funkin.scripting.MultiThreadedScript;
class EngineUtil {
/**
* Starts a new multithreaded script.
* This script will share all the variables with the current one, which means already existing callbacks will be replaced by new ones on conflict.
* @param path
*/
public static function startMultithreadedScript(path:String) {
return new MultiThreadedScript(path, Script.curScript);
}
/**
* Starts a new multithreaded script.
* This script will share all the variables with the current one, which means already existing callbacks will be replaced by new ones on conflict.
* @param path
*/
public static function startMultithreadedScript(path:String) {
return new MultiThreadedScript(path, Script.curScript);
}
}
+24 -24
View File
@@ -7,37 +7,37 @@ import flixel.util.FlxColor;
* Gets rid of precision issues with `FlxColor.interpolate`
*/
class FlxInterpolateColor {
public var red:Float = 0;
public var green:Float = 0;
public var blue:Float = 0;
public var alpha:Float = 0;
public var red:Float = 0;
public var green:Float = 0;
public var blue:Float = 0;
public var alpha:Float = 0;
public var color(get, set):FlxColor;
public var color(get, set):FlxColor;
private inline function get_color()
return FlxColor.fromRGBFloat(red, green, blue, alpha);
private inline function get_color()
return FlxColor.fromRGBFloat(red, green, blue, alpha);
private inline function set_color(c:FlxColor):FlxColor {
red = c.redFloat;
green = c.greenFloat;
blue = c.blueFloat;
alpha = c.alphaFloat;
return c;
}
private inline function set_color(c:FlxColor):FlxColor {
red = c.redFloat;
green = c.greenFloat;
blue = c.blueFloat;
alpha = c.alphaFloat;
return c;
}
public inline function toString()
return '[FlxInterpolateColor - (R:${red} | G:${green} | B:${blue} | A:${alpha})]';
public function new(color:FlxColor) {
this.color = color;
}
public inline function toString()
return '[FlxInterpolateColor - (R:${red} | G:${green} | B:${blue} | A:${alpha})]';
public function new(color:FlxColor) {
this.color = color;
}
public function lerpTo(color:FlxColor, ratio:Float) {
red = (color.redFloat - red) * ratio + red;
public function lerpTo(color:FlxColor, ratio:Float) {
red = (color.redFloat - red) * ratio + red;
green = (color.greenFloat - green) * ratio + green;
blue = (color.blueFloat - blue) * ratio + blue;
alpha = (color.alphaFloat - alpha) * ratio + alpha;
}
}
public inline function fpsLerpTo(color:FlxColor, ratio:Float)
lerpTo(color, ratio * 60 * FlxG.elapsed);
public inline function fpsLerpTo(color:FlxColor, ratio:Float)
lerpTo(color, ratio * 60 * FlxG.elapsed);
}
+27 -27
View File
@@ -5,36 +5,36 @@ package funkin.utils;
* DOESNT SUPPORT CATEGORIES YET!!
*/
class IniUtil {
public static inline function parseAsset(assetPath:String, ?defaultVariables:Map<String, String>)
return parseString(Assets.getText(assetPath), defaultVariables);
public static inline function parseAsset(assetPath:String, ?defaultVariables:Map<String, String>)
return parseString(Assets.getText(assetPath), defaultVariables);
public static function parseString(data:String, ?defaultVariables:Map<String, String>) {
var trimmed:String;
var splitContent = [for(e in data.split("\n")) if ((trimmed = e.trim()) != "") trimmed];
var finalMap:Map<String, String> = [];
if (defaultVariables != null)
for(k=>e in defaultVariables)
finalMap[k] = e;
public static function parseString(data:String, ?defaultVariables:Map<String, String>) {
var trimmed:String;
var splitContent = [for(e in data.split("\n")) if ((trimmed = e.trim()) != "") trimmed];
for(line in splitContent) {
// comment
if (line.startsWith(";")) continue;
// categories; not supported yet
if (line.startsWith("[") && line.endsWith("]")) continue;
var finalMap:Map<String, String> = [];
if (defaultVariables != null)
for(k=>e in defaultVariables)
finalMap[k] = e;
var index = line.indexOf("=");
var name = line.substr(0, index).trim();
var value = line.substr(index+1).trim();
for(line in splitContent) {
// comment
if (line.startsWith(";")) continue;
// categories; not supported yet
if (line.startsWith("[") && line.endsWith("]")) continue;
if (value.startsWith("\"") && value.endsWith("\""))
value = value.substr(1, value.length - 2);
var index = line.indexOf("=");
var name = line.substr(0, index).trim();
var value = line.substr(index+1).trim();
if (value.length == 0 || name.length == 0)
continue;
finalMap[name] = value;
}
return finalMap;
}
if (value.startsWith("\"") && value.endsWith("\""))
value = value.substr(1, value.length - 2);
if (value.length == 0 || name.length == 0)
continue;
finalMap[name] = value;
}
return finalMap;
}
}
+75 -75
View File
@@ -4,84 +4,84 @@ import flixel.util.FlxColor;
import flixel.text.FlxText;
class MarkdownUtil {
public static function applyMarkdownText(text:FlxText, str:String) {
text.textField.htmlText = Markdown.markdownToHtml(prepareMarkdown(str));
var changes:Array<FlxTextFormatMarkerPair> = [
createAdvancedMarkerPair("{title}", 0xFFFFFFFF, text.size * 2, false, true, true),
createAdvancedMarkerPair("{subtitle}", 0xFFFFFFFF, text.size * 1.5, false, true, true),
createAdvancedMarkerPair("{subsubtitle}", 0xFFFFFFFF, text.size * 1.25, false, true, true),
createAdvancedMarkerPair("{ident1}", 0xFFFFFFFF, null, false, false, false, text.size * 2, true),
createAdvancedMarkerPair("{ident2}", 0xFFFFFFFF, null, false, false, false, text.size * 4, true),
createAdvancedMarkerPair("{ident3}", 0xFFFFFFFF, null, false, false, false, text.size * 6, true),
createAdvancedMarkerPair("{ident4}", 0xFFFFFFFF, null, false, false, false, text.size * 8, true),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFFFF00, false, true), "{o}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFF0000, false, true), "{r}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFF00FF08, false, true), "{g}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFF7D7D7D, false, true), "{gray}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFFFFFF, false, true, 0xFF222222), "{italic}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFFFFFF, false, true, 0xFF666666), "{bold}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFFFFFF, false, true, 0xFF888888), "{bold-italic}"),
];
public static function applyMarkdownText(text:FlxText, str:String) {
text.textField.htmlText = Markdown.markdownToHtml(prepareMarkdown(str));
var changes:Array<FlxTextFormatMarkerPair> = [
createAdvancedMarkerPair("{title}", 0xFFFFFFFF, text.size * 2, false, true, true),
createAdvancedMarkerPair("{subtitle}", 0xFFFFFFFF, text.size * 1.5, false, true, true),
createAdvancedMarkerPair("{subsubtitle}", 0xFFFFFFFF, text.size * 1.25, false, true, true),
createAdvancedMarkerPair("{ident1}", 0xFFFFFFFF, null, false, false, false, text.size * 2, true),
createAdvancedMarkerPair("{ident2}", 0xFFFFFFFF, null, false, false, false, text.size * 4, true),
createAdvancedMarkerPair("{ident3}", 0xFFFFFFFF, null, false, false, false, text.size * 6, true),
createAdvancedMarkerPair("{ident4}", 0xFFFFFFFF, null, false, false, false, text.size * 8, true),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFFFF00, false, true), "{o}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFF0000, false, true), "{r}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFF00FF08, false, true), "{g}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFF7D7D7D, false, true), "{gray}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFFFFFF, false, true, 0xFF222222), "{italic}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFFFFFF, false, true, 0xFF666666), "{bold}"),
new FlxTextFormatMarkerPair(new FlxTextFormat(0xFFFFFFFF, false, true, 0xFF888888), "{bold-italic}"),
];
text.applyMarkup(
parseWarnings(text.textField.text),
changes
);
@:privateAccess {
// hacky fix for the text cutting when bigger text formats are used
text._regen = true;
text.regenGraphic();
text._regen = true;
text.regenGraphic();
}
}
text.applyMarkup(
parseWarnings(text.textField.text),
changes
);
@:privateAccess {
// hacky fix for the text cutting when bigger text formats are used
text._regen = true;
text.regenGraphic();
text._regen = true;
text.regenGraphic();
}
}
public static function createAdvancedMarkerPair(marker:String, color:FlxColor, size:Null<Float>, bold:Bool = false, italic:Bool = false, ?underline:Bool = false, ?blockIndent:Int, ?bullet:Bool) {
@:privateAccess {
var format = new FlxTextFormat(color, bold, italic);
format.format.size = size == null ? null : Std.int(size);
format.format.underline = underline;
format.format.blockIndent = blockIndent;
format.format.bullet = bullet;
return new FlxTextFormatMarkerPair(format, marker);
}
}
public static function createAdvancedMarkerPair(marker:String, color:FlxColor, size:Null<Float>, bold:Bool = false, italic:Bool = false, ?underline:Bool = false, ?blockIndent:Int, ?bullet:Bool) {
@:privateAccess {
var format = new FlxTextFormat(color, bold, italic);
format.format.size = size == null ? null : Std.int(size);
format.format.underline = underline;
format.format.blockIndent = blockIndent;
format.format.bullet = bullet;
return new FlxTextFormatMarkerPair(format, marker);
}
}
public static function parseWarnings(text:String) {
text = text.replace("&nbsp;", " ");
text = parseEmote(text, "⚠", "{o}(!)", "{o}");
text = parseEmote(text, "❌", "{r}(X)", "{r}");
text = parseEmote(text, "✔", "{g}(+)", "{g}");
return text;
}
public static function parseWarnings(text:String) {
text = text.replace("&nbsp;", " ");
text = parseEmote(text, "⚠", "{o}(!)", "{o}");
text = parseEmote(text, "❌", "{r}(X)", "{r}");
text = parseEmote(text, "✔", "{g}(+)", "{g}");
return text;
}
public static function prepareMarkdown(text:String) {
text = "\n" + text;
text = parseEmote(text, "\n- ", "\n{ident1}&nbsp;&nbsp;• ", "{ident1}");
text = parseEmote(text, "\n - ", "\n{ident2}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;• ", "{ident2}");
text = parseEmote(text, "\n - ", "\n{ident3}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;• ", "{ident3}");
text = parseEmote(text, "\n - ", "\n{ident4}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;• ", "{ident4}");
text = parseEmote(text, "\n> ", "\n{gray}", "{gray}");
text = parseEmote(text, "\n### ", "\n{subsubtitle}", "{subsubtitle}");
text = parseEmote(text, "\n## ", "\n{subtitle}", "{subtitle}");
text = parseEmote(text, "\n# ", "\n{title}", "{title}");
text = parseEmote(text, "***", "{bold-italic}", "{bold-italic}", "***");
text = parseEmote(text, "**", "{bold}", "{bold}", "**");
text = parseEmote(text, "*", "{italic}", "{italic}", "*");
text = parseEmote(text, "_", "{italic}", "{italic}", "*");
text = parseEmote(text, "__", "{bold}", "{bold}", "*");
text.substr("\n".length);
return text;
}
public static function prepareMarkdown(text:String) {
text = "\n" + text;
text = parseEmote(text, "\n- ", "\n{ident1}&nbsp;&nbsp;• ", "{ident1}");
text = parseEmote(text, "\n - ", "\n{ident2}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;• ", "{ident2}");
text = parseEmote(text, "\n - ", "\n{ident3}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;• ", "{ident3}");
text = parseEmote(text, "\n - ", "\n{ident4}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;• ", "{ident4}");
text = parseEmote(text, "\n> ", "\n{gray}", "{gray}");
text = parseEmote(text, "\n### ", "\n{subsubtitle}", "{subsubtitle}");
text = parseEmote(text, "\n## ", "\n{subtitle}", "{subtitle}");
text = parseEmote(text, "\n# ", "\n{title}", "{title}");
text = parseEmote(text, "***", "{bold-italic}", "{bold-italic}", "***");
text = parseEmote(text, "**", "{bold}", "{bold}", "**");
text = parseEmote(text, "*", "{italic}", "{italic}", "*");
text = parseEmote(text, "_", "{italic}", "{italic}", "*");
text = parseEmote(text, "__", "{bold}", "{bold}", "*");
text.substr("\n".length);
return text;
}
public static function parseEmote(text:String, emote:String, beginning:String, end:String, emoteEnd:String = "\n") {
var index:Int;
while((index = text.indexOf(emote)) >= 0) {
var nextIndex = text.indexOf(emoteEnd, index + emote.length);
if (nextIndex < 0)
nextIndex = text.length;
text = text.substr(0, index) + beginning + text.substring(index + emote.length, nextIndex) + end + (emote == emoteEnd ? "" : emoteEnd) + text.substring(nextIndex + emoteEnd.length);
}
return text;
}
public static function parseEmote(text:String, emote:String, beginning:String, end:String, emoteEnd:String = "\n") {
var index:Int;
while((index = text.indexOf(emote)) >= 0) {
var nextIndex = text.indexOf(emoteEnd, index + emote.length);
if (nextIndex < 0)
nextIndex = text.length;
text = text.substr(0, index) + beginning + text.substring(index + emote.length, nextIndex) + end + (emote == emoteEnd ? "" : emoteEnd) + text.substring(nextIndex + emoteEnd.length);
}
return text;
}
}
+1 -1
View File
@@ -30,7 +30,7 @@ class MemoryUtil {
}
public static function init() {}
public static function clearMinor() {
#if (cpp || java || neko)
Gc.run(false);
+45 -45
View File
@@ -4,12 +4,12 @@ import lime.app.Application;
/**
* Small util that allows you to load any function from ndlls via `getFunction`.
*
*
* NDLLs must be in your mod's "ndlls" folder, and must follow this name scheme:
* - `name-windows.ndll` for Windows targeted ndlls
* - `name-linux.ndll` for Linux targeted ndlls
* - `name-mac.ndll` for Mac targeted ndlls
*
*
* If:
* - The platform does not support NDLLs
* - The NDLL is not found
@@ -17,52 +17,52 @@ import lime.app.Application;
* then an empty function will be returned instead, and a message will be shown in logs.
*/
class NdllUtil {
#if NDLLS_SUPPORTED
#if windows public static final os:String = "windows"; #end
#if linux public static final os:String = "linux"; #end
#if macos public static final os:String = "mac"; #end
#if android public static final os:String = "android"; #end
#end
#if NDLLS_SUPPORTED
#if windows public static final os:String = "windows"; #end
#if linux public static final os:String = "linux"; #end
#if macos public static final os:String = "mac"; #end
#if android public static final os:String = "android"; #end
#end
/**
* Returns an function from a Haxe NDLL.
*
* @param ndll Name of the NDLL.
* @param name Name of the function.
* @param args Number of arguments of that function.
*/
public static function getFunction(ndll:String, name:String, args:Int) {
#if NDLLS_SUPPORTED
return getFunctionFromPath(Paths.ndll('$ndll-$os'), name, args);
#else
Logs.trace('NDLLs are not supported on this platform.', WARNING);
return function() {};
#end
}
/**
* Returns an function from a Haxe NDLL at specified path.
*
* @param ndll Asset path to the NDLL.
* @param name Name of the function.
* @param args Number of arguments of that function.
*/
public static function getFunctionFromPath(ndll:String, name:String, args:Int) {
#if NDLLS_SUPPORTED
if (!Assets.exists(ndll)) {
Logs.trace('Couldn\'t find ndll at ${ndll}.', WARNING);
return function() {};
/**
* Returns an function from a Haxe NDLL.
*
* @param ndll Name of the NDLL.
* @param name Name of the function.
* @param args Number of arguments of that function.
*/
public static function getFunction(ndll:String, name:String, args:Int) {
#if NDLLS_SUPPORTED
return getFunctionFromPath(Paths.ndll('$ndll-$os'), name, args);
#else
Logs.trace('NDLLs are not supported on this platform.', WARNING);
return function() {};
#end
}
/**
* Returns an function from a Haxe NDLL at specified path.
*
* @param ndll Asset path to the NDLL.
* @param name Name of the function.
* @param args Number of arguments of that function.
*/
public static function getFunctionFromPath(ndll:String, name:String, args:Int) {
#if NDLLS_SUPPORTED
if (!Assets.exists(ndll)) {
Logs.trace('Couldn\'t find ndll at ${ndll}.', WARNING);
return function() {};
}
var func = lime.system.CFFI.load(Assets.getPath(ndll), name, args);
if (func == null) {
if (func == null) {
Logs.trace('Method ${name} in ndll ${ndll} with ${args} args was not found.', ERROR);
return function() {};
return function() {};
}
return func;
#else
Logs.trace('NDLLs are not supported on this platform.', WARNING);
#end
return function() {};
}
return func;
#else
Logs.trace('NDLLs are not supported on this platform.', WARNING);
#end
return function() {};
}
}
+26 -26
View File
@@ -2,31 +2,31 @@ package funkin.utils;
#if ALLOW_MULTITHREADING
class ThreadUtil {
/**
* Creates a new Thread with an error handler.
* @param func Function to execute
* @param autoRestart Whenever the thread should auto restart itself after crashing.
*/
public static function createSafe(func:Void->Void, autoRestart:Bool = false) {
if (autoRestart) {
return sys.thread.Thread.create(function() {
while(true) {
try {
func();
} catch(e) {
trace(e.details());
}
}
});
} else {
return sys.thread.Thread.create(function() {
try {
func();
} catch(e) {
trace(e.details());
}
});
}
}
/**
* Creates a new Thread with an error handler.
* @param func Function to execute
* @param autoRestart Whenever the thread should auto restart itself after crashing.
*/
public static function createSafe(func:Void->Void, autoRestart:Bool = false) {
if (autoRestart) {
return sys.thread.Thread.create(function() {
while(true) {
try {
func();
} catch(e) {
trace(e.details());
}
}
});
} else {
return sys.thread.Thread.create(function() {
try {
func();
} catch(e) {
trace(e.details());
}
});
}
}
}
#end
+32 -32
View File
@@ -13,34 +13,34 @@ using StringTools;
*/
class XMLUtil {
/**
* Applies a property XML node to an object.
* @param object Object to which the xml property will be applied
* @param property `property` node.
*/
public static function applyXMLProperty(object:Dynamic, property:Access):ErrorCode {
if (!property.has.name || !property.has.type || !property.has.value) {
Logs.trace('Failed to apply XML property: XML Element misses name, type, or value attributes.', WARNING);
return MISSING_PROPERTY;
}
/**
* Applies a property XML node to an object.
* @param object Object to which the xml property will be applied
* @param property `property` node.
*/
public static function applyXMLProperty(object:Dynamic, property:Access):ErrorCode {
if (!property.has.name || !property.has.type || !property.has.value) {
Logs.trace('Failed to apply XML property: XML Element misses name, type, or value attributes.', WARNING);
return MISSING_PROPERTY;
}
var value:Dynamic = switch(property.att.type.toLowerCase()) {
case "float" | "number": Std.parseFloat(property.att.value);
case "int" | "integer" | "color": Std.parseInt(property.att.value);
case "string" | "str" | "text": property.att.value;
case "bool" | "boolean": property.att.value.toLowerCase() == "true";
default: return TYPE_INCORRECT;
}
if (value == null) return VALUE_NULL;
var value:Dynamic = switch(property.att.type.toLowerCase()) {
case "float" | "number": Std.parseFloat(property.att.value);
case "int" | "integer" | "color": Std.parseInt(property.att.value);
case "string" | "str" | "text": property.att.value;
case "bool" | "boolean": property.att.value.toLowerCase() == "true";
default: return TYPE_INCORRECT;
}
if (value == null) return VALUE_NULL;
try {
Reflect.setProperty(object, property.att.name, value);
} catch(e) {
Logs.trace('Failed to apply XML property: $e on ${Type.getClass(object)}', WARNING);
return REFLECT_ERROR;
}
return OK;
}
try {
Reflect.setProperty(object, property.att.name, value);
} catch(e) {
Logs.trace('Failed to apply XML property: $e on ${Type.getClass(object)}', WARNING);
return REFLECT_ERROR;
}
return OK;
}
/**
* Creates a new sprite based on a XML node.
@@ -69,11 +69,11 @@ class XMLUtil {
if (node.has.scrollx) {
var scroll:Null<Float> = Std.parseFloat(node.att.scrollx);
if (scroll != null) spr.scrollFactor.x = scroll;
}
}
if (node.has.scrolly) {
var scroll:Null<Float> = Std.parseFloat(node.att.scrolly);
if (scroll != null) spr.scrollFactor.y = scroll;
}
}
}
if (node.has.antialiasing) spr.antialiasing = node.att.antialiasing == "true";
if (node.has.scale) {
@@ -83,7 +83,7 @@ class XMLUtil {
if (node.has.updateHitbox && node.att.updateHitbox == "true") spr.updateHitbox();
spr.zoomFactor = Std.parseFloat(node.getAtt("zoomfactor")).getDefault(spr.zoomFactor);
for(anim in node.nodes.anim)
addXMLAnimation(spr, anim);
@@ -116,7 +116,7 @@ class XMLUtil {
if (i != null)
animData.indices.push(i);
}
}
}
return animData;
}
@@ -164,9 +164,9 @@ class XMLUtil {
// nothing
}
}
return OK;
return OK;
}
return MISSING_PROPERTY;
return MISSING_PROPERTY;
}
public static inline function fixXMLText(text:String) {
+191 -191
View File
@@ -24,81 +24,81 @@ using StringTools;
// import ZipUtils; var e = ZipUtils.createZipFile("gjnsdghs.ycemod"); ZipUtils.writeFolderToZip(e, "./mods/Friday Night Funkin'/", "Friday Night Funkin'/"); e.flush(); e.close();
class ZipUtil {
public static var bannedNames:Array<String> = [".git", ".gitignore", ".github", ".vscode", ".gitattributes", "readme.txt"];
public static var bannedNames:Array<String> = [".git", ".gitignore", ".github", ".vscode", ".gitattributes", "readme.txt"];
/**
* [Description] Uncompresses `zip` into the `destFolder` folder
* @param zip
* @param destFolder
* @param zip
* @param destFolder
*/
public static function uncompressZip(zip:Reader, destFolder:String, ?prefix:String, ?prog:ZipProgress):ZipProgress {
// we never know
FileSystem.createDirectory(destFolder);
var fields = zip.read();
var fields = zip.read();
try {
if (prefix != null) {
var f = fields;
fields = new List<Entry>();
for(field in f) {
if (field.fileName.startsWith(prefix)) {
fields.push(field);
}
}
}
if (prog == null)
prog = new ZipProgress();
prog.fileCount = fields.length;
for(k=>field in fields) {
prog.curFile = k;
var isFolder = field.fileName.endsWith("/") && field.fileSize == 0;
if (isFolder) {
FileSystem.createDirectory('${destFolder}/${field.fileName}');
} else {
var split = [for(e in field.fileName.split("/")) e.trim()];
split.pop();
FileSystem.createDirectory('${destFolder}/${split.join("/")}');
var data = unzip(field);
File.saveBytes('${destFolder}/${field.fileName}', data);
}
}
prog.curFile = fields.length;
prog.done = true;
} catch(e) {
prog.done = true;
prog.error = e;
}
return prog;
try {
if (prefix != null) {
var f = fields;
fields = new List<Entry>();
for(field in f) {
if (field.fileName.startsWith(prefix)) {
fields.push(field);
}
}
}
if (prog == null)
prog = new ZipProgress();
prog.fileCount = fields.length;
for(k=>field in fields) {
prog.curFile = k;
var isFolder = field.fileName.endsWith("/") && field.fileSize == 0;
if (isFolder) {
FileSystem.createDirectory('${destFolder}/${field.fileName}');
} else {
var split = [for(e in field.fileName.split("/")) e.trim()];
split.pop();
FileSystem.createDirectory('${destFolder}/${split.join("/")}');
var data = unzip(field);
File.saveBytes('${destFolder}/${field.fileName}', data);
}
}
prog.curFile = fields.length;
prog.done = true;
} catch(e) {
prog.done = true;
prog.error = e;
}
return prog;
}
#if (!macro && sys)
public static function uncompressZipAsync(zip:Reader, destFolder:String, ?prog:ZipProgress, ?prefix:String):ZipProgress {
if (prog == null)
prog = new ZipProgress();
Thread.create(function() {
uncompressZip(zip, destFolder, prefix, prog);
});
return prog;
}
#end
#if (!macro && sys)
public static function uncompressZipAsync(zip:Reader, destFolder:String, ?prog:ZipProgress, ?prefix:String):ZipProgress {
if (prog == null)
prog = new ZipProgress();
Thread.create(function() {
uncompressZip(zip, destFolder, prefix, prog);
});
return prog;
}
#end
/**
* [Description] Returns a `zip.Reader` instance from path.
* @param zipPath
* @return Reader
*/
public static function openZip(zipPath:String):Reader {
return new ZipReader(File.read(zipPath));
}
/**
* [Description] Returns a `zip.Reader` instance from path.
* @param zipPath
* @return Reader
*/
public static function openZip(zipPath:String):Reader {
return new ZipReader(File.read(zipPath));
}
/**
* [Description] Copy of haxe's Zip unzip function cause lime replaced it.
* @param f Zip entry
*/
public static function unzip(f:Entry) {
/**
* [Description] Copy of haxe's Zip unzip function cause lime replaced it.
* @param f Zip entry
*/
public static function unzip(f:Entry) {
if (!f.compressed)
return f.data;
var c = new haxe.zip.Uncompress(-15);
@@ -113,156 +113,156 @@ class ZipUtil {
return f.data;
}
/**
* [Description] Creates a ZIP file at the specified location and returns the Writer.
* @param path
* @return Writer
*/
public static function createZipFile(path:String):ZipWriter {
var output = File.write(path);
return new ZipWriter(output);
}
/**
* [Description] Creates a ZIP file at the specified location and returns the Writer.
* @param path
* @return Writer
*/
public static function createZipFile(path:String):ZipWriter {
var output = File.write(path);
return new ZipWriter(output);
}
/**
[Description] Writes the entirety of a folder to a zip file.
@param zip ZIP file to write to
@param path Folder path
@param prefix (Additional) allows you to set a prefix in the zip itself.
**/
public static function writeFolderToZip(zip:ZipWriter, path:String, ?prefix:String, ?prog:ZipProgress, ?whitelist:Array<String>):ZipProgress {
if (prefix == null) prefix = "";
if (whitelist == null) whitelist = [];
if (prog == null) prog = new ZipProgress();
/**
[Description] Writes the entirety of a folder to a zip file.
@param zip ZIP file to write to
@param path Folder path
@param prefix (Additional) allows you to set a prefix in the zip itself.
**/
public static function writeFolderToZip(zip:ZipWriter, path:String, ?prefix:String, ?prog:ZipProgress, ?whitelist:Array<String>):ZipProgress {
if (prefix == null) prefix = "";
if (whitelist == null) whitelist = [];
if (prog == null) prog = new ZipProgress();
try {
var curPath:Array<String> = ['$path'];
var destPath:Array<String> = [];
if (prefix != "") {
prefix = prefix.replace("\\", "/");
while(prefix.charAt(0) == "/") prefix = prefix.substr(1);
while(prefix.charAt(prefix.length-1) == "/") prefix = prefix.substr(0, prefix.length-1);
destPath.push(prefix);
}
var files:Array<StrNameLabel> = [];
var doFolder:Void->Void = null;
(doFolder = function() {
var path = curPath.join("/");
var zipPath = destPath.join("/");
for(e in FileSystem.readDirectory(path)) {
if (bannedNames.contains(e.toLowerCase()) && !whitelist.contains(e.toLowerCase())) continue;
if (FileSystem.isDirectory('$path/$e')) {
// is directory, so loop into that function again
for(p in [curPath, destPath]) p.push(e);
doFolder();
for(p in [curPath, destPath]) p.pop();
} else {
// is file, put it in the list
var zipPath = '$zipPath/$e';
while(zipPath.charAt(0) == "/") zipPath = zipPath.substr(1);
files.push(new StrNameLabel('$path/$e', zipPath));
}
}
})();
prog.fileCount = files.length;
for(k=>file in files) {
prog.curFile = k;
var fileContent = File.getBytes(file.name);
var fileInfo = FileSystem.stat(file.name);
var entry:Entry = {
fileName: file.label,
fileSize: fileInfo.size,
fileTime: Date.now(),
dataSize: 0,
data: fileContent,
crc32: Crc32.make(fileContent),
compressed: false
};
Tools.compress(entry, 1);
zip.writeFile(entry);
}
zip.writeCDR();
} catch(e) {
prog.error = e;
}
prog.done = true;
return prog;
}
try {
var curPath:Array<String> = ['$path'];
var destPath:Array<String> = [];
if (prefix != "") {
prefix = prefix.replace("\\", "/");
while(prefix.charAt(0) == "/") prefix = prefix.substr(1);
while(prefix.charAt(prefix.length-1) == "/") prefix = prefix.substr(0, prefix.length-1);
destPath.push(prefix);
}
public static function writeFolderToZipAsync(zip:ZipWriter, path:String, ?prefix:String):ZipProgress {
var zipProg = new ZipProgress();
Thread.create(function() {
writeFolderToZip(zip, path, prefix, zipProg);
});
return zipProg;
}
var files:Array<StrNameLabel> = [];
/**
* [Description] Converts an `Array<Entry>` to a `List<Entry>`.
* @param array
* @return List<Entry>
*/
public static function arrayToList(array:Array<Entry>):List<Entry> {
var list = new List<Entry>();
for(e in array) list.push(e);
return list;
}
var doFolder:Void->Void = null;
(doFolder = function() {
var path = curPath.join("/");
var zipPath = destPath.join("/");
for(e in FileSystem.readDirectory(path)) {
if (bannedNames.contains(e.toLowerCase()) && !whitelist.contains(e.toLowerCase())) continue;
if (FileSystem.isDirectory('$path/$e')) {
// is directory, so loop into that function again
for(p in [curPath, destPath]) p.push(e);
doFolder();
for(p in [curPath, destPath]) p.pop();
} else {
// is file, put it in the list
var zipPath = '$zipPath/$e';
while(zipPath.charAt(0) == "/") zipPath = zipPath.substr(1);
files.push(new StrNameLabel('$path/$e', zipPath));
}
}
})();
prog.fileCount = files.length;
for(k=>file in files) {
prog.curFile = k;
var fileContent = File.getBytes(file.name);
var fileInfo = FileSystem.stat(file.name);
var entry:Entry = {
fileName: file.label,
fileSize: fileInfo.size,
fileTime: Date.now(),
dataSize: 0,
data: fileContent,
crc32: Crc32.make(fileContent),
compressed: false
};
Tools.compress(entry, 1);
zip.writeFile(entry);
}
zip.writeCDR();
} catch(e) {
prog.error = e;
}
prog.done = true;
return prog;
}
public static function writeFolderToZipAsync(zip:ZipWriter, path:String, ?prefix:String):ZipProgress {
var zipProg = new ZipProgress();
Thread.create(function() {
writeFolderToZip(zip, path, prefix, zipProg);
});
return zipProg;
}
/**
* [Description] Converts an `Array<Entry>` to a `List<Entry>`.
* @param array
* @return List<Entry>
*/
public static function arrayToList(array:Array<Entry>):List<Entry> {
var list = new List<Entry>();
for(e in array) list.push(e);
return list;
}
}
class ZipProgress {
public var error:Exception = null;
public var curFile:Int = 0;
public var fileCount:Int = 0;
public var done:Bool = false;
public var percentage(get, null):Float;
public var error:Exception = null;
private function get_percentage() {
return fileCount <= 0 ? 0 : curFile / fileCount;
}
public var curFile:Int = 0;
public var fileCount:Int = 0;
public var done:Bool = false;
public var percentage(get, null):Float;
public function new() {}
private function get_percentage() {
return fileCount <= 0 ? 0 : curFile / fileCount;
}
public function new() {}
}
class ZipReader extends Reader {
public var files:List<Entry>;
public var files:List<Entry>;
public override function read() {
if (files != null) return files;
try {
var files = super.read();
return this.files = files;
} catch(e) {
}
return new List<Entry>();
}
public override function read() {
if (files != null) return files;
try {
var files = super.read();
return this.files = files;
} catch(e) {
}
return new List<Entry>();
}
}
class ZipWriter extends Writer {
public function flush() {
o.flush();
}
public function flush() {
o.flush();
}
public function writeFile(entry:Entry) {
writeEntryHeader(entry);
o.writeFullBytes(entry.data, 0, entry.data.length);
}
public function writeFile(entry:Entry) {
writeEntryHeader(entry);
o.writeFullBytes(entry.data, 0, entry.data.length);
}
public function close() {
o.close();
}
public function close() {
o.close();
}
}
class StrNameLabel {
public var name:String;
public var label:String;
public var name:String;
public var label:String;
public function new(name:String, label:String) {
this.name = name;
this.label = label;
}
public function new(name:String, label:String) {
this.name = name;
this.label = label;
}
}
#end
+88 -88
View File
@@ -7,103 +7,103 @@ package funkin.windows;
* Does not have any effect on other platforms.
*/
class WindowsAPI {
@:dox(hide) public static function registerAudio() {
#if windows
native.WinAPI.registerAudio();
#end
}
@:dox(hide) public static function registerAudio() {
#if windows
native.WinAPI.registerAudio();
#end
}
@:dox(hide) public static function registerAsDPICompatible() {
#if windows
native.WinAPI.registerAsDPICompatible();
#end
}
/**
* Allocates a new console. The console will automatically be opened
*/
public static function allocConsole() {
#if windows
native.WinAPI.allocConsole();
native.WinAPI.clearScreen();
#end
}
@:dox(hide) public static function registerAsDPICompatible() {
#if windows
native.WinAPI.registerAsDPICompatible();
#end
}
/**
* Sets the window titlebar to dark mode (Windows 10 only)
*/
public static function setDarkMode(enable:Bool) {
#if windows
native.WinAPI.setDarkMode(enable);
#end
}
/**
* Allocates a new console. The console will automatically be opened
*/
public static function allocConsole() {
#if windows
native.WinAPI.allocConsole();
native.WinAPI.clearScreen();
#end
}
/**
* Shows a message box
*/
public static function showMessageBox(caption:String, message:String, icon:MessageBoxIcon = MSG_WARNING) {
#if windows
native.WinAPI.showMessageBox(caption, message, icon);
#else
lime.app.Application.current.window.alert(message, caption);
#end
}
/**
* Sets the window titlebar to dark mode (Windows 10 only)
*/
public static function setDarkMode(enable:Bool) {
#if windows
native.WinAPI.setDarkMode(enable);
#end
}
/**
* Sets the console colors
*/
public static function setConsoleColors(foregroundColor:ConsoleColor = LIGHTGRAY, ?backgroundColor:ConsoleColor = BLACK) {
#if windows
var fg = cast(foregroundColor, Int);
var bg = cast(backgroundColor, Int);
native.WinAPI.setConsoleColors((bg * 16) + fg);
#end
}
/**
* Shows a message box
*/
public static function showMessageBox(caption:String, message:String, icon:MessageBoxIcon = MSG_WARNING) {
#if windows
native.WinAPI.showMessageBox(caption, message, icon);
#else
lime.app.Application.current.window.alert(message, caption);
#end
}
public static function consoleColorToOpenFL(color:ConsoleColor) {
return switch(color) {
case BLACK: 0xFF000000;
case DARKBLUE: 0xFF000088;
case DARKGREEN: 0xFF008800;
case DARKCYAN: 0xFF008888;
case DARKRED: 0xFF880000;
case DARKMAGENTA: 0xFF880000;
case DARKYELLOW: 0xFF888800;
case LIGHTGRAY: 0xFFBBBBBB;
case GRAY: 0xFF888888;
case BLUE: 0xFF0000FF;
case GREEN: 0xFF00FF00;
case CYAN: 0xFF00FFFF;
case RED: 0xFFFF0000;
case MAGENTA: 0xFFFF00FF;
case YELLOW: 0xFFFFFF00;
case WHITE | _: 0xFFFFFFFF;
}
}
/**
* Sets the console colors
*/
public static function setConsoleColors(foregroundColor:ConsoleColor = LIGHTGRAY, ?backgroundColor:ConsoleColor = BLACK) {
#if windows
var fg = cast(foregroundColor, Int);
var bg = cast(backgroundColor, Int);
native.WinAPI.setConsoleColors((bg * 16) + fg);
#end
}
public static function consoleColorToOpenFL(color:ConsoleColor) {
return switch(color) {
case BLACK: 0xFF000000;
case DARKBLUE: 0xFF000088;
case DARKGREEN: 0xFF008800;
case DARKCYAN: 0xFF008888;
case DARKRED: 0xFF880000;
case DARKMAGENTA: 0xFF880000;
case DARKYELLOW: 0xFF888800;
case LIGHTGRAY: 0xFFBBBBBB;
case GRAY: 0xFF888888;
case BLUE: 0xFF0000FF;
case GREEN: 0xFF00FF00;
case CYAN: 0xFF00FFFF;
case RED: 0xFFFF0000;
case MAGENTA: 0xFFFF00FF;
case YELLOW: 0xFFFFFF00;
case WHITE | _: 0xFFFFFFFF;
}
}
}
@:enum abstract ConsoleColor(Int) {
var BLACK:ConsoleColor = 0;
var DARKBLUE:ConsoleColor = 1;
var DARKGREEN:ConsoleColor = 2;
var DARKCYAN:ConsoleColor = 3;
var DARKRED:ConsoleColor = 4;
var DARKMAGENTA:ConsoleColor = 5;
var DARKYELLOW:ConsoleColor = 6;
var LIGHTGRAY:ConsoleColor = 7;
var GRAY:ConsoleColor = 8;
var BLUE:ConsoleColor = 9;
var GREEN:ConsoleColor = 10;
var CYAN:ConsoleColor = 11;
var RED:ConsoleColor = 12;
var MAGENTA:ConsoleColor = 13;
var YELLOW:ConsoleColor = 14;
var WHITE:ConsoleColor = 15;
var BLACK:ConsoleColor = 0;
var DARKBLUE:ConsoleColor = 1;
var DARKGREEN:ConsoleColor = 2;
var DARKCYAN:ConsoleColor = 3;
var DARKRED:ConsoleColor = 4;
var DARKMAGENTA:ConsoleColor = 5;
var DARKYELLOW:ConsoleColor = 6;
var LIGHTGRAY:ConsoleColor = 7;
var GRAY:ConsoleColor = 8;
var BLUE:ConsoleColor = 9;
var GREEN:ConsoleColor = 10;
var CYAN:ConsoleColor = 11;
var RED:ConsoleColor = 12;
var MAGENTA:ConsoleColor = 13;
var YELLOW:ConsoleColor = 14;
var WHITE:ConsoleColor = 15;
}
@:enum abstract MessageBoxIcon(Int) {
var MSG_ERROR:MessageBoxIcon = 0x00000010;
var MSG_QUESTION:MessageBoxIcon = 0x00000020;
var MSG_WARNING:MessageBoxIcon = 0x00000030;
var MSG_INFORMATION:MessageBoxIcon = 0x00000040;
var MSG_ERROR:MessageBoxIcon = 0x00000010;
var MSG_QUESTION:MessageBoxIcon = 0x00000020;
var MSG_WARNING:MessageBoxIcon = 0x00000030;
var MSG_INFORMATION:MessageBoxIcon = 0x00000040;
}