AS3 HTML to Flash Conversion Library – htmlwrapper

Interesting library for html to flash front end. Basically this runs off the HTML in your page to draw the same in Flash. I am sure there are great pitfalls in this but when controlled this could be very key in a flash add-on to CMS or CMS content. Might be useful for many things.

Wrapper is a cross-browser compliant HTML/CSS rendering engine written in ActionScript that sits on top of your standards compliant HTML page. Wrapper eliminates cross-browser issues and makes integrating ActionScript and HTML/CSS projects possible without needing to compile.

Wrappers strives to answer the most common problems web designers face without forcing them to learn too many new things. Most web sites can be created in HTML or CSS, then when you need to extend Wrapper’s capabilities you can either use JSON to call functions within ActionScript or you can load compiled plug-ins. Wrapper also has built in methods within CSS to load custom fonts, display elements as any shape, and fill them with linear or radial gradient background colors. ActionScript’s event model is also implemented within Wrapper’s HTML. Wrapper’s best features are the ones that you get for free because of how it is set up. It’s like getting all the great features of the Flash Player without needing to deal with compiling and being able to create your content the same way any HTML page would be created. Wrapper is fully accessible to the search engines and integrates well with any back-end technology.

Wrapper is currently released as a fully functional open source beta for Flash Player 9. Wrapper is set up as a pre-compiled plug-in but can easily be integrated into any Flex or AIR applications or even as an ActionScript framework for creation of compiled projects.

Documentation can be found in the wiki and news about this project can be found at http://motionandcolor.com

Examples can be found in the downloads http://code.google.com/p/htmlwrapper/downloads/list

Source is for everything is in svn http://code.google.com/p/htmlwrapper/source

I checked it out and it looks pretty well done, most of the time HTML to Flash or vice versa has to be a semi-controlled environment in terms of the markup. This and FlashML which is only AS2 I am using a partially converted to AS3 are part of my rotation for HTML<–>Flash content challenges for research right now. Usually most CMS in Flash has content loaded into the flash and then an alternate (sometimes similar) representation, here this is trying to merge the two which has it’s challenges.

Try out a demo (view source)

EDIT: Title dyslexia


HOWTO: SharedObjects for Local Storage AS3

Using SharedObjects in Flash is very simple. Flash has SharedObjects that have been in the player since Flash6 when the introduction of Flash Communication Server which is now Flash Media Server which is releasing version 3 soon (also remote SharedObjects in Red5 is an open source RTMP media server that is based on Flash Media Server). So we can thank this release for SharedObjects, Camera objects, Audio, lots of the NetConnections, protocol enhancements and many other things. However to keep the tips simple we will just touch on the local usage and post a series of posts on these objects.

SharedObjects locally and remote have changed the way offline is thought about and are the backbone of many offline systems and prototypes. They have been influential in moving storage locally to remote in a lightweight AMF0 or AMF3 format.

SharedObject is in the flash.net namespace in AS3.

Here we show how to use the local version of a SharedObject to store data in the most simple form.

import flash.net.SharedObject;
var so:SharedObject = SharedObject.getLocal("userData");
so.data.username= "user1377";
so.data.pwdhash= "[hash] or pwd";
so.flush(); // writes changes to disk

You can see this is extremely simple to store data.Here we show how to use the local version of a SharedObject to retrieve data in the most simple form.

import flash.net.SharedObject;
var so:SharedObject = SharedObject.getLocal("userData");
var username:String = so.data.username;
var pwdhash:String = so.data.pwdhash;

That is it! In the most basic form SharedObjects are more simple than cookies and also are quite nice living outside the bounds of the cookies folder. If a user deletes all cookies it will not delete the SharedObjects. To delete SharedObjects you need to roght click on the Flash player, go to Settings and delete the objects there.You can store any type of data Flash supports from objects to numbers to strings in the SharedObject data.

import flash.net.SharedObject;
var so:SharedObject = SharedObject.getLocal("userData");
so.data.username= "user1377";
so.data.uid= new Number(1337);
var obj:Object = new Object();
obj.prop = "value";
so.data.userobj= obj;
so.flush(); // writes changes to disk

For large applications SharedObjects local are great because users can have their SharedObject space set to a high amount of space or unlmited for large offline type apps or more complex apps stored in a state object. It gets interesting when you pass this to the server in AMF or extremely compact AMF3 format to a remote stored object, via remoting, Shared Object events or any way you want to.We will be posting more on remote shared objects and some of the other tools such as Camera and Streams for AS3 over the coming weeks and deeper into the Sync Events for remote and local SOs.Sephiroth has a great Python tool to peer into the SOs on disk.

The first version of SharedObject Reader was written in python 2.2.
This new version is written in C# (C Sharp) as it’s now part of FlashDevelop editor.

Red5 also does this as well as many AMF kits.

Sync Events for SharedObject (as they change they launch a sync event)

Event object type: flash.events.SyncEvent
SyncEvent.type property = flash.events.SyncEvent.SYNC

Read more at adobe docs:

flash.net.SharedObject

Sample from AS3 docs showing usage

package {
    import flash.display.Sprite;
    import flash.events.MouseEvent;
    import flash.events.NetStatusEvent;
    import flash.net.SharedObject;
    import flash.net.SharedObjectFlushStatus;
    import flash.text.TextField;
    import flash.text.TextFieldAutoSize;
    import flash.text.TextFieldType;

    public class SharedObjectExample extends Sprite {

        private var mySo:SharedObject;

        public function SharedObjectExample() {
            buildUI();
            saveBtn.addEventListener(MouseEvent.CLICK, saveValue);
            clearBtn.addEventListener(MouseEvent.CLICK, clearValue);

            mySo = SharedObject.getLocal("application-name");
            output.appendText("SharedObject loaded...\n");
            output.appendText("loaded value: " + mySo.data.savedValue + "\n\n");
        }

         private function saveValue(event:MouseEvent):void {
            output.appendText("saving value...\n");
            mySo.data.savedValue = input.text;

            var flushStatus:String = null;
            try {
                flushStatus = mySo.flush(10000);
            } catch (error:Error) {
                output.appendText("Error...Could not write SharedObject to disk\n");
            }
            if (flushStatus != null) {
                switch (flushStatus) {
                    case SharedObjectFlushStatus.PENDING:
                        output.appendText("Requesting permission to save object...\n");
                        mySo.addEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
                        break;
                    case SharedObjectFlushStatus.FLUSHED:
                        output.appendText("Value flushed to disk.\n");
                        break;
                }
            }
            output.appendText("\n");
        }

        private function clearValue(event:MouseEvent):void {
            output.appendText("Cleared saved value...Reload SWF and the value should be \"undefined\".\n\n");
            delete mySo.data.savedValue;
        }

        private function onFlushStatus(event:NetStatusEvent):void {
            output.appendText("User closed permission dialog...\n");
            switch (event.info.code) {
                case "SharedObject.Flush.Success":
                    output.appendText("User granted permission -- value saved.\n");
                    break;
                case "SharedObject.Flush.Failed":
                    output.appendText("User denied permission -- value not saved.\n");
                    break;
            }
            output.appendText("\n");

            mySo.removeEventListener(NetStatusEvent.NET_STATUS, onFlushStatus);
        }

        // UI elements
        private var inputLbl:TextField;
        private var input:TextField;
        private var output:TextField;
        private var saveBtn:Sprite;
        private var clearBtn:Sprite;

        private function buildUI():void {
            // input label
            inputLbl = new TextField();
            addChild(inputLbl);
            inputLbl.x = 10;
            inputLbl.y = 10;
            inputLbl.text = "Value to save:";

            // input TextField
            input = new TextField();
            addChild(input);
            input.x = 80;
            input.y = 10;
            input.width = 100;
            input.height = 20;
            input.border = true;
            input.background = true;
            input.type = TextFieldType.INPUT;

            // output TextField
            output = new TextField();
            addChild(output);
            output.x = 10;
            output.y = 35;
            output.width = 250;
            output.height = 250;
            output.multiline = true;
            output.wordWrap = true;
            output.border = true;
            output.background = true;

            // Save button
            saveBtn = new Sprite();
            addChild(saveBtn);
            saveBtn.x = 190;
            saveBtn.y = 10;
            saveBtn.useHandCursor = true;
            saveBtn.graphics.lineStyle(1);
            saveBtn.graphics.beginFill(0xcccccc);
            saveBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5);
            var saveLbl:TextField = new TextField();
            saveBtn.addChild(saveLbl);
            saveLbl.text = "Save";
            saveLbl.selectable = false;

            // Clear button
            clearBtn = new Sprite();
            addChild(clearBtn);
            clearBtn.x = 230;
            clearBtn.y = 10;
            clearBtn.useHandCursor = true;
            clearBtn.graphics.lineStyle(1);
            clearBtn.graphics.beginFill(0xcccccc);
            clearBtn.graphics.drawRoundRect(0, 0, 30, 20, 5, 5);
            var clearLbl:TextField = new TextField();
            clearBtn.addChild(clearLbl);
            clearLbl.text = "Clear";
            clearLbl.selectable = false;
        }
    }
}

Flash App Photo Editor Picnik Integrated with Flickr

Picnik is an excellent application that makes believers out of RIA skeptics made with Flash/Flex.   Today Picnik is now integrated with Flickr bringing user friendly photoshop essentially to the masses

This is a pretty interesting market direction as more photo companies like photobucket and flickr add to the competition for photo editing. As flash based uploads, photo editors, word processors, presentation creators, conference systems, office apps, planning apps and many others all over the web does this mean the services model is really here and RIA is not just a fad?

The model of software is changing, again. The one competitive edge that web applications, and specifically RIA apps have over desktop is that many desktop apps are bloated, have legacy evolution that caused heavy, busy interfaces and absolutely no abstraction of the possible user level in many cases. Web applications are for a broad audience so these applications will see many benefits in making simplified versions of applications for lower skilled users, and then for advanced users more features.

The model is entirely different. They also have the ability to embed in sites like flickr, photobucket, social networks, office product offerings, small business servers, etc.  They could even compete on these sites.  The install base will not be millions of client computers but networks and clusters of users at online places and services.

This was a dream with ASP applications and software as a service.  The problem was before RIA some of the limits of the web were preventing web apps from overtaking and beating out the features of desktop apps. RIAs and the web, web services, user controlled  environments are changing the way software is used. is   We aren’t entirely there yet but RIAs are reviewing their schematics, late at night, and are slowly taking over the software world and changing the model.  Like a ninja is Picnik.

Regarding Picnik, I can’t say enough about the simplicity, clean design that they have pulled off here.  The website and application have an identical brand.  The application is extremely responsive and acts like html sites would when it comes to text and forms. The integration of services, webcam, all filters in flash, on and on.  They really have a great team and it seems like they are both a great product team but also have the right quality. The new market is extremely agile, the paradigm is shifting.

AS3 BulkLoader Useful Flash Asset Loading Kit by Arthur Debert

Found via Zeh, this great bulk loading kit for AS3 from Arthur Debert.

AS3 Loaders are very useful, but when you have large projects there is always a pause and focus on loading scenarios and architecture needed for your loading scenarios, sometimes this can literally eat days and entirely change performance with wrong moves. BulkLoader is a well written kit from Authur Debert that makes loading scenarios or using BulkLoader as a base to your loading situations a great pluggable piece of code that has many excellent features.

Some of the calls like BulkLoader.getLoader(“main-site”).getContent(“bg”), are also very similar to Silverlight’s downloader object that can be queued like this. All in all a kit that is very useful that I have already put to work and will help teams standardize on bulk loading for those killer flash apps.

Creating a BulkLoader instance:

// creates a BulkLoader instance with a name of "main-site", that can be used to retrieve items without having a reference to this instance

var loader : BulkLoader = new BulkLoader("main-site");

Add urls to load:

// simplest case:loader
.add("logo.png");

// use an "id" so the item can be retrieved later without a reference to the urlloader
.add("background.jpg", {id:"bg"});

// since the url by itself can't tell us what the filetype is, use the type property to let BulkLoader know what to do:loader
.add("/some-web-services?size=Large", {type:"image"});

// add an item that should be loaded first (higher priority):loader
.add("/data/config.xml", {priority:20});

// add a max trie number (defaults to 3)loader
.add("/unreliable-web-services.xml", {maxTries:6});

// you can also use a URLRequest object , this will load from a POST request

var postRequest : URLRequest = new URLRequest("/save-prefs.php");postRequest
.method = "POST";

var postData : URLVariables = new URLVariables(myPostDataObject );postRequest
.data = postData;loader
.add(postRequest, {"id":"settings"});

// of course, all options can be combined:loader
.add("the-sound-webservices?name=maintrack", {"id":"soundtrack", type:"sound", maxTries:1, priority:100});

Listening for events:

// attaching events to all items:

// this will fire once all items have been loadedloader
.addEventListener(BulkLoader.COMPLETE, onAllLoaded);

// this will fire on progress for any item

// the event , BulkProgress is a subclass of ProgressEvent (with extra information)loader
.addEventListener(BulkLoader.PROGRESS, onAllProgress);

// this will fire if any item fails to load:

// the event is BulkErrorEvent and holds an array (errors) with all failed LoadingItem instancesloader
.addEventListener(BulkLoader.ERROR, onAllError);

// you can also listen to events in individual items               

// this will fire as soon as the item registred with the id of "bg" is done loading (even if there are other items to load)loader
.get("bg").addEventListener(Event.COMPLETE,onBackgroundLoaded)

// this will only trigged if the config.xml loading fails:loader
.get("data/config.xml").addEventListener(BulkLoader.ERROR, onXMLFailed)

Starting the loading operation:

BulkLoader will only begin loading once you call the start method:

loader.start();

Retrieving content:

You can retrieve an untyped object and cast it your self:

var theBgBitmap : Bitmap = loader.getContent("bg") as Bitmap;

// you don't need to keep a reference to the loader intance, you can get it by name:

var theBgBitmap : Bitmap = BulkLoader.getLoader("main-site").getContent("bg") as Bitmap;

// you can also use the conviniece methods to get a typed object:

var theBgBitmap : Bitmap = loader.getBitmap("bg");

// grab a BitmapData directly:

var theBgBitmap : Bitmap = loader.getBitmapData("bg");

Other convenience functions: getXML, getText, getNetStream, getSound, getMovieClip, getNetStreamMetaData.

You can retrieve an item using it’s id, it’s url as a String or as the URLRequest object (if the item was created with an URLRequest).

Arthur also has experience on Tweener so making simplified calls and minimalist code to make a library successful is very clear in the notes/goals on the project and the resulting code:

BulkLoader is a minimal library written in Actionscript 3 (AS3) that aims to make loading and managing complex loading requirements easier and faster. BulkLoader takes a more dynamic, less architecture heavy aproach. Few imports and making heavy use of AS3′s dynamic capabilities, BulkLoader has a one-liner feel that doesn’t get your way.

BulkLoader tries to hide the complexity of loading many data types in AS3, providing a unified interface for loading, accessing and events notification for different types of content.

This library is licensed under an open source MIT license.

Features:

  • Connection pooling.
  • Unified interface for different loading types.
  • Unified progress notification.
  • Events for individual items and as groups.
  • Priority
  • Stop and resuming individually as well as in bulk.
  • Cache managing.
  • Statistics about loading (latency, speed, average speed).
  • Multiple kinds on progress indication: ratio (items loaded / items to load), bytes , and weighted percentage.
  • Multiple number of retries.
  • Configurable logging.

Design goals:

  • Minimal imports.
  • Few method to learn.
  • Dynamic nature: items can be added by specifying a url as a String or a URLRequest .
  • Items can be assigned an identifier key to be used on retrieval.
  • Only one class to learn / use.

BulkLoader tries to gracefully handle progress notification in these use cases:

  • Few connections to open: bytes total can be used instantly.
  • Many connections opened: progress by ratio
  • Many connections opened for data of widely varying sizes: progress by weight.

Check out and download AS3 BulkLoader!

This is quite a contribution to the flash community and is a perfect candidate for the base of your loading assets projects and scenarios. Thanks Arthur!

Sandy3D and Red5 Server Attack! – Sandy 3.0 Final Released for AS2 and AS3

Sandy 3.0 was released today. To go along with that a RedSandy (Red5 and sandy demo) has also been released. Sandy is the original 3d flash engine that was around before Papervision3D and Away3D and all the others. Sandy3d is an excellent library and it has many features that others do not have well particularly in the easier control of objects and importing all types of files such as ASE, WRL and 3ds in addition to COLLADA which other 3d engines like PV3d and Away3d support although it has been slower in the past 3.0 may change that.

Sandy 3D engine main features are :

  • Flash player 7 to 9 compatibility.

  • Both MTASC and Macromedia compilers compliant for AS2 and Flash CS3 and FlexBuilder for AS3 versions.

  • Several 3D primitives, allowing fast and parameterized object creation without any 3D modelisation knowledge.

  • Advanced and easy object management allowing some fantastic possibilities during your creations (scaling, rotation, translation, tween, etc.)

  • Advanced camera management ( rotation, motion on linear or bezier-curve path, movements, etc.)

  • Complex object loading thanks to the .ASE and .WRL files parser , but also Collada and 3DS files for AS3, (files generated by several 3D object modeling packages such as 3D Studio Max or Blender)

  • Material system to easily change your objects appearance. Several material are available allowing to create transparent faces, bitmap texture and video texture as webcam video stream.

  • Managment of Flash filters bringing some very nice visual effects

Red5 is the best multi-user media server out there right now and it is built with Java.

The cool and probably most interesting part is Sandy combined with Red5 to create multi-user environments in 3d for flash. There have been experiments with this and many attempts at this and is being done but an open source kit that does this is very helpful and these are two great flash toolkits in Sandy and Red5.

Get your game on!

Getting started video with Sandy 3.0 with a wise robot

Good Usable RIA Applications in Flash and Silverlight

Flash and Silverlight allow developers to make amazing tools, they allow creative expression and they also are usually a bad user experience many times.

Lots of that is changing as more applications are made and frameworks like Flex and Silverlight progress. Much of the needed performance is now available for Flash/Flex in AS3 and the AVM2 virtual machine that runs it, making full applications much faster for all actions that might have been a drag in AS2 and vector based application’s of the past. Some great tools were made with this still that were usable like gModeler a flash based UML modeling tool but the performance boost will make these applications even more usable for mainstream.

Some great examples of user friendly apps where the flash or the silverlight element doesn’t blind the developer from usability. These applications might really have a market for general users of applications from advanced depending on feature set as long as they are usable.

buzzword (Flash/Flex/AS3)

Is a word processor that is really well done. This is made with Flex and everything from validation to the toolset is very usable and clean. I use Google Docs and haven’t looked back for about a year but this application is a nice change to web editors for documents at the current state. It included all the usual basic functionality and great new zoom, revision history and sharing tools that web office tools like word processors has come to expect. Be sure to try this one.

scrapblog (Flash/Flex/AS3)
scapblog is a bloggy/presentation that is a great template editor and the tools are broad and expected from users including great integration with the web for photos and video at major sites such as photobucket, flickr, etc.

Google SearchMash (Flex/Flash/AS3)

This is a Flex 2 (actionscript 3) application that is very fast and usable in vector.

Sample Textured 3d Vista demo(Silverlight 1.0)

This demo showcases the speed of Silverlight and a usable OS like interface that performs well. It showcases Silverlight but also has great usability in expected user actions and results.

tafiti (Silverlight 1.0 demo)

Tafiti is a search tool that uses SIlverlight and live search to represent search results in a rich way. They did a pretty good job with usability and especially considering the Silverlight 1.0 lack of good input controls. Little bit laggy.

The point is solution developers should use technology but most importantly make it functional and usable to what users expect. RIAs will succeed very well as long as you can select text, hit back buttons, deep linking, use menu systems, integrate services, have all the features of apps not in vector engines like Flash or Silverlight and to make it mainstream friendly they need to have a low bar of entry and just work. RIAs have an advantage right now as office apps move to the web and photo apps as well, many of these apps above would appeal to general computer users in addition to advanced users.

AS3 Amazing Isometric 3D Alternativa Game Engine Demo

Alternativa Game is a leap forward in isometric 3d engines for flash. A gigantic leap…, would you expect this kind of quality of software out of anyone but the Russian Alternativa Game group? Check it out NOW.

The demo runs suprisingly smooth. I had to kick down the quality just a bit to get started but once I did that it was very smooth, full 360 degree turning, texturing levels, render quality, day/night, and many more features. You have to try the day and night, check the lighting coming out of the window…

More from Anton Volkov:

This is technological demoversion of an Alternativa3D Flash engine, which was made within Alternativa MMORPG development. This engine uses Flash player version 9 as a platform, and, as far as we know, works in all full-flash-supporting browsers. Alternativa3D is optimized with upcoming game features in mind, and utilizes some non-trivial solutions to show game graphics quickly.

Main features:

  • Three-dimensional geometry and 3D-sprites. Buildings and landscape are made in a fair 3D, objects with complex geometry — using sprites, including multi-phase ones.
  • Lighting system, including ambient, directional and omni lights. Changing daytime, diffuse and sunlight, automatical “in-corners” shading, dynamic shadows, including sprite shadows.
  • Texture and light quality settings (it is really important without 3D hardware acceleration in Flash).
  • Low processor load (excluding moments of lighting change and camera rotation, which happen not too often and is not critical for the game).

This is on par with Paul Spitzer’s amazing FPS flash engine.

You can follow this amazing development over at the Alternativa Game blog. I suspect quite a bit of interest now that they have thrown it down. Apparently when Anton and the guys of Alternativa throws down, they bring it!

This is only possible in AS3, this would be nothing more than a prototype test in AS2 but in AS3 it is fast enough and much much more capable of building stuff like this.

Deep Linking in Flash – SWFObject and SWFAddress

Flash is great, but accessibility can sometimes be a problem if it is not paid attention to. Direct linking, deep linking, back button support, these are very important to wire up in your applications. I am seeing many new RIAs, apps, sites, interactives still not do this and it is quite annoying.

The great thing about the web is that is gave users the ability to control the presentation and the context, from outside the presentation. By allowing users to use the back button and change urls in the address bar this was empowering. Empower your users and ad campaigns to get to different places of your application easily with deep linking, it is required for usability.

But this is hard right? Not really with great tools. What are you waiting for, SWFObject and SWFAddress make up THE platform right now for deep linking, embedding and back button support. These kits have been exhaustively tested and are very compact scripts to help you embed and then provide deep-linking, back button support and direct linking instantaneously almost.

Download SWFObject

Download SWFAddress

Both of these kits are well tested and provide instant small simple components of which to build complex systems on top of. SWFAddress builds on SWFObject tested embedding script and provides the tools you need to get deep linking running in your application in no time.

Note of caution, design implications (architecture design)

When you drive off the URL such as with direct and deep linking in Flash it does change your order of how you handle operations when you have to take into account the URL state. The first thing you have to do is when you receive an onChange event from SWFAddress that the URL has changed, you need to parse it and take action. However if you plan to deep link and provide usability throughout your flash site or app (even in the forms or multistep processes driven by URL) then you need to plan for this event and work this into your architecture for the url handling within the flash framework for your site.

A scenario might be:

  1. User using your flash app
  2. User clicks link or new section of your flash application
  3. INSTEAD of just animating the state in the flash application, you have to just update the section or URL (location.hash in javascript that provides the # name linking allowing the browser to stay put, or in this case SWFAddress.setValue((“/sectionname/page1″)),
  4. THEN the flash app or site is REACTIVE to the URL, reads in “sectionname/page1″ parses it and then animates to sectionname/page1.
  5. Or detect if the change came from the app or the URL directly and handle that differently in the onChange event with a subsystem.

Rather than just animating the app state or changing it, or showing that next photo on the button event, your button event would change the URL, then the flash monitoring the URL would push the onChange event. After that either animate in the next section or take appropriate action per the user requested action.

It isn’t like this for all areas or states of your application but you have to decide what is directly linkable, and when you want a state directly linkable then you have to wire it this way. Obvious choices are navigation items in your site, but they might also be specific cases like a multi-page form wizard that you want to link to step 3 directly, or a movieclip that someone can pass #3m2s to advance the movie by the url. There are many cases where you might want to provide deep linking into your flash application.

I know it sounds complicated? but it really isn’t, just a reversed way of thinking which we will highlight in the future with a tutorial and a fluid flash template. The SWFAddress site has great samples and examples, SWFAddress sets up the onChange handling in these samples and examples of how to do it in AS1, AS2 and AS3 so pick it up.

Download SWFObject

Download SWFAddress

Enable Deep Linking in Flash in 8 lines of code to start with SWFAddress:

From SWFAddress Documentation

1) Insert the SWFAddress script in your page directly after the SWFObject file.

<script type="text/javascript" src="swfobject/swfobject.js"></script>
<script type="text/javascript" src="swfaddress/swfaddress.js"></script>

2) Include or import one of the provided ActionScript classes. SWFAddress comes with versions for AS1, AS2 and AS3.3) Write your own navigation logic that will be executed when the address is changed.

SWFAddress.onChange = function()
{
    // Your code goes here.
}

4) Call the SWFAddress setter method from every button or action that requires deep linking.

this.onRelease = function() {
    SWFAddress.setValue('/portfolio/');
}

Check out the Asual blog (makers of SWFAddress) for more on good practices and bad practices with deep linking and more tips.Tips like:

Bad Practice: Address values naming using camelCase or other forms of custom convention

SWFAddress samples clearly define the best naming convention for deep links. Web addresses are case insensitive and the standard is lower case. For readability and Google SEO compatibility reasons the convention ‘my-deep-link’ is more appropriate than ‘myDeepLink’ or ‘My_deep_link’. The format http://domain.com/#/my-deep-link/?param=value is the only one fully compatible with the SWFAddress SEO rewriting.

Silverlight Deep Linking

This is also very simple in Silverlight to deep-link using javacript tools kits for Silverlight 1.0 which is javascript only, on location.hash change using a timer you could call an application method that might change the state or call certain transitions or move Canvases around, hide/show them, load content in, etc. Again, something you want to think about early on.

Other notes

SWFObject 2.0 beta5 is out and after 5 betas hopefully is nearing release

Pick up the code here for SWFObject 2.0

SWFObject 2 (script based) is the name again after a small switch and merge with UFO (standards based) to SWFFix but as Geoff Sterns pointed out, this seems to assume that something is broken.

SWFObject 2.0 is the new name again and let’s hope many more great tools are built on SWFObject 2.0 like SWFAddress which handles direct linking and back button support (using location.hash as most AJAX/RIA apps do to get deep linking and back button support).

JSTweener: Javascript Tweener for Animation

Zeh Fernando’s AS2 and AS3 Flash Animation Kit Tweener has inspired a JSTweener port to javascript, why thanks Yuichi Tateno (secondlife).

This actually could be used quite easily with Silverlight and an AgTweener could be very easily created from this. The Tweener like syntax with an object and adding tweens of available properties as an object or array is very simple and could make animation systems much more standard if everything used this not to mention easier for developers to animate in any presentation layer. The syntax makes for the best of the Animation Packages currently available for AS3. If this could be used in other kits it would make animation pretty standard and simple when changing platforms.

JQuery is very lightweight and has a similar syntax on their animate() call. There are many animation javascript kits such as mootools, jquery, dojokit and prototype and others that have similar functionality but it is all handled differently.

JSTweener

JSTweener.addTween(element.style, {
time: 3,
transition: 'linear',
onComplete: function() {},
width: 200,
height: 200,
left: 500,
top: 300
});

JSTweener Source

JSTweenerRepo

Samples:

Found via Zeh

Helpful Flash Debugging Tools

When debugging flash sometimes you need to either debug in browser or check a past version of the Flash player or the new beta player to see how things are looking. Here is a list of some tools beyond the included debugging IDEs FlashCS3 and Flex2 that are helpful to making your flash projects more bulletproof.

  • Firefox Flash Version Switcher from Sephiroth


    Find out if your code is just messed in the latest version or an older version of the flash player. This has links to the older versions of the Flash player from Adobe that you are interesting in testing.

  • Xray Flash/Flex Debugging Kit by John Grden XRay is a flash/flex debugger

    for real-time debugging and spying on your code. It is 16KB for the connector that you add to your files but it is debugging in style. If you have any issues with a live app or to help during testing Xray is great. It also includes a nifty admin site that allows you to access objects and spy on your code at any time.

    Xray (The AdminTool) is a “snapshot viewer” of the current state of your Flash application without impacting the performance or the file size of your application. Xray’s true nature is to look into the very guts of the Flash application and disolve the 2d myth you see on screen to a 3D tangible entity you can truly crawl through.Xray is brought to you by Blitz Labs.

  • AS3 Debugging with Firebug and Actionscript from marcosweskampWhen using Firebug (a web developers Swiss army knife for browser debugging) you can also use actionscript to write to the firebug console with this class from marcosweskamp The code to Console.as for firebug is here.

  • Output Panel from Senocular
    Last but not least, try out this class that creates or mimic the output panel in flash
    . Another great quick class from senocular. You have to change your trace command to Output.trace but I recommend that you abstract logging anyways to a method that can determine to trace, Output.trace(str:*) or any further logging you might want to do for debug or application logs (it also makes it easy to switch out logging options). This Output panel can help when you don’t’ have the debugger available, or for use in a live debug mode of your application. This class can be implemented in minutes.

    package com.senocular.utils {
    	import flash.display.Shape;
    	import flash.display.Sprite;
    	import flash.display.Stage;
    	import flash.display.GradientType;
    	import flash.events.Event;
    	import flash.events.MouseEvent;
    	import flash.geom.Matrix;
    	import flash.text.TextField;
    	import flash.text.TextFieldType;
    	import flash.text.TextFormat;
    	import flash.text.TextFormatAlign;
    	import flash.text.TextFieldAutoSize;
    
    	/**
    	 * Creates a pseudo Output panel in a publish
    	 * swf for displaying trace statements.
    	 * For the output panel to capture trace
    	 * statements, you must use Output.trace()
    	 * and add an instance to the stage:
    	 * stage.addChild(new Output());
    	 *
    	 * Note: You may want to place Output in an
    	 * unnamed package to make it easier to
    	 * trace within your classes without having
    	 * to import com.senocular.utils.Output.
    	 */
    	public class Output extends Sprite {
    		private var output_txt:TextField;
    		private var titleBar:Sprite;
    		private static var instance:Output;
    		private static var autoExpand:Boolean = true;
    		private static var maxLength:int = 1000;
    
    		public function Output(outputHeight:uint = 150){
    			if (instance && instance.parent){
    				instance.parent.removeChild(this);
    			}
    
    			instance = this;
    			addChild(newOutputField(outputHeight));
    			addChild(newTitleBar());
    
    			addEventListener(Event.ADDED, added);
    			addEventListener(Event.REMOVED, removed);
    		}
    
    		// public methods
    		public static function trace(str:*):void {
    			if (!instance) return;
    			instance.output_txt.appendText(str+“n”);
    			if (instance.output_txt.length > maxLength) {
    				instance.output_txt.text = instance.output_txt.text.slice(-maxLength);
    			}
    			instance.output_txt.scrollV = instance.output_txt.maxScrollV;
    			if (autoExpand && !instance.output_txt.visible) instance.toggleCollapse();
    		}
    		public static function clear():void {
    			if (!instance) return;
    			instance.output_txt.text = “”;
    		}
    
    		private function newOutputField(outputHeight:uint):TextField {
    			output_txt = new TextField();
    			output_txt.type = TextFieldType.INPUT;
    			output_txt.border = true;
    			output_txt.borderColor = 0;
    			output_txt.background = true;
    			output_txt.backgroundColor = 0xFFFFFF;
    			output_txt.height = outputHeight;
    			var format:TextFormat = output_txt.getTextFormat();
    			format.font = “_typewriter”;
    			output_txt.setTextFormat(format);
    			output_txt.defaultTextFormat = format;
    			return output_txt;
    		}
    		private function newTitleBar():Sprite {
    			var barGraphics:Shape = new Shape();
    			barGraphics.name = “bar”;
    			var colors:Array = new Array(0xE0E0F0, 0xB0C0D0, 0xE0E0F0);
    			var alphas:Array = new Array(1, 1, 1);
    			var ratios:Array = new Array(0, 50, 255);
    			var gradientMatrix:Matrix = new Matrix();
    			gradientMatrix.createGradientBox(18, 18, Math.PI/2, 0, 0);
    			barGraphics.graphics.lineStyle(0);
    			barGraphics.graphics.beginGradientFill(GradientType.LINEAR, colors, alphas, ratios, gradientMatrix);
    			barGraphics.graphics.drawRect(0, 0, 18, 18);
    
    			var barLabel:TextField = new TextField();
    			barLabel.autoSize = TextFieldAutoSize.LEFT;
    			barLabel.selectable = false;
    			barLabel.text = “Output”;
    			var format:TextFormat = barLabel.getTextFormat();
    			format.font = “_sans”;
    			barLabel.setTextFormat(format);
    
    			titleBar = new Sprite();
    			titleBar.addChild(barGraphics);
    			titleBar.addChild(barLabel);
    			return titleBar;
    		}
    
    		// Event handlers
    		private function added(evt:Event):void {
    			stage.addEventListener(Event.RESIZE, fitToStage);
    			titleBar.addEventListener(MouseEvent.CLICK, toggleCollapse);
    			fitToStage();
    			toggleCollapse();
    		}
    		private function removed(evt:Event):void {
    			stage.removeEventListener(Event.RESIZE, fitToStage);
    			titleBar.removeEventListener(MouseEvent.CLICK, toggleCollapse);
    		}
    		private function toggleCollapse(evt:Event = null):void {
    			if (!instance) return;
    			output_txt.visible = !output_txt.visible;
    			fitToStage(evt);
    		}
    		private function fitToStage(evt:Event = null):void {
    			if (!stage) return;
    			output_txt.width = stage.stageWidth;
    			output_txt.y = stage.stageHeight - output_txt.height;
    			titleBar.y = (output_txt.visible) ? output_txt.y - titleBar.height : stage.stageHeight - titleBar.height;
    			titleBar.getChildByName(“bar”).width = stage.stageWidth;
    		}
    	}
    }
    

Other debug and logging tools that may help are listed here from OSflash.

  • Alcon – An external output console for Actionscript debugging

     

  • LuminicBox.Log – A logging API and output console for ActionScript

 

  • DebugIt – Displays traced data in a seperate SWF so you can debug outside of Flash, while running your application in its shell/production environment.
  • Print_r Debugger – Brings PHP‘s “print_r” to Flash, invaluable once you start to use it. Free, Complete Source Available
  • Sock4Log – JAVA application which displays traced data from SWF and other (PHP,JS…). Could be a command line or windowed application.

HAXE Flash9 Assembler Library and Compiling SWF


Haxe
is a very interesting project that is a scripting language that can create SWF for Flash.

Haxe has now added Flash9 Assembler library called hxASM and released version 1.1.4 that includes performance updates for Flash9 SWFs compiled using Haxe scripting.

I have to compile SWFs dynamically right now in a service and this is a very attractive solution with the new version and the performance improvements. Previously there was some slow down and only static content really worked well but if this is equal or a 30% improvement that is excellent.

Flex 2 can also compile at the command line you can compile flash9 swf with or without the flex2 libraries, when using mxml the flex libraries are included which add 100k or so minimum. It is not required to compile with flex 2 libraries though.

Flex 2 command compiler options

Haxe command compiler tutorial

Using Haxe with Flex 2

Using Haxe hxASM

Full Haxe API (includes all flash libraries)

No Flash Support on iPhone, No Java Either

There is no Flash or Java support on the iPhone. This had leaked earlier but now that it is out this is verified and it pretty much sucks.

This limits the type of gaming market the iphone could become, or the type of shiny chrome apps that could be built with Flash. I guess games can be built with HTML5 and javascript (um thanks Jobs).

I was at least hoping for FLV support which would open up many clip sites for mobile, but then again this would compete with iTunes and QuickTime.

Current knowns about the iPhone dev platform:

  • there’s no Flash or Java support
  • there is PDF support
  • Quicktime is used for encoding and displaying video and audio
  • said video is encoded via H.264
  • with Safari on the iPhone, links can be embedded in web pages to allow phone calls from a click; this would be insanely useful for corporate directories and such
  • web pages are limited to 10 MB (!), Javascripts can only run for five seconds (maybe no games at all :( )
  • the iPhone’s browser user agent: Mozilla/5.0 (iPhone; U; CPU like Mac OS X; en) AppleWebKit/420+ (KHTML, like Gecko) Version/3.0 Mobile/1A538a Safari/419.3

Also more info from here:

  • HTML5
  • 10MB max html size for web page
  • Javascript limited to 5 seconds run time
  • Javascript allocations limited to 10MB
  • 8 documents maximum loaded on the iPhone due to page view limitations
  • Quicktime used for audio and video
  • stylesheet device width:480px
  • there are no scroll bars or resize knobs. the iphone will automatically expand the content
  • new telephone links allows you to integrate phone calls directly from your webpage. remember this is only on safari.
  • built in google maps client for integrated mapping from your website
  • iPhone screen size 480×320
  • encode movie size 480×360
  • Links to movies on a web page will take users directly to video full screen playback

They are really controlling the experience early on, something I was hoping they wouldn’t do. Controlled markets is the current problem with mobile platforms in the US. I am sure better specs and flash might pop up in later versions of the iPhone in Apple fashion of increasing the hype on each version. Advancements such as 3G, more than 8GB storage, flash maybe, just not sure about this one due to the competition of Quicktime and iTunes. This severely limits the RIA web on the iPhone, at least this version of it.

UPDATE: Jesse Warden has links to using Flash content inside of Quicktime. This coud be a gaming option after all. It still limits the web browsing but in terms of interactives and games this could be good.

Flash on the iPhone via Quicktime: Part Deux

Apparently the “enabling” of Flash is as simple as clicking a button, correcting my original coverage.

Check out I2Fly’s coverage of iGiki.com’s iPhone Flash Games. Also, some of Gary’s ported Flash games worked.

Be sure to check out this out regarding a mobile web with no Flash.

HOWTO: Using the ContextMenu in AS3 with FullScreen Mode As a Sample

Right clicking and other mouse support in flash is not really a shining star but in AS2/AS3 you *can* stuff the context menu with items. You can clear out all but Settings and About from the menu and stuff in other items that may pertain to a selected movieclip or the entire app you are building. This can be good when adding multiple functions into applications and for extra functions that you want to make available from a quick location such as full screen, selecting an item etc.

To enable a context menu for full screen capabilities take this example:

1) Make your document class of your AS3 Flash CS3 file to the class below.

package
{
import flash.display.*;
import flash.errors.*;
import flash.events.*;
import flash.filters.*;
import flash.geom.*;
import flash.net.*;
import flash.media.*;
import flash.ui.*;
import flash.utils.*;
import flash.xml.*;
public class FullScreenTest extends MovieClip
{
public function FullScreenTest()
{
// create the context menu, remove the built-in items,
// and add our custom items
var fullscreenCM:ContextMenu = new ContextMenu();
fullscreenCM.addEventListener(ContextMenuEvent.MENU_SELECT, onContextMenuHandler);
fullscreenCM.hideBuiltInItems();
var fs:ContextMenuItem = new ContextMenuItem("Show Full Screen" );
fs.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onShowFullScreen);
fullscreenCM.customItems.push( fs );
var xfs:ContextMenuItem = new ContextMenuItem("Exit Full Screen");
xfs.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, onShowNormalScreen);
fullscreenCM.customItems.push( xfs );

// THIS ASSUMES YOU HAVE A MOVIECLIP IN THE LIBRARY
// THAT IS SET TO A CLASS NAMED 'mc' that inherits from MovieClip
var m:MovieClip = new mc();
m.contextMenu = fullscreenCM;
addChild(m);
}
// functions to enter and leave full screen mode
function onShowFullScreen(event:ContextMenuEvent):void
{
stage.displayState = StageDisplayState.FULL_SCREEN;
}
function onShowNormalScreen(event:ContextMenuEvent):void
{
stage.displayState = StageDisplayState.NORMAL;
}
// function to enable and disable the context menu items,
// based on what mode we are in.
function onContextMenuHandler(event:ContextMenuEvent):void
{
if (stage.displayState == StageDisplayState.NORMAL)
{
event.target.customItems[0].enabled = true; // show full screen button
event.target.customItems[1].enabled = false; // hide normal screen button
}
else
{
event.target.customItems[0].enabled = false; // hide full screen button
event.target.customItems[1].enabled = true; // shoe normal screen button
}
}
}
}

2) Now Export to HTML and be sure to change the exported parameters in the HTML file to allowFullScreen = true (for the fullscreen effect) and menu = true (for the ability to add in context menu items) to whatever library you use for embedding flash:

   'menu', 'true',
   'allowFullScreen', 'true'

OR if using HTML parameters

<param name="allowFullScreen" value="true" />
<param name="menu" value="true" />

You can view a sample here. (right click on the movie clip and ‘show full screen’, then ‘hide full screen’)

You can download a sample FlashCS3/AS3 version here.

If you want more information on fullscreen check here and here (downloadable sample and component).

SWF to XAML Converter SWF2XAML (Flash to WPF/Silverlight)

Photo Sharing and Video Hosting at PhotobucketMichael Swanson has created a SWF2XAML converter that you should check out.  It has quite a few features and fixes that would seem like conversion from SWF to XAML might not be worth the time.  This might change that.  I think that it is important to stay up on all vector technologies as a RIA solution provider and we do not treat platforms like religions rather tools to use at our disposal.

The conversion at least for the vector art looks pretty on target.

Photo Sharing and Video Hosting at Photobucket

Features

The following table contains a list of features that are supported by the current version of the SWF2XAML tool or are planned for a future release. Where there are issues, I’ve tried to address them in the Comments column. If you’d like to see some visual illustrations, take a look at the Eye Candy.

Support Feature Comments
Yes  Frame by Frame Advance Use the horizontal scroll bar at the bottom of the window to navigate frames in the SWF file. Because frames in a SWF file must be processed sequentially, later frames will need to calculate intermediate frames, so jumping forward may take some time.

* The current version of the SWF2XAML tool does not cache prior frames (and that feature in Edit/Preferences is permanently disabled). So, when navigating backwards, the file will be re-calculated from the beginning. Depending on the file complexity, this may take some time.
Yes Explore Project Folder Choose File/Explore Project Folder to view the folder that contains any exported assets (like XAML files and bitmap images).
Yes XAML Export Choose File/Export… to export the current frame to a XAML file.
Yes Save Frame as Bitmap To save the current frame as a bitmap image (.PNG), choose File/Save Bitmap. The image will be named frame####.png where #### is replaced by the current frame number. The file will be saved to the subfolder identified in the application preferences.
Yes Launch XAML File Choose File/Launch XAML to automatically export the current frame to a XAML file and launch it in your default browser (normally Internet Explorer). 
Yes Launch Original SWF File Choose File/Launch Original to launch the current SWF file. If you have the Flash Player installed, this will open the player and begin the animation.
Yes Copy XAML to Clipboard Choose Edit/Copy XAML to copy the XAML for the current frame to the system clipboard.
Yes Copy ResourceDictionary Choose Edit/Copy ResourceDictionary to copy a XAML ResourceDictionary element that represents the shapes that have been defined up to the current frame. The XAML is copied to the system clipboard. Note that any shapes that are defined after the current frame will not be included (so, to include everything, first navigate to the last frame of the SWF file).
Yes Go To Specified Frame Choose Edit/Go To… and enter a frame number to jump to that frame. Because Flash files must be processed sequentially, all interim frames will also need to be calculated, so this may take some time.
Yes Preferences Choose Edit/Preferences… to configure various aspects of the tool:

  • The Display tab contains settings that determine the opacity of the Onion Skin mode and the stroke color and fill opacity for Wireframe Mode.
  • The XAML tab contains settings to export to WPF/E-compliant XAML and to control its formatting.
  • The Files tab controls where the various file types are saved on your system. By default, each SWF file will have its own subfolder created.
  • The Advanced tab contains settings that control how the tool caches various assets. Although caching of assets can improve performance, there may be a significant memory cost involved.
Yes Stage Clipping Choose View/Clip Stage to toggle clipping of the frame on and off. Often times, frames in a Flash file contain elements that can’t be seen with clipping turned on.
Yes File Information Choose View/File Information to enable the File Information pane. This pane displays information about the SWF file, including: file name, file signature, version, file length, frame width, frame height, frame rate (in fps), and the total frame count.
Yes Display List Choose View/Display List to enable the Display List pane. Think of the Display List as a stack of layers that make-up the current scene. You can use the checkboxes to selectively hide/unhide elements until the frame content looks the way you’d like. Note that not all checkboxes will change the visual display (only Shapes, MorphShapes, Sprites, Buttons, and Text).
Yes Advance Sprite Frames Many Flash files contains movie clips (or Sprites) that are sub-elements that have their own animation frames. Although these animations will automatically progress with each frame in the main scene, choosing View/Advance Sprites will manually advance each sprite in the scene by a single frame.

** If you run across a single frame Flash file and it doesn’t appear to animate properly, it may be because you need to manually advance the sprites in the scene.
Yes Wireframe Mode Choose View/Wireframe Mode to display the outlines of the elements in each frame. The wireframe stroke color and fill opacity can be configured under Edit/Preferences. Note that XAML exported or copied to the clipboard in this mode will represent the wireframe version of the frame (i.e. what you see).
Yes Onion Skin Mode Choose View/Onion Skin Mode to toggle opacity of the entire tool window. When Onion Skin Mode is enabled, the tool window becomes semi-transparent so that it can be moved over the top of a comparison window (like the Flash Player). This is useful to visually compare the converted geometry. The opacity of the window can be configured under Edit/Preferences.
Yes Tag Statistics Choose View/Tag Statistics to view a table of the Flash tags that have been encountered up until the current frame in the current file. To get statistics for the entire SWF file, choose Edit/Go To… to jump to the last frame of the file, then view the tag statistics.
Yes View Original Size Choose View/Original Size to size the frame to the height and width that is specified in the Flash file. When using Onion Skin Mode, this makes it easier to do a visual comparison with the Flash Player.
Yes Shape Morphs Shapes that were authored to morph over a specific number of frames are supported in the conversion. This includes geometry, fills, strokes, gradients, matrix transformations, etc.
Yes Clipping Layers Layers in the Display List that are set to clip lower layers are supported. Although these layers don’t have any visual strokes or fills, toggling these layers in the Display List pane will affect the display.
Yes Bitmaps All JPG, indexed color, and full color bitmap types are supported. Note that indexed color modes are simply converted to 32-bit RGBA PNG files (as are JPG files with an alpha layer, unique to Flash files).
Yes Color Transformations Simple color transformations (multiply and add) are supported per-layer in the Display List.
Yes/No Shape Fill Types  All fill types are supported to varying degrees:

  • Solid fills are fully supported
  • Both radial and linear gradient fills are supported. However, the new radial gradient settings in later Flash versions are not supported.
  • Bitmap fills are supported, but non-repeating clipped fills currently have some issues.
Yes/No  Buttons Only the button “up” state is currently converted and displayed. Also, there is no interactivity. 
No Frame Blend Modes No current support for various frame blend modes that were introduced in later versions of Flash.
No Dynamic Text Although static glyph text is supported, there is currently no support for text that uses locally-installed fonts.
No ActionScript All ActionScript code is currently ignored. As such, no interactivity is converted. 
No Sound No sounds are currently exported or played; they are simply skipped.
No Video All video is skipped. 

Installation

To get the SWF2XAML tool up-and-running on your system, follow these steps:

  • Make sure that you have the .NET Framework 3.0 installed on your machine. If you’re running Windows Vista, you can skip this step, because the Framework is automatically installed with the operating system.
  • Download SWF2XAML_0.2.zip (521KB).
  • Extract all of the files to a folder of your choice.
  • Double-click SWF2XAML.exe to run the tool.

FlashDevelop 3 Alpha Released: Best Flash IDE Gets an Upgrade

Photo Sharing and Video Hosting at PhotobucketObligatory posting on FlashDevelop3 Alpha being released.  To people like me alpha means “old school” released.  I am ready to use it today!

Download it here

If you are not using FlashDevelop for your coding portion of your flash application, you might be missing out.  There is a reason some of the best actionscripters (ahem actioncoders) use it.

Follow

Get every new post delivered to your Inbox.