Category: Flex

  • Event Bubbling in Flex 1.5 & ActionScript 3

    Biggest problem I had in Flash was using a bucket brigade technique to notify one of my high level View controllers from a deeply nested View. Basically, if a form elment, nested in a form container with other views, that is in turn nested in a View controller; he has to go through the View he’s hosted in to get the event out to those who may care. In turn, the main View controller couldn’t subscribe to the event unless the hosting container forwarded it along… which is what I would do in Flash.

    The nested would dispatch his event:

    private function doSomething():Void
    {
       dispatchEvent({type: "someEvent", target: this});
    }

    Then, the View hosting it would have to suscribe to the event, and forward it up the chain:

    nestedView.addEventListener("someEvent", Delegate.create(this, doSomething));
    
    private function doSomething(event_obj:Object):Void
    {
       dispatchEvent(event_obj);
    }

    Pain in the ass, and suddenly Views know too much about eachother; a parent shouldn't have to do a child's handiwork.

    Peter Hall had made an ARP extension that allowed bubbling events.

    Apparently, Flex 1.5 already does that. I have a View nested 2 deep in some complicated Flex components, and all the main View controller has to do is subscribe to the View it hosts, and as long as no one intercepts it, the event will "bubble up" the Views to anyone who cares.

    This is accomplished by adding the bubbling property to true on the event object:

    private function doSomething():Void
    {
      dispatchEvent({type: "someEvent", bubbles: true, target: this});
    }

    Now, with Flex, you still have to define the event in the MetaData tag, much like you define Inspectable properties that component developers can use as getter/setters. So, that is one draw-back; you still have to define the event in whatever View uses it via composition. Bleh.

    I'm not really sure if AS3 requires the metadata, though. Since EventDispatcher is built into Flash Player 8.5, and the 3 phases of capture, target, and bubbling are built into the core of Sprites and MovieClips, I'm sure you probably don't have to define the event; you can just have faith in knowing that if you mark the event is bubbling, it'll flow up!

    :: goes to try a test ::

    :: 20 minutes later ::

    Well, that almost worked. Apparently, events that bubble cause Firefox to crash, haha! Anyway, I probably just found a bug in the alpha software, go figure, but if this is how easy it is to bubble events, awesome.

    Flex 2 Bubble Event Source Files

    *** Update 1.23.2006: Good write up on Event Bubbling with a great class by Bokel.

  • Blitting & Double Buffering for Tile Based Games in Flash & Flex: Part 1 of 3

    Why should you care? 96% to 6% CPU usage, that’s why.

    Flash Player 8 opened up a lot of boilerplate code via the new Bitmap drawing classes in ActionScript. Usually confined to the nether regions of Director via Lingo, one had to utilize the standard vector drawing tools in Flash. With the combination of runtime drawing with the sprite like nature of MovieClips, Flash enabled pretty powerful tile-based & other gaming engines to be created that were very flexible, and eased a lot of the coding pain that was harder in other graphical engines.

    Painful meaning, you had to write a lot more code to get the same result.

    Performance Bottlenecks – Many Objects

    The one issue, however, is performance. The Flash Player has a few performance bottlenecks, 3 of which tile-based games suffer from. The first is object overhead. Because of the way Flash Player 8 handles prototypes of classes, each Object class has a series of slots for functions and properties, 1 of which is for the proto and prototype properties. These allow the class to know what methods and properties he inherits from his base class as well as who his base class is. Walking up this chain of prototype objects to the main parent (Object) is how inheritance works when you call methods on an extended class; if it doesn’t find it on the immediate prototype, it walks up the chain until it does.

    There is significant overhead in creating objects, memory wise. Keeping track of all of the objects slot information, etc. results in a extreme downgrade in performance the more objects you create in Flash, specifically MovieClips. The more MovieClips you create, the slower things get, both in code response time and render time.

    Vector Drawings – less detail, high CPU cost

    A common response is to simply draw everything dynamically. Why create a tile class object directly (extending MovieClip) or indirectly (extending Object, use MovieClip instance via Composition in class’ constructor), when you can just draw the tiles via the runtime drawing tools into 1 movieclip, and handle mouse interactions via hitTest? Since most tilebased games are event-based, using the keyboard as the primary means of interactivity, the only real hardcore math you are doing is keeping track of where the characters are on the screen, the sprites, and determining if they are allowed to move to another tile.

    Utilizing meta-tiles, like Grant Skinner & Brandon Hall have spoken about before, you can significantly reduce collision detection if you need it for a smaller area of objects and tiles, thus lowering the amount of code needed to run for collision detection.

    This, however, leads to the 2nd issue. The drawing operations, while fast, are vector only. Most tile-based games utilize bitmaps. Drawing bitmaps would require pixel-precision to duplicate in vector, and vector images are extremely CPU intensive. Another option is to merely just attach bitmap tiles as MovieClips, but then you are back to the same problem of too many MovieClips. Even if they are in no way associated with a class (beyond MovieClip by default), you still incur the overhead.

    Bigger vector images do not scroll well either. Even if you don’t utilize strokes (since strokes are rendered differently fills, fills being more efficient when compared to strokes), you will notice the larger and/or more complex you make your vector drawing, the lower your framerate gets. The bigger and/or more complicated the drawing, the less responsive your scrolling maps and code gets.

    Bigger Drawing Area, Less Performance

    Finally, both of the above are contigent upon size of the drawing area. How big is your map, and how much are you displaying. Unfortunately the 2 play extremely little in performance. For example, if you’re drawing is 600×600, and you utilze a mask to only show 200×200, performance isn’t significantly improved, even if the stage itself is 200×200. The reason for this is even MovieClips with their visibility set to false, non-shown, or off-screen are still rendered. While the combination of visibility to false and putting them helps, it doesn’t gain you very much.

    Bigger images render slower, as do many small images taking up the same size area. A larger stage size renders slower than a smaller one. Both of the above have an extreme curve; I don’t have the trig for it, but basically significant performance gains can be gleaned from smaller drawing areas and smaller stage sizes.

    This doesn’t necessarely bode well for Flash Lite 1.1/2 either. While utilizing vector drawing tools sounds attractive for a runtime that only gives you 1 meg or less of RAM to play with, you must understand the phones CPU’s are not extremely powerful.

    Blitting

    Solving the 3 problems above can be solved via blitting & double buffering in combination with cacheAsBitmap and scrollRect.

    Defined succintly, blitting is taking 1 or more bitmaps, and combining them into 1 bitmap. So, if you remember the arcade game Pac-Man, imagine the game itself as 1 big bitmap and each element; the maze walls, the dots, the ghosts, the score text, and Pac-Man himself, as individual bitmaps, or pixels. Each is painted onto the same background, in order: walls, dots, Pac-Man, ghosts, and score. To the end viewer they appear is different elements because every frame some of the elements appear to move. In reality, it is just redrawn every frame, and only those areas that have changed.

    This is important for Flash Player because of a few reasons. First, Bitmaps take far less CPU to render. While Flash Player since day 1 has been a vector-to-pixel renderer, you now have true bitmap objects that are just that; a series of pixles with different colors on the screen. Drawing & displaying these on todays machines takes very little system resources. In all fairness, bitmaps take more RAM to display vs. CPU.

    Secondly, to create a scenario like the above, you are still just drawing and displaying 1 bitmap for what would of been a large number of sprites in Flash Player 7 or below. While sprites (Flash Player’s MovieClip) offer an easier way to animate and code, they are not efficient, ecspecially for an exteremely small runtime web player that utilizes no hardware acceleration, excluding some for newer Macs.

    Double Buffering

    You can accomplish blitting in Flash by using the new Bitmap classes. You can accomplish blitting for games by using something called Double Buffering.

    Defined succinctly in a Flash Player context, double buffering is a technique used display a bitmap on screen that contains a plethora of other bitmaps. One bitmap is drawn in RAM, with additional bitmaps blitted, (copied) onto it. Then, you copy the finished bitmap from RAM and display it on screen as one bitmap.

    This is done in screen drawing in other applications to prevent redraw issues, such as seeing the drawing as its being drawn. However, because of Flash’s single-threaded nature, this is mainly done to simplify coding and still getting the performance increase of only displaying 1 bitmap to the screen.

    Conclusion

    Thus, a developer has the opportunity to create some really compelling tile-based games in Flash Player now that the performance bottlenecks can be overcome via blitting and double-buffering.

    Part 2 will show how you utilize blitting and double-buffering in ActionScript 2 in Flash Player 8, and ActionScript 3 in Flash Player 8.5. Additionally, I’ll show you used to do things, and how you can get your CPU usage while scrolling the map to go from 96% to 6%.

  • Test Flash Remoting Services w/ ARP

    If you are developing service calls, but the back-end (Java, .NET, ColdFusion, etc.) isn’t done yet, you can still be productive by setting up test services. Utilizing what the ServiceLocator in ARP does best, you can point to your test service class instead of the real service, which would be a server gateway.

    Your test service is merely an ActionScript class that has all of the methods that your back-end service would have. So, if you plan on calling “createItem” and passing a string as the only parameter to some Java method on the backend, you merely mirror that in ActionScript.

    You do this for all of your methods. That way, you can continue writing your Commands and Business Delegate server calls as normal with plans to use them as is. When the back-end is ready, you change 2 lines of code in your ServiceLocator from this:

    var CreateItemsService = new TestService("", null, "CreateItemsService", null, null);
    addService("CreateItemsService", CreateItemsService);
    

    to this:

    var CreateItemsService = new Service("http://server.com/gateway", null, "CreateItemsService", null, null);
    addService("CreateItemsService", CreateItemsService);
    

    Notice the only thing that changes is you instantiate a real Flash Remoting Service class (Flex RemoteObject’ish), and put in a real gateway URL.

    That’s it!

    Here’s an example of the TestService.as file. This class extends the mx.remoting.Service class so it operates like a real remoting class. It’ll create Operations, return PendingCalls to server method calls, etc. All you do is make an interval so the method call “waits” 2 seconds before responding so it “feels” like it’s taking some time to talk to the server, where in reality there is no server at all, just ActionScript acting like it.

    Bottom line, to avoid the waterfall effect where a client developer is waiting on a server-side developer before she/he can proceed, this allows you to continue coding without a server, and if the server gets fubarred during development, you can merely toggle this back on to continue testing.

    I reckon this would work in Cairngorm too if you chose to use straight ActionScript instead of RemoteObject tags.

    import mx.remoting.Service;
    import mx.remoting.PendingCall;
    import mx.services.Log;
    import mx.remoting.Connection;
    import mx.rpc.Responder;
    
    class com.company.project.model.testing.TestService
    {
            private var speed:Number = 2 * 1000; // milliseconds
            
            private var createItemID:Number;
            private var createItemPC:PendingCall;
            
            function TestService(gatewayURI:String, logger:Log, serviceName:String, conn:Connection, resp:Responder)
            {
                    super.apply(this, arguments);
            }
            
            public function createItem(itemName:String):PendingCall
            {
                    clearInterval(createItemID);
                    createItemID = setInterval(this, "onCreatedItem", speed);
                    createItemPC = new PendingCall(Service(this), "createItem");
                    return createItemPC;
            }
            
            private function onCreatedItem():Void
            {
                    clearInterval(createItemID);
                    createItemID = null;
                    delete createItemID;
                    
                    createItemPC.onResult(true);
                    createItemPC = null;
                    delete createItemPC;
            }
    }
    
  • Re-invent Yourself: Flash to Flex Developer

    Preface

    I missed David Samuel’s Re-invent Yourself Personal Retreat this weekend. Last week was stressful, and I got little sleep Thursday. When the alarm went off Saturday morning at 6:30am, rather than hit snooze, I just turned it off. In my fading moments of consciousness, my left and right brain had a friendly debate, neurons firing over postulates and hypothesis of the risk/reward ratio of getting up and going.

    I had decided 3 months ago I would go. I had decided Friday night I would go. Yet, I didn’t go. At 11:00am, when I finally awoke to a blonde licking my face and stepping on my neck, I was very disappointed in myself. I’ve been cursing myself since.

    When I look back on my life before I pass, I’ll have no regrets, but this will be one of my admittedly bad mistakes. I’ve seen David speak before, and he had 2 colleagues with him this time, so I’m sure it was off the hook and I could of gained a lot.

    Background

    Why so glum about a seminar I missed? Because I really could of used some insight on how to re-invent myself.

    11 months ago, I fell in love with Flex. Coupled with Flash, it makes for a great team to create great apps, web and fat client front-ends.

    After a few experiences in large Flash applications, I realized it was time to move on. I was hoping I could remain a Flash Developer, and support the Flex Developers like Nigel’s article describes, but it was not to be. The more responsibility that was bequeathed to me in terms of application architecture, as well as a growing amount of team members, the more I realized Flash isn’t cut out for large application development. Weekend contract jobs, 3 month web app stints, and components created for re-use? Flash owns.

    But when you start getting into 6 months, have significant amount of views, and large amounts of data that are kept with your apps state… there is no other alternative than to use Flex.

    Developer Attitude & Pashion

    I am not like a lot of my colleagues’ in the industry, however. A majority I would assert are definitely of the mindset that you utilize the appropriate technology for job. If an application requires AJAX, Flash, older browsers, MySQL, Oracle, .NET, ColdFusion… whatever combination of client, middle, and back-end tier technologies work best given the business requirements, technology constraints, and your current resources.

    I, on the other hand, am loyal to craft, not to company. An ex-marine (once a marine, always a marine) manager at a former job told me that. I always liked to ask him questions about management and other terms that had nothing to do with programming since he could explain it using terms and analogies I could understand. “Managing Einsteins” as he put it was challenging, referring to managing a plethora of engineers in our technology department. He used that phrase towards me, saying that because I am loyal to craft, and not to company, he as a manager needed to provide opportunities for me to excel and be challenged at my favored technology or risk losing me as a company asset. Bad ass concept!

    I find that extends, however, to my view on my career. I thrive in instability, work extremely well under pressure, and have a passion for what I do. So, if the appropriate technology to use on a project is AJAX… I simply wouldn’t do it. Hear me out. Am I qualified? No, I don’t do HTML + CSS + JavaScript for a living, so anyone who considered me a resource on that project has grossly misjudged my skill set. Can I learn to do it? Absolutely! It is very similar to what I do today; using an SGML markup to render form elements, connect the logic the forms use together via an ECMA script based language, and style them using CSS.

    Do I want to? Hell no. I’m not passionate about it, fail to see how I can excel at it since I hate it, view it as an inferior technology, and if Jesse Warden isn’t kicking ass and taking numbers, he’s finding a way to do so. And that way is finding an avenue where people can utilize my skill set for an appropriate job.

    What that boils down to is targeted employment opportunities. Meaning, my contracting and employment goals are focused on getting employment in a specific area of development, mainly Flex with a little Flash vs. just a steady job that pays. Many jobs, big and small, require developers to wear many hats. I believe any competent engineer can code .NET 1 week, and learn to code in PHP the next, and succeed at many projects in the long run.

    Do I want to? No, but will I? Well, in my experience, I’ve never had that happen. I’ve had to learn ASP because there were no programmers available, but I still used Flash for the front-end. I’ve had to learn enough about SQL Server to update database tables… but I still used Flash on the front-end. Currently, I’m learning about setting up and using ColdFusion… but I’m still using Flex on the front-end. The only thing I can conclude is that in my case, there is no question what Jesse Warden will utilize on the client-side, but on the middle-tier and back-ends, whatever is appropriate. It is already assumed that Jesse wouldn’t be here working on said project if it were not already previously established Flex was the appropriate client side technology.

    Hiring Craze

    So, with that being said & established things have been crazy this summer. Thanks to my large contractor list, I’ve managed to hopefully fulfill the daily job & contracting requests I get to potential clients & headhunters. There have been cases, however, where potential opportunities were actually in my best interest to see where they led. It doesn’t mean I’d actually take said positions, but hearing what people have to say is very telling of the industry, opens up new networking contacts, and at the very least hopefully allows me to find them a potential candidate I may know who’s appropriate for the opportunity.

    Usually February/March and October/November are “Hire a RIA Developer” months. Not sure what it is, but my guess is budgets are either approved by the beginning of the year, or there is enough left over towards 3rd quarter to hire more. Either way, I usually get inundated with contract positions and potential jobs for employers either seeking me, my skills from a website, or most often if I know anyone. My canned response is usually that I’m busy (which is true), and I then provide them with my list of contractors, with notes on who’d be most appropriate to contact.

    The ones that sound interesting to pursue, I’ll usually follow-up with I’m interested, but not available with the hopes that they’ll let me in what their company is doing; I’m always fascinated & interested in what companies are working on in the Flash & Flex sphere so take every opportunity to find out more about it.

    Three opportunities in the past 3 months have really hit home to me, 2 of which made it to employment descriptions and I had to decline because I already have a great gig going on, but again wanted to hear what they had to say.

    The first was a Flash opportunity working with a bunch of experienced and talented developers as well as some I could work with to train. I could make good money, work in a stable & growing company doing product based work (meaning re-use of code base without wildly different approaches to different projects), train fellow developers, and hopefully work towards management training. Problems? No room for Flex in the near future. I’ve had enough battling with Flash in my career to know that even when developing multimedia games, I’d prefer to utilize Flex. I couldn’t justify doing small time development; while extremely less stressful as well as leaving more room for getting myself mentored, something I’ve longed for from a couple past jobs, I know I have other areas where I should be to improve my career, case in point working on larger scope projects with more appropriate deadlines. Challenging my pragmatic assumptions is my current personal goal. Meaning, I know enough about OOP, encapsulation, and design patterns that they really falter under tight deadlines; I’ll use them until the boss starts giving me the stern gaze at which point they go out the window without much fan fair.

    Ok, cool, so at the time, I had 2 other real, Flex opportunities on the horizon. I’m ready to move to the my next level. Keyword, my, as I don’t think going from smaller time development to more Enterprise level development is the next level, because seeing Enterprise Developers put into a smaller shop is just as paradigm smashing, and fun to watch.

    I’ve had a series of emails that lead up to a 2 minute call this morning. Usually what happens is, if people press me to talk to them instead of sending them contact information of those of my fellow contracts, I give them my current contract rate and explain again how much I apologize, but I’m busy beyond belief, and am willing to take a few minutes to hear what they have to say, and recommend either a personal path or a technology path; they should look into hiring “X”, and/or using technology “X”, sometimes what they already have.

    The majority of the time, these extremely short phone calls are with recruiters, while I’m making lunch. I try to be as positive and helpful as possible, gleaning as much information as possible about the position(s), and recommend who they contact and why.

    When it’s an actual potential position, like today, I try to pry as to why they want X technology (Flash or Flex), how they found me, and why, all the while preparing in my head who I can recommend, and confirming they sound like they are on the right technological path.

    Tipping Point

    Today was the 2nd time I’ve seen a clear gap in Flash vs. Flex developer employment. This is big to me, because for the past 18 months, it’s been more about education. 9 times out of 10, they just had no clue about Flex, or had heard some information about it and Laszlo, but were investigating it at the same time as looking for potential candidates. At this point, I’ll proceed to explain the various options, and give my suggestions.

    I clearly explained I am not interested Flash development, I am 100%, gung ho for full-time Flex development, and recounted my past experiences up till now to give some context as to why. I heard him out, heard what he is looking for, and got a tiny bit of information on their existing products and plans.

    I’ve done this like 3 times this year, first 2 with recruiters, so it wasn’t anything new… hell, it’s getting routine. What was different about this call, however, was the clear cut & quick understanding that I wasn’t a fit for the position.

    People may think it’s obvious, but it’s amazing how easy this stuff is when you know what you want to do. Ask anyone what they want to do, and I bet you the majority have a guess, not a true, confirmed understanding. I do, so when people ask, it borders on yes or no.

    I guess what was scary is this was an additional incident in a growing series, and most importantly, it happened when I’m an already employed Flex contractor vs. a recently un-employed Flash contractor. It was confirmation I had crossed to the other side.

    Eerie.

    The only thing I didn’t like about the conversation was I gave the false impression that I use Flex for mundane, forms based development, creating SWF front-ends for CRUD (create, read, update, delete) back-ends, and how I no longer utilize my multimedia skill sets that flourished when using Flash. That isn’t really true, nor an accurate picture of what I do, but it certainly was illustrated in the gentleman’s response comment asking if I knew anyone who was good at doing creative, application development with Flash.

    Apparently, I failed at illustrating that Flex was more than capable of doing that was as well, even with Flash’ help via integrating the workflows. It was ok, though, because the current Flex 1.5 license doesn’t fit with their budget and team size. Regardless, Flex Builder 2 does (at least from initial reports), and I was frustrated at myself for not correctly articulating those points.

    I may give the impression I get these calls “all the time” and that’s not the case; it’s just the pure volume and frequency of emails & phone calls about asking for Flash & Flex talent, compounded by the re-invigoration in discussing Flex because of the Flex Builder 2 announcement at MAX is making me euphoric about the state of this industry.

    Conclusion

    Bottom line, I’m in the process of re-inventing myself as a Flex Developer, and it’s hard. I could really use some guidance and that’s why I was really upset about not attending last weekend’s Re-invent Yourself retreat. Although the work I do is more appropriate for Flex development, my years spent in Flash make it that much cooler, and I can see a lot of opportunities in mixing the two.

    Explaining that, formulating that into an actionable plan, and setting multiple personal goals at attaining & defining what a Flex Developer is, however, is proving extremely challenging.

    I know I want to continue doing what I’m doing currently, and that is doing Flex work for my current employer. At least I got a solid base to work from, and all your base are belong to us!