Calling ActionScript 3 from Javascript

27.03.2008

I really hate Javascript. It’s so inconsistent, loosely typed and annoying to debug. But there are some things that you just can’t do without Javascript. For instance, allowing an HTML page to communicate back and forth with an embedded Flex application.

The Flex documentation gives a very good example of how to call an AS3 method from Javascript. It’s simple, it’s easy to understand and it doesn’t work properly in a real life scenario. But let’s start with the AS3 code example from the documentation:

function callMe(name:String):String
{
    return "busy signal";
}
ExternalInterface.addCallback("myFunction", callMe);

And here’s the corresponding Javascript and object/embed tags for use in an HTML page:

<script language="JavaScript">
    // result gets the value "busy signal"
    var result = flashObject.myFunction("my name");
</script>
...
<object id="flashObject"...>
    ...
    <embed name="flashObject".../>
</object>

All well and good. And it works, too. That is, except when you are dynamically adding object/embed tags with Javascript’s document.write(). Which is what you do, if you don’t want that annoying security frame around your Flex application in the browser. If you use document.write(), the above method only works in Internet Explorer. Not FireFox. Whaaa? I could have sort-of understood it, if it were the other way around.

Anyways. The solution, which I was unable to find in the Flex docs, is the call the flashObject’s method using the following Javascript syntax:

    var result = document["flashObject"].myFunction("my name");

Sheez. Only took me an hour to figure out. Hope someone else finds this post if they are in a similar situation.

I really hate Javascript.


Flex 3 is Released

29.02.2008

The long wait is over! Well, ok, the wait really wasn’t that long, because there have been three betas out of which the last two were feature complete and well functioning.

But anyways, grab it from here: www.adobe.com/flex.


Flex, C# and Asynchronous Sockets Chat

18.02.2008

I’ve previously written about the wonders of Rich Internet Applications (RIAs), and I’ve have been looking at both Silverlight and Adobe Flex. For now, at least, I go with Flex, because it’s the mature and complete of the two.

After being sidetracked for a while with my love for casinos and games, I thought it would be appropriate to return to something more business-friendly. So, for my next project, I have chosen to implement a chat client/server with Flex on the frontend and C# on the backend. It could be used for customer service or be a community feature on a website.

I was thinking about doing the whole thing with Web Services, but that has a couple of shortcomings.

First of all, Web Services are stateless; Consuming a Web Service means sending one request from a client to a server and receiving one response. Each request/response pair is separate from all others - stateless. A chat application needs to be more “connected” the entire time, so that it’s possible to push things from either end to the other without the client having to continuously poll the server.

Secondly, Web Services include a bit of overhead in terms of SOAP envelopes, and requires code-generation (in Flex), etc., and I wanted something clean and fast. Ok, sure, my chat application probably won’t be used by thousands of simultaneous users, but why go for the Kia when you can have the Ferrari at more or less the same implementation cost?

The fastest ride in town is “asynchronous sockets”, and the easiest and cleanest implementation of that is using TCP. And luckily, it’s completely supported by both Flex and C#, so that’s what I went with.

Chat Client

http://www.topholt.com/ChatClient/bin-debug/ChatClient.html

A Few Implementation Details 

The chat client above is setup to use port 8000 for communications, so your firewall should allow you to make TCP connections to that port if you want to try it out. It shouldn’t be a big deal. If you download the code, you can modify it to use whatever port you like.

All communications are currently unsecured, which means no encryption, no authentication, no authorization and no data checks of any kind. The downside is that anyone can mess with the chat, but the upside is that you, dear readers, can grab the code and easily modify it for your own needs.

The application’s communications architecture is simple: Each time someone says something, a 256 byte UTF-8 encoded datagram is sent to the server and then immediately distributed to all connected clients, including the sender. That way, everyone sees what everyone is writing.

Edit: View Source on the Flash/Flex file to get the client code or download the zip. And get the C# server source code here. It’s built with VS 2008 and compiled for .NET 3.5, but should work just as fine with 2.0.

Edit 2: I’m currently having server hosting problems, so I am getting ready to move my stuff to a new provider. Therefore, the chat server may be offline at times. The code is still available for download, though.


Arkanoid Using Torque 2D

20.01.2008

Right! I’m getting seriously side-tracked here. I was planning on using a bit of my spare time to investigate news on the Rich Internet Applications (RIA) front, but I found myself trying to create an Arkanoid clone in Flex.

It didn’t go too well, because Flex/Flash doesn’t update the visuals fast enough. I think it has to do with the fact that Flash rendering uses a software device, instead of direct hardware access, such as through DirectX or OpenGL.

At any rate, I just couldn’t let the thought of creating an Arkanoid game be, so I browsed around and found GarageGames’ excellent product, Torque Game Builder. Using the product’s out-of-the-box features, some sample graphics and a bit of TorqueScript, I have put together the following:

arkanoidtest1.png

To see it in action, just download the following file, un-zip it and run the .exe file: www.topholt.com/arkanoid/arkanoidtest1.zip

I’m actually pretty happy with it, considering that it only took a few hours to put together. It uses simple rigid body physics (!) to bounce the ball, and just for fun I added rotation to the paddle.

There are tons of things still missing or not working correctly. Some of the collision detections are a bit off, and the physics are not completely correct - but that’s my fault, not the product’s. I think I’ll keep playing with this and see if I could make it into a real “casual” game.

Comments are always welcome!


Flex Framerate / Movement Woes

12.01.2008

I’ve been experimenting a bit more with Flex, but seems to have hit a roadblock on my next project. I want to build an Arkanoid clone, but so far have not found a suitable way to move a (png) ball across the screen smoothly.

Currently, my efforts look like this:

Arkanoid Test 1

http://www.topholt.com/Arkanoid/bin-release/Arkanoid.html

Use the slider at the bottom to change movement speeds (not FPS, but number of pixels moved each time).

I’ve updated the framerate of the Flex application to 99 fps, but still movement is very jerky.

I have tried using the FRAME_ENTER event to move the ball. I have tried using a Timer. I’ve tried it with and without a background image. I’ve tried using a Move object and intercepting collisions. It all looks the same. Nothing gets me the results I’m looking for.

Is it really not possible to move a ball smoothly? Someone please help!


A Slot Machine in Flex

28.12.2007

Slot machines fascinate me; For some strange reason both my girlfriend and I can walk into a casino and spend literally hours there playing slot machines for pennies. I consider myself a fairly rational person, but even though I know what the odds are of hitting the jackpot, I still think it’s a great game to play.

And I’m not alone: Slots is the number one game played in casinos around the world. It’s the worst game odds-wise, yet the most played. Go figure.

Lately, we’ve been playing a bit online, because we can’t take our daughter to a casino :) So instead of spending a ton of money online, I decided to write a small slot machine application in Flex - just for fun.

Now all I need is to register a company on Gibraltar and get a casino license and I’m all set to become insanely rich!

Try it out here: http://www.topholt.com/SlotMachine/bin-release/SlotMachine.html

It was fun to implement, because I found out that image filters can be applied directly on a BitmapData instance. I use a BlurFilter to create a blurred version of the block graphics to simulate spinning the reels and the “result” of a spin is drawn on-the-fly. Also, there’s some overlay shadowing as well. All in all pretty cool, because it means no pre-processing of the images in Photoshop.

I haven’t calculated the stats on the slot machine yet, nor have I tuned the reels accordingly. Also, there’s no backend - the entire thing runs as a stand-alone SWF-file. And the graphics are crap.

So perhaps there’s still some way to go before I open my casino…

Edit: Cleaned the code up a bit so View Source is now enabled. Please note that I used Flex Builder 3 beta 3 to build this!


Online Flex Compiler with ASP.NET Web Service

18.12.2007

I just received a couple of very cool books from Adobe a few days ago along with a training DVD, and I’ve been trying to consume as much of it as I could while tying up some loose ends at work before the holidays.

Anyways, two things I like a lot about .NET is reflection and runtime compilation. So I thought I would see how far I could take my (limited) Flex knowledge in that direction, using the new Flex 3 beta 3.

I decided the best way forward would be to create an “online Flex compiler” – that is, a Flex application that allows the user to input some source code and have it compiled and executed directly.

Flex doesn’t allow runtime compilation, so my solution is based on a Flex front-end and an ASP.NET 3.5 Web Service backend, which in turn calls the Flex mxmlc.exe command-line compiler.

I should point out here that Adobe has created another command-line tool called Flex Compiler Shell (fcsh.exe), which boosts compilation time and contains a few features not present in mxmlc.exe. However, I decided that because fcsh.exe is in beta (not production-grade) and mxmlc.exe is a finished product (for Flex 2 at least), I should concentrate on the latter.

My idea was this: Any SWF-file can be compiled using either Flex Builder or mcmlc.exe, and such an SWF-file can also be dynamically loaded, for instance as a module, in a running Flex application.

So why not combine those two things? It might make for an interesting way to allow user-created content to be added to a community RIA in true Web 2.0 style.

Well, I didn’t get that far, but I got the technical solution working :)

The Solution

I can’t show you the finished solution, because I’m sure my poor little web server would choke under the stress of people playing with it – because it’s really quite fun. Instead, I’ve captured a screenshot for you to take a look at.

Dynamic Compiler Screenshot

It works like this:

  • - The screenshot above is of a Flex application called “DynamicCompilerClient.swf” that runs in a browser, and which contains a simple TextArea into which the source code for a simple Flex module is loaded.
  • - The user can change the code freely and then click “Compile and Run”. By clicking the button, the ASP.NET 3.5 Web Service “Service.asmx”, which was previously imported into Flex Builder, is called with the source code as input.
  • - The Web Service saves the received source code in a unique folder on the server that is available from http (eg. mapped as a Virtual directory) and then uses System.Diagnostics.Process to call the mxmlc.exe command-line tool. The standard output from the compiler is picked up by the Process and the resulting SWF-file “DynamicModule.swf” is saved in the folder.
  • - The Web Service returns a URL to the “DynamicModule.swf” to the calling “DynamicCompilerClient.swf”, which picks up that URL and loads the module using ModuleManager.GetModule(url).
  • - Once the module is loaded, the ModuleEvent.READY is fired, and the module is added to the canvas.

Thoughts on Implementation

Here are my current thoughts on the implementation:

  • - It works fine and only took a few hours to implement.
  • - Importing an ASP.NET Web Service into Flex Builder was easy and works great for my simple scenario. I haven’t tested complex data structures yet, but I imagine I will at some point.
  • - The Flex compilation process itself wasn’t as smooth as using .NET’s Microsoft.CSharp.CSharpCodeProvider etc., but on the other hand dynamic module loading in Flex seems to be less bothersome than dynamically loading (and particularly re-loading) assemblies in .NET.
  • - The command-line compiler was pretty slow – it takes approx. 2 seconds each time. However, I imagine a big speed penalty is incurred because mxmlc.exe launches a new Java Virtual Machine on each run and because results are not cached between runs. Fcsh fixes this to a great extent, I’m sure.
  • - I wouldn’t exactly call the solution I’ve implemented production grade. I don’t so much mean code-wise (it’s a mess), but rather the architecture: Calling a Web Service that in turn executes a command-line compiler that stores the result on disk and returns a URL seems to be a chain with a lot of weak links.
  • - There are, luckily, lots of ways to improve the stability of the solution. For instance, instead of doing things synchronously (which is what would cause my server to choke if I opened up to external requests), the Web Service could asynchronously queue the request in a database, and a Windows Service could then poll the queue, run the compiler and store the result also in the database, letting the Web Service (again asynchronously) return the result to the caller whenever it’s good and ready. In other words, it’s not so much a Flex/ASP.NET interoperability issue, it’s an implementation issue on my part.

Conclusion - and what about Silverlight?

The conclusion has to be: It works fine and I’m fairly happy with the results. It’s not runtime compilation in Flex, but it’s pretty close.

However, now I am really looking forward to Silverlight 2.0 beta, because it seems that this scenario is simpler to handle in a pure .NET environment. Runtime compilation will probably not be possible from within a Silverlight application either (CSharpCodeProvider calls .NET’s C# compiler csc.exe from the command-line behind the scenes), but at least the server-side logic would be less of a hack.

Comments? Thoughts? Let’s hear’em!


Adobe Flex 3 beta 3 is out!

13.12.2007

Just a quick post to let everyone know who hasn’t seen it already that Flex 3 beta 3 is out!

Grab it here: http://labs.adobe.com/technologies/flex/flexbuilder3/

(and read the release notes, there are steps you absolutely must follow to uninstall beta 2, etc)


A* Pathfinding with Silverlight - Not!

09.12.2007

Being a .NET fanboy, I thought I would reproduce the isometric pathfinding demo I made a couple of days in Flex, using Silverlight 1.1 (see the original post).

The A* algorithm, the mouse picking and the movement should be easy enough. But I immediately hit a snag: It’s apparently not possible to paint the image tiles onto another image?! And I refuse to draw the isometric “world” using 10 x 10 images! So I was unable to do it :(

It seems my point about Flex being the easy choice for RIAs until Silverlight is much more feature complete and mature still stands. I doubt all wishes are fulfilled in the 2.0 beta coming in the beginning of 2008.


A* Pathfinding in an isometric world with Flex

07.12.2007

I’m having way too much fun with Flex.. It didn’t take me more than a few nights to put together a small test of an isometric world and implement an A* algorithm for pathfinding. It’s not nearly done yet, particularly the motion is bad, but you can check it out here:

isopathfinder11.png

http://www.topholt.com/Flex/bin-release/IsoPathfinder.html

Perhaps I could spend some time this holiday season making it into a small game or something. Who knows.

If anyone are interested in the implementation details, let me know. The screen-to-tile-space conversion took me a while to figure out, and A* can be tricky as well.

Edit: I’ve added the ability to fire small pieces of cheese at the cursor, to test collision with walls. Just press ‘A’ and you’ll see it in action!

Edit: View Source is now available.