Automating Image Creation With JSFL

December 7, 2009 – 9:02 pm

A while ago Steve wrote a post about converting images to SWFs to minimise loading times.  In the right circumstances it can be a very nice tactic, as it makes such a huge difference.

Anyway, a project manager that Steve was working with heard about this, loved the idea, and by coincidence I am now working with said project manager.

While from my point of view it didn’t really change things from my end, it meant quite a bit of work for the designer.

Because I’m such a nice person, I knocked up some JSFL for him to automate the process, and now I’m sharing it with everyone.  Christmas spirit abounds…

The JSFL runs through the FLA’s library, and exports all images, reflecting the library folder structure in the saved path.  If you’re new to JSFL then all you have to do is save the JSFL file somewhere, and in Flash go to Commands > Run Command, and select the JSFL.

Feel free to download the JSFL, or just take the code from below:

var doc = fl.getDocumentDOM();
var items = doc.library.items;
var len = items.length;

fl.outputPanel.clear();

var path = fl.browseForFolderURL("Select a folder") + '/';

for (var xi = 0; xi < items.length; xi++){

	doc.selectAll();
	if (doc.selection.length > 0) doc.deleteSelection();

	var item = items[xi];
	var currFolder = '';

	if (item.itemType == 'bitmap'){

		doc.addItem({x: 0, y: 0}, item);

		doc.selectAll();
		doc.align('top', true);
		doc.align('left', true);

		var tName = item.name.split('.');
		var pArray = tName[0].split('/');

		for (var xp = 0; xp < pArray.length - 1; xp++){
			currFolder += pArray[xp] + '/';

			if (!(FLfile.exists(path + currFolder))) FLfile.createFolder(path + currFolder);
		}

		doc.exportSWF(path + tName[0] + ".swf");

		fl.trace('Exported ' + path + tName[0] + '.swf');
	}
}

Incidentally, there are some really useful JSFL scripts from Fuel, on Google Code. I highly recommend having a quick look…

MultiLoader – for all your loading needs…

July 30, 2009 – 9:21 pm

I’ve recently had a chance to work on a project I’ve wanted to get on with for ages, and I’ve just completed the Beta release of MultiLoader.

MultiLoader can load in images, text, XML, sounds and videos in a consistent way, and allows you to manage the loading in a number of ways.  It has pretty extensive functionality – including, among other things:

  • Simple to use
  • Allows prioritising of items
  • Force immediate load of an item
  • Connection pooling
  • Many debugging and error handling options
  • A debugging profiler
  • Queue management
  • Methods for extracting assets from the Flash library

I’ve used BulkLoader on a few projects in the past, and it has saved me a lot of time in past projects, but there were a few things about it that didn’t suit me.  As an FDT user, I’m quite picky about having Errors and Warnings in my projects. That’s part of a debate which can go on forever, as most of them are not errors as such in the eyes of the actual compilers, but I live by FDT’s rules these days, so I want to keep it happy!

The profiler is quite a nice feature – as you’d expect it gives you a running graphical display of what’s going on:

 

Another useful feature is the report, which gives you a pretty print summary trace of what’s going on at that point, ie details of all the loaded items, all the pending items, all the failed items and so on…

The documentation is pretty extensive, and should answer most of your questions regarding usage.

I used BulkLoader for reference while developing MultiLoader, to help myself avoid any unexpected issues, and I’d like to say thanks to Arthur Debert, who has by far the best attitude I have ever come across in my years in this industry.

Thanks also to Shane McCartney, as usual, as I’ve used some of his ideas and adapted some of his utility and abstract classes in the development. 

Please note that this is a Beta release, which means that it’s probably not suitable for use in commercial projects yet.  I would love any feedback – good or bad – and I hope you find it useful!

Finally, MultiLoader is a rubbish name!  I haven’t been able to decide on the final name yet, so again, any suggestions are welcome.

Colour graduation steps

July 6, 2009 – 11:38 pm

I had to get the graduations between a couple of colours the other day, and in lieu of finding much of use online, I thought I’d put my solution up here in case it can help anybody who’s looking for something similar.

 

Usage is really simple:

getColourSteps(0xFF0000, 0x0000FF, 10);

 

...or as a simple demo:

var colours : Array = getColourSteps(0xFF0000, 0x0000FF, 10);

for (var i : uint; i < colours.length; ++i) {
    var shape : Shape = new Shape();
    shape.graphics.beginFill(colours[i]);
    shape.graphics.drawRect(50*i, 0, 50, 50);
    addChild(shape);
}

 

So here's the code. As always, use it how you want, but this time there's the proviso that you have to keep the "u" in colour...

function getColourSteps(hex_1 : uint, hex_2 : uint, steps : uint) : Array {
	var arr : Array = [];

	for (var i : uint; i < steps; i++) {
		arr.push(getColourStep(hex_1, hex_2, i / (steps-1)));
	}

	return arr;
}

function getColourStep(hex_1 : uint, hex_2 : uint, percent : Number) : uint {

	var tmpHex : uint;
	var newHex : uint;
	var i : int;

	while (i++ < 4) {
		tmpHex = hex_1 >> i*8 & 255;
		tmpHex += ((hex_2 >> i*8 & 255) - tmpHex) * percent;
		newHex = newHex | tmpHex << i*8;
	}

	return newHex;
}

Switching a type check

January 25, 2009 – 6:23 am

A colleague was recently trying to determine a way to use a Switch for the type of Display Object he was feeding, that is, to have a case for a Sprite, another for a Bitmap, etc.

In if…else language it would be easy, using the is operator:

if (obj is Bitmap) {
    doBitmap();
} else  if (obj is Sprite) {
    doSprite();
...etc

…but it’s annoying that the nature of “is” doesn’t lend itself to switches, and it seems that other languages have the same stumbling block.

It would obviously be best to make sure that everything you are feeding in is your own class with a method doThing(), as this would make things much neater and cleaner, but that’s not always possible, including in the case I was being shown.

Instead I was toying with the following solution:

var bmp : Bitmap = new Bitmap();
var spr : Sprite = new Sprite();
var obj : Object = {};

function getType(obj : *) : void {
	switch(true) {
		case obj is Bitmap:
			trace('Bitmap');
			break;
		case obj is Sprite:
			trace('Sprite');
			break;
		default:
			trace('Neither');
			break;
	}
}

getType(bmp);
getType(spr);
getType(obj);

As with any switch, you need to be careful with the order in which you have the statements, eg you’d have MovieClip before Sprite in the cases, otherwise it would get trapped too early.

Interestingly, this solution seems to work in VB.NET but not C#, as C# only deals with Strings & Ints, while VB takes any primitive.

It started as being about decompilers…

January 24, 2009 – 11:21 pm

It’s been ages since I tried using a decompiler, but I did tonight, just because I was quite intrigued how somebody had solved a problem. I tried Sothink’s (no link cos I’m *really* not recommending it!), and it was absolutely no use.  It’s not really a surprise – decompilers have a pretty impossible job – but it was actually a little comforting.

Generally, if we’re honest, then people use decompilers to try to steal code.  Most of us did it when we were first learning AS, but only to be somewhat let down by the rubbish delivered to us, and realise that we actually had to learn it. The code compiles, of course, but it’s of no use to anyone by the time it has been re-re-assembled.

I hope there’ll be some new Flash developers reading this so I can save them some pain.  If you want to get hold of somebody’s code, there’s no shame in it – personally I take it as a great compliment when I am asked, and I’ve asked for other peoples’ code more than once – and you can also gauge a lot from the response you get when you ask, as well.  Obviously I’m talking about snippets here, as opposed to sending you the full source code for a project.

Some people just flat out refuse. While this may be seen as understandable, I see this as being an awful ethic. The people who I have met who keep their code “secret” tend to be the same ones who complain about other people’s code the most. If you’re not helping others to learn, then you’re the part of the problem.

Others ask you for money. Unless you’re actually asking for a complete working model then I’d say it’s never worth it. You’ll learn far more by working it out yourself, and again, people who charge just aren’t helping, and their code will probably not help much more. However, if somebody’s helping you, and there’s a “Donate” on their site, then don’t be selfish – they’re helping you to earn more, and to make your life easier, so do the right thing, even if it’s a small amount!

Some give it away, unrestricted, without asking. At least, I’d guess there are people like this, although I’ve never come across any…

The rest will give you advice. Maybe send you a snippet, or point you in the right direction. This is the most useful kind of person you’ll ever find in your work – whoever wrote it knows some stuff you don’t, so you really should listen to them. And treasure your micro mentor!

As a freelancer, I’d like to walk into projects and find them in a good state. This just doesn’t happen, though, which is the nature of the beast. A lot of AS3 coders in London at the moment are just winging it, and scarily often they’re happy to admit it to other developers, but as employers generally have no way of judging coders until the project’s due, and agencies never care who they put forward for a role, they keep getting re-employed and making life more difficult for those who have to sort out their mess.  In the past 6 months I’ve met 4 AS3 contractors who only code within the Flash IDE, which pretty much sums it up.

I’d equate learning ActionScript to a decorator pattern – there is a very definite, solid base to learn, and from there you can expand in any directions you wish (video, performance, 3D etc). Many developers have moved over from AS2 without bothering to learn encapsulation, best practice, and patterns etc. It’s a whole new world, but there’s a definite bleed from the old.

Over time, some developers will drop out, and others will surprise. In the meantime, then if you know something, then be happy to share it, and help others to learn it. All programmers are still learning, and the best ones are never worried about asking advice from their peers. Just make sure you don’t ask unless you need to!

P.S. If you wish to purchase the HTML source of this article, please e-mail…

Tweensy – it’ll save the world…

September 4, 2008 – 12:43 pm

My friend Shane at Lost In Actionscript has released the private beta of his new tweening engine, Tweensy, and it’s set to destroy the competition. I’ve been using it for a few months now, but he’s recently gone crazy with it, extending it in all sorts of amazing ways.

At its simplest (motion tweens etc) it’s a joy to use, and wickedly efficient, but the extensions are what will make it so much more useful and interesting. Stop wasting your time here and go and play with it. And never look back…

Google Chrome

September 3, 2008 – 11:31 am

I’ve just got my copy of Google’s Chrome Beta, their response to IE8. Obviously it was always going to be superior to Microsoft’s legacy mess, but regardless, first impressions are very good. 

They’ve made some interesting, and potentially great choices, with each tab running as an individual process (not just an individual thread), and incorporating the V8 JavaScript engine.  Some of their more interesting ideas include an “Incognito” tab, which apparently stores absolutely nothing on your system, stopping all popups by restricting them to the corner of the tab which opened them, and it comes tied in to a load of the Google APIs by default, like the phishing filters, and Google Suggest.  It’s well worth a look, so sign yourself up, and start playing.

On the other hand, it’s another browser to check your HTML & CSS on. Cos there weren’t enough already…

A Simple & Quick Preloader

August 22, 2008 – 3:30 pm

Often in my work then I have to chuck something online quickly for clients or whoever to be able to see, and it’s usually nice to have a preloader. It doesn’t exactly take long to create one from scratch, but as I’ve been having to do a lot of it recently, I decided to write a generic AS3 preloader. The difference with this one is that the SWF doesn’t need to be touched – all the necessary parameters are dealt with by the FlashVars. Using this, it takes literally a few minutes to add the preloader.

You can have a loading bar and/or percentage tracker, and you can format the colours, sizes and position of them. The full code is in my code wiki. It’s not much of a wiki, really, as I don’t let anybody else edit it, but it’s just a simple way of making it all readily accessible. All the details about usage and parameters etc are in the wiki.

As always, take anything you like, and don’t worry about copyright, but a link back would be nice if you feel so inclined.

Time conversion using the proxy class

August 1, 2008 – 12:18 pm

I’m quite a fan of neat, sparse code, especially if efficiency isn’t so important. Following on from my date stuff earlier, I had to have a few conversion utils, including time conversions. Everyone’s been through the boredom of creating the methods for millisecondsToSeconds, secondsToMinutes, minutesToHours and so on, and then making composite functions to jump from seconds to hours or whatever, but it’s a pretty dull process.

Using a simple implementation of the proxy class, the following takes whatever combination you like of unitToUnit from milliseconds, seconds, minutes, hours, days and weeks, and automatically works it out. So while, due to the nature of extending proxies, it’s by no means efficient, it’s definitely elegant, and could be easily adapted for similarly incremental units, eg bytes & bits.

package com.utils {

 /**
  * @author chris@acleveraddress.com
  */

 import flash.utils.Proxy;
 import flash.utils.flash_proxy;

 dynamic public class TimeUtil extends Proxy {

  private var units : Array = [
   ["weeks",7],
   ["days",24],
   ["hours",60],
   ["minutes",60],
   ["seconds",1000],
   ["milliseconds"]
  ];

  public function TimeUtil() {
  }

  override flash_proxy function callProperty(name : *, ...args : *) : * {
   var arr : Array = String(name).toLowerCase().split("to");
   var from : uint = indexOfMulti(units, arr[0]);
   var to : uint = indexOfMulti(units, arr[1]);
   var i : Number = args[0];

   while (from != to) {
    if (to > from) {
     i *= units[from++][1];
    } else {
     i /= units[--from][1];
    }
   }

   return i;
  }

  private function indexOfMulti(arr : Array, str : String) : int {
   for each (var a : Array in arr) {
    if (a[0] == str) return arr.indexOf(a);
   }
   throw('Function badly named');
  }
 }
}

Usage:

var tu : TimeUtil = new TimeUtil();
trace(tu.millisecondsToWeeks(604800000));

PHP Date in AS3

July 28, 2008 – 10:37 am

I had to do some date formatting for a project recently, and realised I missed the PHP Date function, so I recreated it in Actionscript 3. While I was doing it I noticed it’s been done a few times before, but there tend to be quite a few of the options missed out, or mistakes made, especially when it comes to the ISO stuff. The only function I couldn’t replicate properly was the Timezone identifier (e) as AS simply doesn’t have access to that information, so it could only be faked.

The example shows lovely slashes being used in the string but in the actual code you’ll have to escape (double) them or use a dollar symbol. Usage: DateUtils.date(‘c’, new Date(2008, 01, 01)); The date defaults to the (client side) date if it’s null.

Source here.