Sunday, December 21, 2008

Lua Alchemy v0.1a Released

The first release of Lua Alchemy has been released; the library SWC, demo, and code can be downloaded from here:
http://code.google.com/p/lua-alchemy/

Since my preview post (which is now running the same demo code) we have
  • Added many Lua scripting samples.
  • Fixed some memory leaks.
  • Cleaned up function callbacks created in Lua which would typically be used for event listeners.

Below is a preview of the release:

Note that the demo above requires Flash Player 10 (required by Alchemy and my use of the local file system to allow opening/saving files). It is also hosted here where it can take up a full browser screen and is much easier to read.

The next version will include syntax sugar so instead of calling as3.call(var, "function", param) you could call var.function(param) and similar calls to make calling ActionScript code look the same as calling Lua code.

Monday, December 15, 2008

LuaAlchemy Project v.1a Preview

Since my last post my experiment to make Lua a runtime scripting language in Flash using Alchemy has become a full open source project located here:
http://code.google.com/p/lua-alchemy/

I even have a partner named Alexander Gladysh whom I met on the Lua boards.

We are approaching a V.1a release of the project. Using LuaAlchemy you can now create any ActionScript class available at runtime, get/set properties, call functions, and set event listeners (actually you can return a Lua function to use as an ActionScript function). The Lua to ActionScript interface is a little raw right now but we plan on adding some Lua sugar to make accessing ActionScript objects, classes, and namespaces in Lua look and feel like using Lua objects.

Below is a preview of the release:

Note that the demo above requires Flash Player 10 (required by Alchemy and my use of the local file system to allow opening/saving files). It is also hosted here where it can take up a full browser screen and is much easier to read.

Along the way to this release we have encountered a few problems which I will discuss. The first problem was speed. Although the Alchemy V.4a compiled code was fast enough for our purposes, it was about 30 times slower running a life simulator written in Lua than natively compiled Lua. The release of Alchemy V.5a has made life run 4 times faster so progress is being made (v.4a had some debug code compiled in that slowed things down).

The second problem has been gluegen. Gluegen is a tool to help you create wrappers around C code that takes a mix of C and ActionScript code to generate C and ActionScript wrappers. Unfortunately this seems to interfear with CLibInit.setSprite() which we wanted to use to provide a sprite that Lua could use for stdin, stdout, and stderr. Glugen created code creates and inits CLibInit as static members and you seemingly need to call setSprite() before init(). We worked around that problem by providing an output TextArea in the demo below, but we plan on writing the wrapper ourselves and not using gluegen at all.

The third problem is related to garbage collection in Flash and Lua. To make Lua functions usable as an ActionScript function we call AS3_Function() to create an ActionScript function that calls a C callback function passing in some contextual data. This data includes some Lua references in a malloced structure and we would like to know when it isn't needed anymore so it can be released. We haven't figured out any way for Alchemy to tell us when the object is no longer needed. A future version will do some cleanup when the lua_state is closed.

Overall our experience has been a positive one and Alchemy is still in Alpha.

Tuesday, December 2, 2008

Lua ActionScript Alchemy

At Adobe MAX 2008 San Francisco, Alchemy was released. Alchemy was once known as FlaCC or Cassava and is a C/C++ to ActionScript compiler.

Alchemy works by translating C/C++ code to ActionScript through a LLVM compiler which instead of producing machine or bytecode produces ActionScript. The translated C/C++ code uses a big ActionScript ByteArray as the C/C++ heap and stack. The performance of alchemy is slow if you martial data from C/C++ code to ActionScript or back but faster (supposedly up to 10 times faster) than ActionScript code you write yourself for data intensive actions where everything operates in the C/C++ memory space - speed improvements over AS code are also due to LLVM doing code optimization which is missing from the normal AS compiler.

After downloading and setting up Alchemy, I started trying to port over a few C/C++ libraries. The following libraries have given me some trouble mainly with needing to adjust makefiles or the ./configure script: Angband, Nethack, guile, Python, Ruby, ARToolkitPlus, SDL, and Squeak. I haven't given up on them but I wasn't in the mood to do battle with Makefiles; I wanted to learn Alchemy.

My success came with compiling the scripting language Lua 5.1.4 and embedding it into a Flex application. The following proof of concept can run a Lua script which returns one or more values and are shown in the Lua Stack Panel. Lua can make the following calls into Flex:
  • getTextAreaProperty(property_name) - Returns the given property of the text area in the lower left hand corner.
  • setTextAreaProperty(property_name, value) - Sets the given property on the text area in the lower left hand corner (must accept string values).
  • callTextAreaFunction(function_name[, param1, ..., paramN]) - Calls a function on the text area in the lower left hand corner (must accept string values).
  • average(value1, ..., valueN) - Returns the average and sum of the given values.


Note that the demo above requires Flash Player 10 (required by Alchemy and my use of the local file system to allow opening/saving files). It is also hosted here.

Should I continue working on this library, I'd want to allow Lua to create and call functions on any arbitrary ActionScript class. Alchemy is still in beta and does have its own problems - not everything builds easily and while pure Alchemy code can be faster than ActionScript, marshaling from ActionScript to C/C++ code and back can slow things down - for example life.lua takes 4 seconds with the standard compile of Lua and 13 minutes! with the Alchemy build. Still it works quite well for my purposes of embedding a runtime scripting language into my Flex applications.

For more information check out the following blog posts:
Edit: Created a google code project to share efforts in using Alchemy to embed Lua in ActionScript. Uploaded the proof of concept:

Sunday, October 5, 2008

FlaCC (C/C++ to Flash Compiler)

More news on the C/C++ to Flash compiler, now called FlaCC. With this tool developed by Scott Petersen at Adobe would allow almost any arbitrary C/C++ code to be compiled down to ActionScript bytecode to run on the Flash player. I first heard of this at MAX 2007 and there will be a session at MAX 2008 on this (plus hints it will be in keynotes).

While we wait here are a few links to some more recent news:
The MAX 2008 Session is "Using C++ Libraries in Flash Player and Adobe AIR" Monday, November 17, 2:00 pm - 3:00 pm. I'm looking forward to that session.

Sunday, July 27, 2008

360|Flex

This coming August, I'll be heading out to San Jose to attend the 360 Flex conference:
http://www.360conferences.com/360flex/

I'm new to the Flex scene (almost a year now) and came from a background of 14 years of C++ cross-platform application development so it is exciting and different to immerse myself in the new culture. This is the first 360 I will have attended and only the second conference related to Flex (the first being MAX 2007 in Chicago). I'm now fortunate enough to be working for Universal Mind (as a contractor) and when I saw all the people taking vacation to attend 360, I knew I had to attend.

Of particular interest to me are sessions teaching frameworks, component building, design patterns, process (I'm a big process geek - how you do something is very important for maintainability), and low level programming. There are so many sessions that appeal to me at the same time that I'm going to have to make some rough decisions. Here is a list of the appealing sessions (fortunately I work with some of these people so I can pick their brain later):
  • Pre-Conference stuff I cannot attend because my plane doesn't land until 2pm
    • James Huang - The R1-RPC/J Toolkit and the D.eval API
    • Ben Stucki/Ryan Campbell - OpenFlux
  • Adam Flater - How to make your AIR app blow up with Merapi
  • Alex Harui - Versioning Support for Large Applications and Portals
  • Andrew Powell - Implementing BlazeDS
  • Axel Jensen - Project Workflow (trac,svn,ANT,XML...)
  • Ben Clinkinbeard - Concepts and Strategies for Creating Reusable Components
  • Ben Stucki - How to Build a Framework
  • Brad Umbaugh/RJ Owen - Diving Deep with the Flex Component Lifecycle
  • Brian Weisenthal - Architecting real-time and collaborative applications in Flex
  • Chet Haase - Filthy Rich [Flex] Clients
  • Chris Scott - Introduction to the Swiz Framework for Flex
  • Eric Ko - Reflective Programming
  • Jacob Wright - Advanced ActionScript APIs
  • Jeff Houser - How to Build Flex Components
  • Jeff Tapper - Unraveling the hassle with Drag an Drop in AIR
  • Jonathan Branam - Improve your programming by reading the Flex source code
  • Josh Tynjala - Polishing Components for the Unwashed Masses
  • Laura Arguello - Decoupling Flex Applications with Mate Framework
  • H. Paul Robertson - Advanced AIR and SQLite: An optimization conversation
  • Ryan Campbell - PlexiGlass (OpenFlux 3D Components)
  • Samuel Asher Rivello - Creating an MMO from Scratch with Adobe Flex 3… in 59 minutes.
  • Tom Gonzalez - Data Visualization and Dashboards with Flex
  • Troy Gardner - Advanced State management, the Heirarchical State Design Pattern
PS: The 360|Flex team sent me a 1GB flash drive with content from 360|Flex Atlanta and Europe. I could pass it on to a lucky commenter.

Friday, May 16, 2008

Best new Flash 10 Feature: File Access

The new Flash 10 Beta is out. While all the graphical improvements are fantastic, for me the best new feature is file access. I've written a few applications where I wanted to load or save files directly from Flex. Having to write a server just to upload the file to and then send back to Flash was pretty ridiculous just to preview an image that the user may or may not want to really upload. As long as the user is asked to load or save a file it should be safe.

Sunday, May 11, 2008

ActionScript Cross Compiler Theories

This post is a bit late coming, but I'm trying to be good and post once a week.

Last year after Adobe MAX 2007, I posted a bit on the preview of a C++ to ActionScript compiler. This year there has been a little more buzz buzz on the subject. I've been curious how this might be done and have a few theories:
  • Create a C++ parser/compiler to either produce Flash bytecodes or ActionScript. C++ is notoriously hard to parse so this would be quite a pain without something to get you started. There is a partial ANTLR grammar for C++ here.
  • Create a gcc backend to produce Flash bytecodes. All gcc languages compile to intermediate languages called GIMPLE and GENERIC. Target platforms "merely" translate this intermediate form to the target platform. See this link for more information. This path would be the most generic solution and allow any gcc language to be compiled to flash.
  • Leverage PyPy (a python VM generator and more) to create an ActionScript or Flash bytecode target. Of course this would only really help you use python unless you created a translator for C++, but flex-pypy is cool enough to mention.
Overall I think the gcc solution is the most likely and most powerful. I'm looking forward to the cross compiler and hope it will be included in Flex 4 as part of the broadening horizons theme.

Tuesday, April 29, 2008

Not Using Source Code Control is Insane!

"Like skydiving without checking your parachute or having sex with a stranger without using a condom." -- me, earlier today
I've worked for a few places that didn't use source code control properly or even at all before I started. But today, I met a new PHP programmer who didn't know what I was talking about when I mentioned source code control. He recently migrated over from writing and graphic design and has no background in computer science or software engineering so it isn't his fault really. The fault lies with those that brought him into the fold.

As far as I can tell, I'm somewhat strange - I'm passionate about source code control (now noted as SCC) and have tried a few new ones just to see if I like them. Process is important and while I don't believe in crazy ISO-9000 level of process (then most of your work is to maintain the process rather than produce value) but you need some or there is only chaos. Go check out "The Joel Test", I'll wait.

I don't necessarily believe that all of them are necessary or sufficient. But what is #1? That's right SCC. SCC is so important, many word processors (like word) embed version tracking into the software.

Why do people insist on using nothing or tarballs/zipfiles to ensure the safety of business/personally critical data? One place I worked used zip files but also required you comment out changed code with a reason plus add comments for the new code. This resulted in files where there were pages of code with ocassional live code (it was unreadable). SCC systems do this for you.

What is SCC?

In essence, a SCC tracks changes made to files and directories and allows users to (among other things):
  • Checkout (aka get) the current version or some version from the past of those files/directories.
  • Check-in (aka save) your current changes to the SCC to be saved for posterity.
  • Revert changes you don't like.
  • Find out who made changes and why.
  • Do differences on what exactly has changed either between past versions or with what you have done since the last check-in.
  • Manage multiple people working on the same files and directories.
  • Give the ability to mark and later retrieve files/directories related to some important event like a release.
There are several main paradigms for SCC:
  • Locking vs Merging - Some SCC tools require you to mark a file for editing such that it is locked and no other user can commit changes until you release the lock. Other SCC tools don't require locking but will require (or do it for you if simple) merging if there are conflicts. I have found the locking model interrupts my workflow because I may not know all the files I'll change ahead of time, stopping to lock a file gets in the way, and someone might lock the file I'll need and then need a file I have locked (classic deadlock problems). Merging might sometimes be a pain, but it is better than the alternative.
  • Client/Server vs Peer to Peer - Most SCC has a server that holds the "one true version" and all clients must submit to that server. A few systems use a peer-to-peer structure where the only "one true version" is decided by social convention not technology.
For more information check out:

SCC and the Individual Developer

Even if you work by yourself for work or fun you should use SCC. The few times I haven't, I often regretted it. The first reason is that this helps develop good habits. Secondly, this makes it so much easier to undo mistakes should they happen.

Imagine you are making some changes to a game you wrote. The changes, while simple, are invasive and touch numerous files over the course of a day and you were interrupted numerous times. Sadly you made an error that causes saved data to become corrupted but the error could have been introduced anywhere and you can't remember exactly what you changed. SCC allows you to quickly find out what files changed, what the changes were, and if necessary revert back to good code and start over. Without SCC, you might be debugging for a long time.

SCC Tool Recommendations

This is based on tools I've used for long periods of time for production code with the exception of Git (many tools are omitted):
  • Perforce - This is a commercial product I used long ago. It can use locking or merging. I don't use it now because it costs money, I'm cheap, and there are great open source alternatives.
  • Visual Source Safe (VSS) - This pile of steaming... rubbish is given away by Microsoft. It uses a locking model by default. The problems with VSS are that it often corrupts large codebases and Visual Studio integration (up too 2005 I believe, or beyond) puts little snippets in your project files to handle integration. If you are ever kidnapped to a tropical island by a criminal mastermind with a claw and a cat and are told you must use VSS or be given to a bunch of cannibals, choose the cannibals because it will be less painful. I have heard from some insiders that Microsoft doesn't use VSS. If the producer of software doesn't use their product (and they could), then I don't feel it is wise using it either.
  • Vault - A VSS commercial clone (plus bonuses) of VSS. While this tool never corrupted my code like VSS did on a regular basis, I dont' much like how Vault works, so I don't like using it.
  • CVS - An open source merging SCC used for years by many open source products.
  • Subversion - A newish SCC that is much like CVS but it offers atomic commits (everything goes or nothing - so you don't have partial commits), versioning directories, better brancing/merging, and other improvements. If you want to use a client/server SCC, I'd recommend this (despite what Linus says).
  • Git - This is the only distributed/peer-to-peer tool on my list. I've only been using it for a few weeks, but thus far I like it. Git was quick and easy to setup and does everything I expect in a SCC with the added bonus of being really fast (partially because there is no server to talk to) One of the selling points is better branching/merging but I have yet to do much of that.
Closing Comments

I'll end with a few recommended best practices:
  • Use source code control
  • Check-in as often as possible without breaking the build.
  • Keep your commits small.
  • Add a useful (but short) message to each commit on why you made the commit (not what you changed since the SCC handles that). This should include a bug number if available.
  • Tag all your releases in SCC
This brings my SCC rant to a close. I feel much better now.

Sunday, April 20, 2008

Using ANTLR to create an Excel Like Formula Parser in Flex

Introduction
One of my first Flex programming projects was to write an Excel-like expression parser. This parser was written using the “shunting yard” algorithm by Edsger Dijkstra to transform infix notation to a reverse-polish notation (postfix) stack which is easily processed. That code isn't publicly available but the algorithms are described in a paper I wrote here.

I decided to re-write the expression evaluator using ANTLR. ANTLR is a parser generator that takes BNF-like notation and generates code for a target language. The default target language is Java, but there are many other target languages including an ActionScript target in the upcoming 3.1 version.

Flex Formula Evaluator
The actual Flex application is available here with source available. This is an example of a formula that can be evaluatedl feel free to copy and paste into the evaluator below (variables are noted in "[variable_name]"):
(1+2)*sum(9-8,5,17.5,[numarray])/if(or([string]="hello",1>5),2,99)

How Does it Work?

The formula parser begins with the ANTLR grammar found in Formula.g and FormulaTree.g (in src com.arcanearcade.antlr). ANTLR has 3 types of grammar rules:
  • Lexer - Used to transform the character stream into a series of tokens. Lexer rule names are written in all capital letters. For example, the following code describes how to recognize variables which are any characters except [ or ] found between [ and ].
  • VARIABLE : '[' ~('[' | ']')+ ']';
  • Parser - Walks though the tokens to form sentences in the grammar. Parser rules begin with lower case letters. The following example shows how to recognize a percent token, which is a number token followed by the percent sign (both described in the parser grammar). The '^' in the grammar is a special token that shows what the head of the created tree grammar looks like. So "50%" is transformed into a tree with an s-expression notation of "(% 50)" and will be evaluated to the value "0.5" by the tree grammar.
  • percent: NUMBER PERCENT^;
  • Tree - This optional grammer taks the tree that can be created by parser grammar and with the help of native code snippets interprets the tree to produce output. While you can use code snippets directly in the parser, using a tree grammer allows you to reuse the lexer and parser for other languages and write a (usually simpler) tree parser for each target language. The following tree grammar shows how to evaluate addition where "6 + 7" was turned into "(+ 6 7)" by the parser and is evaluated to the number "13" by the ActionScript code between the {}
  • operation returns [Object value]
    : ^(ADD a=expression b=expression)
    { $value = Number($a.value) + Number($b.value); }
The ANTLR tools parse the grammar files to produce native code as shown in the diagram below:
Code in FlexFormula.mxml evaluateFormula() takes a string, feeds it into the lexer, takes the output of the lexer feeds it into the parser, and then finally feeds that into the tree to evaluate the result. FormulaTree#addFunction() adds new spreadsheet functions like "sum" and "if" and FormulaTree#lookupVariable sets the function callback to retrieve variables.

What Next?
The expression parser isn't as friendly as it could be (it is just a demo). To improve the formula engine to the point it could be used in a spreadsheet the FormulaLexer, FormulaParser, and FormulaTree in a class that would:
  • Add all the common function.
  • Setup binding to watch for changes to the formula string and only call the lexer and parser when the formula changes.
  • Setup a public and bindable variable for the result value.
  • Add binding for all variables in an expression so when they change the tree can be re-evaluated.
  • Improve error handling