LiveReload, HTML/CSS/JS tool… for Flash, noooo!

Been dabbling in some goodies for straight non Flash-based web apps and one of the tools I’m using regularly is LiveReload. It basically refreshes a site whenever files change in a watched directory. It’ll also compile CoffeeScript, SASS, Jade, etc for you but the folder watching feature itself has been handy for my Flash work. So with Flash Builder’s automatic build enabled, the latest compilation is always ready in a specific browser window and tab on my secondary screen.

I won’t go over LiveReload setup as you can find that yourself but I will say that I’m using version 2.0a7 on OSX… I tried their 1.x Ruby gem but it made my MacBook do one of those jet engine impersonations. Besides, the new ui is pretty convenient.

I should also point out that atm LiveReload does not work with the local file URI protocol. To get around this, I currently run the following command out of my test site root such as bin-debug…

python -m SimpleHTTPServer

then just hit up http://localhost:8000, connect to LiveReload via the browser extension LiveReload can install, setup the watch folder(s) and I’m all set.

swcvis

Here’s a little tool I threw together while evaluating some Flash libraries for another project. I wanted to get a quick sense of a library’s size and structure but I usually find myself hopping all over the asdocs trying to draw a mental map. Basically all it does is read the object dependency information out of a swc library’s catalog and renders an inheritance tree.

This also gave me a chance to play with some data visualization libraries I’ve had bookmarked for awhile. I chose to use JavaScript InfoVis Toolkit as I really liked their space tree but another consideration was Prefuse Flare. If you’d like to view all the object dependencies not just inheritance, check out their dependency graph demo for a very nice visualization.

Demo

Anyways, the app is at http://nochump.com/swcvis, just click ’change’ in the top left to load a swc file from your local machine.  You can also click below to view some miscellaneous Flash libraries right away.

swcvis – playerglobal.swc
swcvis – flex.swc
swcvis – osmf.swc
swcvis – flexunit-0.9.swc
swcvis – framework.swc
swcvis – hamcrest-as3-1.1.0.swc
swcvis – robotlegs-framework-v1.3.0.swc
swcvis – PureMVC_AS3_2_0_4.swc
swcvis – Mate_08_9.swc
swcvis – swiz-0.6.4-flex4.swc
swcvis – Alternativa3D 7.5.0.swc
swcvis – Away3DLite.swc
swcvis – as3-signals-v0.6.swc

AS3 logging with Log4j

There are several things I miss about FlexBuilder…the debugger, authoring-time error checking, code assistance, and the quick compiles to name a few. But perhaps the first thing you’ll miss when just using the free Flex SDK is your basic trace output window. Initially I had written a simple Ruby script to handle tracing to a terminal window. This was fine for awhile but as some of my projects grew bigger, I wanted more control over logging.

Flex comes with a logging system under the mx.logging package which works similarly to typical logging systems in other languages, it’ll categorize logs, provide log levels, and has some log filtering capabilities. So I changed my tracing class that connects to the Ruby script into a log target. This was much nicer since any code using the standard mx.logging package is now compatible just by add the target.

However something still bothered me, I didn’t like the filtering controls being done in ActionScript. I mean it’s nice to have, but I really don’t see why we have to re-code and re-compile just to view a different log category and/or level. Sure a nice little component could be made to handle this at runtime but that didn’t seem necessary either. Certainly there must be dozens of existing logging apps out there for doing just this.

After some digging, I found Apache’s Chainsaw v2 to be a good fit. It has the filtering features I wanted, it’s cross-platform (interestingly as a webstart on windows and linux but native for osx), it’s by a huge well respected organization, and it’s free. With a little work to create the Log4j based log messages and connection to Chainsaw, this logging target is now a part of my standard workflow and so I thought I’d share.

Features

  • Log category and level filtering done externally at runtime
  • Chainsaw features also include log message filtering by search query, builds category tree, customizing log presentation, and log saving/loading
  • Log events are Log4j XML messages and should be able to tie with other compatible systems

Usage Example

After you’ve added the logging.swc to your project’s library path, the following example will log to Chainsaw.

package nochump.logdemo {
	import flash.display.Sprite;
	import mx.logging.*;
	import nochump.logging.target.Log4jXMLSocketTarget;
	public class LogDemo extends Sprite {
		protected static const logger:ILogger = Log.getLogger("nochump.logdemo.LogDemo");
		Log.addTarget(new Log4jXMLSocketTarget());
		public function LogDemo() {
			logger.debug("Hello debug message");
			logger.info("Hello info message");
			logger.warn("Hello warn message");
			logger.error("Hello error message");
			logger.fatal("Hello fatal message");
		}
	}
}

Before running the swf, fire up Chainsaw v2 and load the supplied log4jconf.xml file when it asks. This creates an XMLSocketReceiver which you should see in the receivers panel. Running the above example shows up in Chainsaw like the following.

ss-chainsaw-logdemo.gif

Download
nochump-logging-10-dist.zip

Revisiting 3D in flash

So recently I start working on a 3d engine again. I had toyed around with writing one back in the flash mx days but the speed of the flash player prior to version 9 was a major hurdle. Obviously even with 9, you’re not going to get 3d quality on par with the popular games out now without hardware acceleration. But seeing all the exciting Papervision3D based demos in the recent months and being blown away by this SWFZ demo renewed my interest. Speaking of which, there was another great 3d engine demo with an dancing Yoshi but I lost my bookmark to it :( Sound familiar to anyone and might have a link?

Another thought is the possibility of having hardware acceleration in the future via Apollo. There is one question on the Apollo developer FAQ:

Will developers be able to extend Apollo with native code?

No. This functionality will not be available in Apollo 1.0.

So maybe in 1.0.1? :)

Well I’m sure there’s lots of other concerns involved with adding OpenGL and DirectX but can you imagine if Apollo offered this? I’m not pushing it for the flash player, it’s not worth the risk of bloating the player size thus affecting the penetration rate. But for Apollo? It’s desktop and if they did it for Director I would bet it’s possible and that they’re considering it.

Anyways I just wanted to ramble on a little about 3d in flash in general. As for my engine, it’s mostly a learning experience and not something I’m looking to release as a usable library.

Update: April 12, 2007

So I finally found that 3D dancing Yoshi demo, one of the 1st Flash9 3D demos I came across and it turns out it was the SWFZ engine all along! Check it out.

AS3 Runtime Font Loading

Here’s a little experiment with loading fonts dynamically at runtime. So what’s this good for? Well let’s say you have a flash application where you want to allow users to customize the text formatting for some text box. Typically you would provide a small set of fonts which would all get embedded into the swf but this isn’t very flexible or ideal. Changing font’s or adding new one’s require rebuilding the swf. Also if only one or two fonts get used then all the other extra fonts do nothing but bloat the swf size. For this situation, it would be ideal to externalize the fonts and only load in the one’s needed.

Flash never supported this feature but some developer’s found ways around it. In particular, there was Shared Fonts Manager. However the author’s approach, although very impressive and useful, was a hack and not the easiest to use. With the major changes in flash 9, I got curious if runtime font loading was easier to do now and fortunately it is.

Approach

This isn’t new or anything, apparently all assets embedded in a swf become associated with a class and the ApplicationDomain object is the way to access classes in other swfs. The Flex documentation describes these topics but here, the focus is on fonts.

So first off, create the external font asset swf with something like the following:

package {

	import flash.display.Sprite;

	public class FontLibrary extends Sprite {

		[Embed(systemFont='Bank Gothic', fontName='emBank Gothic', mimeType='application/x-font')]
		public static var BankGothicFont:Class;

	}

}

Keep track of the class names you use and the fontName attribute of the Embed statement as that will be font name you’ll have to use in a text format. You can embed as many fonts within the swf as you like. I won’t describe the other features of the embed statement as they have been pretty well covered elsewhere.

After the swf is built (for this example let’s call it fontlibrary.swf), you load it like any normal swf via a flash.display.Loader object. After it is loaded, you just need to register the font class associated with the embedded font. Here’s an example of loading and registering the font library swf from above.

var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler);
loader.load(new URLRequest("fontlibrary.swf"));

private function completeHandler(event:Event):void {
	var FontLibrary:Class = event.target.applicationDomain.getDefinition("FontLibrary") as Class;
	Font.registerFont(FontLibrary.BankGothicFont);
	var tf:TextField = new TextField();
	tf.defaultTextFormat = new TextFormat("emBank Gothic", 12, 0);
	tf.embedFonts = true;
	tf.rotation = 15; // to demonstrate the embed worked
	tf.text = "blah blah blahnblah blah blahnblah blah blah ";
	addChild(tf);
}

If you’d like to grab a little demo with source, here’s a download.

More Thoughts

Another approach for the font asset swfs is to keep the main application class empty and include specific font classes thru the -source-path and -includes compiler options. A font class would then look something like this:

package {

	import flash.text.Font;

	[Embed(systemFont='Bank Gothic', fontName='emBank Gothic', mimeType='application/x-font')]
	public class BankGothicNormalFont extends Font {}

}

With this it won’t matter what the definition name of the main application class is (which was “FontLibrary” in the earlier example) or would you need to know the name of the static property associated with the font, you would just register the included font class such as “BankGothicNormalFont”. I prefer this approach better because of this and that it gives a little more control over to my build scripts. Say you want a font swf to contain more than one font, with the first approach you’ll need to edit the main application class to add the embeds but here you can just edit your build script to include the other font classes (assuming they’re already written).

Another thought was using the component compiler (compc). With compc you can embed non-source files directly however I have not tried it with fonts. It doesn’t seem like it gives you controls over the font style, weight, or other attributes available with the embed syntax. I played with some other options but none seem that great.

There are also runtime shared libraries (RSL) and modules with 2.0.1. I haven’t used them so if I’m wrong please let me know but from my understanding, RSLs do externalize assets and load at runtime however they are loaded when the swf loads. There is no control in actionscript for the loading of RSLs it appears. As for modules, I’m guessing they would be the better approach but not sure what advantages they offer over just using the ApplicationDomain object. Perhaps it has some management features I dunno. I can see a problem when loading and registering the same font swf twice. Well I’ll have to look into using modules.

Using other types within packages

I was doing something, I forget what it was now, but it got me curious about functions defined in some of the flash player native packages. The flash.net, flash.profiler, flash.system, and flash.utils packages all have functions defined in the package itself rather than in a class as static methods. This got me wondering if it was possible to do this with my own packages. Typically what’s defined in a package file is a class or interface which I thought were the only allowed but apparently not.

You can define a package function like so:

// file: src/nochump/util/string/repeatString.as
package nochump.util.string {

	public function repeatString(s:String, times:int):String {
		return new Array(times).join(s);
	}

}

You can then use it like this:

// file: src/MainApp.as
package {

	import flash.display.Sprite;
	import nochump.util.string.repeatString;

	public class MainApp extends Sprite {

		public function MainApp() {
			trace(repeatString("Wokka", 3));
		}

	}

}

Also, any type can be defined:

// file: src/nochump/util/math/TWO_PI.as
package nochump.util.math {

	public const TWO_PI:Number = Math.PI * 2;

}

Use this like so.

// file: src/MainApp.as
package {

	import flash.display.Sprite;
	import nochump.util.math.TWO_PI;

	public class MainApp extends Sprite {

		public function MainApp() {
			trace(TWO_PI);
		}

	}

}

Of course this isn’t really advantageous if you have to define a lot of types as you’ll need a separate file for each definition. A file can only have one externally visible definition otherwise you get an error.

I don’t know often I would use this, it’s just better to give your definitions a more specific context. Doing things this way can get back into a procedural programming style. If you do want to define things this way, be sure it’s something very generic that just deals with primitive types or types in the same package.

It’s not all bad tho, there are some small advantages. For one, it saves an extra object reference to access the definition. As in the example above, you can just call repeatString instead of something like StringUtil.repeatString. Yes, very minor. Another plus is it can save a bit of space in terms of what gets compiled into your swf. Let’s take a StringUtil class that has say 20 methods for various things like trimming, padding, and whatever else but you only need to use one of those methods. Rather than importing the whole class you can try something like the approach presented here. Of course, you can always just copy and paste that method to your project somewhere.

Anyways, I wasn’t sure if others have covered this. Heck, it’s probably right there in in the manual or ECMAScript specification but whatever. Just sharing what I learned today. :)

AS3 Zip Library Release

Here’s an ActionScript 3 based library for reading and writing zip files. I wrote this for another project I’m messing around with and thought I’d release it. I realize there’s already a useful library out there called FZip which is faster at uncompressing zip files as it uses the native uncompress method. However, it may require a script to preprocess a zip and inject Addler32 checksums which this library avoids by implementing a deflate compression decoder (inflater). If you are dealing with zips that only store files or run Python I recommend you check out FZip otherwise give this a try.

Features

  • Read or write zip files
  • Interface based on Java API (java.util.zip package)

Demo

This movie requires Flash Player 9

The source for this demo is available here.

Documentation

ASDoc Documentation

Download

The zip library is available as a swc component:
nochump-ziplib-105-dist.zip
The source files and documentation are also available:
nochump-ziplib-105-src.zip

nochump-ziplib-1.0-docs.zip

License

MIT

Usage

Below are examples of reading from a zip and writing to a new zip.

// read from a zip
import flash.utils.IDataInput;
import nochump.util.zip.*;

var loadedData:IDataInput;
// load a zip via URLStream or URLLoader using binary data format...
// create zip file
var zipFile:ZipFile = new ZipFile(loadedData);
for(var i:int = 0; i < zipFile.entries.length; i++) {
	var entry:ZipEntry = zipFile.entries[i];
	trace(entry.name);
	// extract the entry's data from the zip
	var data:ByteArray = zipFile.getInput(entry);
	trace(data.toString());
}
// write to a new zip

import flash.utils.ByteArray;
import nochump.util.zip.*;

// file info
var fileName:String = "helloworld.bin";
var fileData:ByteArray = new ByteArray();
fileData.writeUTF("Hello World!");
var zipOut:ZipOutput = new ZipOutput();
// Add entry to zip
var ze:ZipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(ze);
zipOut.write(fileData);
zipOut.closeEntry();
// end the zip
zipOut.finish();
// access the zip data
var zipData:ByteArray = zipOut.byteArray;

Update: April 11, 2007

Updated the library to use Apollo’s ByteArray inflate/deflate native methods when running in the Apollo environment as pointed out by Ian Thomas. The current version is 1.0.1 built with acompc from the Apollo SDK. I’ve also tested the Apollo compatible swc under a regular as3 app and everything worked fine.

Update: July 29, 2007

Supports adding a zip file comment to ZipOutput. Use ZipOutput.comment =”Your comment here”.

Update: January 28, 2008

Changed license to LGPL.

Update: November 22, 2008

Changed license to MIT.

Testing WP-SWFObject…

Just trying out WP-SWFObject, a WordPress plugin for embedding swf files in posts that uses SWFObject. Below is a Flash 9 swf:

This movie requires Flash Player 9

It seems to work nicely. Although I couldn’t read the author’s site, the installion was pretty easy. Just one little thing bugged me which was that the plugin files have to be placed in directly in the plugin folder, it won’t work within a subfolder.

Anyways there’s a few things left to be desired. For one, it looks like player version checking is global instead of on a per swf basis. The same goes for the other swf parameters. Also, the replacement content only allows text…but I’m just being picky on this issue, it’s fine for quick swf posts.

The only other issue I ran into is with the Hemingway theme I’m currently using, the plugin does not take effect on the front page. But I’ll eventually replace this theme with something more colorful, I just liked it much better than the default theme.

Flex Compiler Shell

Well I got around to playing with fcsh and man it’s so much faster. For one of my projects, each build (with incremental=true option) takes about 4-5 seconds. Under fcsh, the same project initally takes that long but each build thereafter using the compile id command took only 200ms or so even with changes to various source files.

Now to figure out how to use it with Ant. I found this post by Brian Diette and tried out his suggestion by setting the inputstring attribute for an exec task which worked. However, this approach executes a new shell process each time so it does not take advantage of the libraries loaded into memory with a single persistent one. For now, I have fcsh as an external tool in Eclipse which shows up in the console view. I then edited my Ant build script to echo the mxml command string instead of executing which I can paste it into the fcsh console and then just call compile id on subsequent builds. Yea it’s ugly but it’ll do for now.

Flash 9 XML vs. XMLDocument

Was going over some older Flex 2 beta posts by Ralf Bokelberg, a developer I very much admire, and found this interesting piece regarding the speed of XML vs. XMLDocument objects. Out of curiousity, I quickly tested his script with the latest Flash Player release (9.0.28.0) and sure enough, XMLDocument still beat out XML. I guess the E4X expressions remains a bit cumbersome performance-wise but it’s still very fast considering this test is being run 10,000 times. Certainly the lesser code and better readability benefits of E4X outweighs this minor performance hit but I thought it was interesting.