Paul Taylor's Blog

The Flex Framework and Modularity: A Manifesto

by Paul Taylor on Jan.20, 2010, under Bitching, Development

If you haven’t watched Greg Burch’s excellent presentation on Slider at RIAdventure, you freakin should. Seriously, stop right now and watch it. But don’t forget about this blog post. Make sure to come back here after you’re done.

The Soul of Flex
Ok, from this point on I am going to assume you’ve done exactly as I told you and watched Greg Burch’s excellent presentation on Slider at RIAdventure. Around 6 minutes in, Greg starts talking about the Soul of Flex. I didn’t have much time to consider it, but two things immediately came to mind: invalidation and styles. In the video you’ll hear me mention CSS but later agree with Greg that CSS or not, styles is the true feature.

Of course, I agree with all the others he said were also part of the Soul: MXML, databinding, states, skinning, item renderers, containers, and components. But as I watched him remove items that weren’t part of the Soul of Flex, I thought to myself:

“Self, this list is completely subjective and based entirely on my opinion. It is extremely likely that someone else’s definition of the Soul of Flex is different than mine, and who’s to say which one is right? Is it Adobe’s job? Now that they’ve packed a framework full of features that real people use, they’re going to remove a good many features simply because the they do not fall into Adobe’s definition of what the Soul is? That’s not right. The community is too diverse for that. Flex is the Soul of Flex.”

The real Soul of Flex

I say Flex is the Soul of Flex.

This got me thinking about Flex with regards to mobile development. At the time of this writing, every Flex 4 component has a base class that is 13,246 lines of code. UPDATE: I told my buddy Jon Toland I was writing this article, so he wrote a Javascript parser to count comments, blank lines, and actual lines of code. Turns out, the UIComponent currently has 1412 blank lines, 6423 comment lines, and 5411 actual code lines. If you’re using Flex 4 and skinning, you have two components, so multiply potentially everything the UIComponent does by 2:

  • 2x the UIComponents to initialize
  • 2x the UIComponents added to the inheriting style chain
  • 2x the UIComponents to make validation passes on
  • 2x the event listeners that are registered
  • 2x the number of objects for the DragProxy (in the DragManager) to find in its getObjectsUnderPoint() implementation
  • and on and on…

This means one of two things. Either the decision to abstract skins into another UIComponent was monumentally retarded, or the UIComponent is too large and tries to do to many things. Since I believe the new skins are wonderful from an architectural/modularity standpoint, I have to pick the second choice: the UIComponent is too damn big. It tries to do too damn much. Let me reiterate: I love the new Spark skins. I hate the size of the UIComponent.

The Question of Responsibility
Why is the UIComponent (at the time of this writing) 13,246 lines long? The answer is features. The UIComponent violates the Single Responsibility Principle. Here’s a list of most of the features the UIComponent encapsulates:

  • Invalidation – Implements IInvalidating.
    • Defines invalidate properties/size/displayList functions.
    • Defines validateNow function.
  • Validation – Implements ILayoutManagerClient.
    • Defines the initialized, nestLevel, processedDescriptors, and updateCompletePendingFlag properties.
    • Defines validate properties/size/displayList functions.
  • Styles – Implements IAdvancedStyleClient, the only visual class that does.
  • States – Implements IStateClient and IStateClient2 to support the new Fx4 states syntax.
  • Tooltips – Implements IToolTipManagerClient, the only component class that does.
  • Constraint-based layout.
  • IRepeaterClient – UIComponents (and subclasses) can be created by Repeaters.
  • Databinding.
  • Related to Databinding, implements IPropertyChangeNotifier.
  • Embedded fonts.
  • Focus – Doesn’t implement IFocusManagerComponent by name, but does implement the functions. Has a reference to the FocusManager and a focusPane property.
  • Validators – Implements IValidatorListener, which allows the UIComponent to respond to ValidationResultEvents dispatched by the Validator classes.
  • Modules – Implements IFlexModule, so if created by an IFlexModuleFactory, the factory stores a reference of itself on the UIComponent.
  • Explicit/measured- max/min – widths/heights.
  • Percent widths/heights.
  • Enabled/disabled.
  • Effects.
  • Special logic for adding/removing children.
  • All the events it creates and dispatches, including
    1. Initialization events, like preInit and creationComplete.
    2. FlexEvents like show, hide, move, resize
    3. StateChangeEvents.
    4. DragEvents for the List classes. Not part of the public API.
    5. ToolTipEvents
    6. FlexMouseEvents

Man, the UIComponent does a ton of stuff. We haven’t even gotten into the measurement, layout, containment, children handling, skinning, item renderers, or graphics functionality of Flex yet!

The UIComponent is the base class for… everything
At least, everything visual. Not including Flex 3 skins. It’s the base class for all non-Fx3-skin-related visual elements.

The UIComponent has so many responsibilities because it is the base class for so many controls. You want a Label or TextArea? They’re UIComponents. You want a Button? It’s a UIComponent. You want a container of Buttons? It’s a UIComponent.

But there are a few things I can’t figure out about this configuration:

  1. Why does a container need logic in its base class that accesses embedded fonts, or creates UITextFields from embedded font contexts (I checked, UITextField is the only class passed into createInFontContext()).
  2. Similarly, why does a Label require any knowledge about processedDescriptors, states, or validators? Labels can’t have children, states, or validators. In fact, Labels can’t do much except display text. Why do they need to be IFlexModule objects? I could go on, but I think you get the point.

There is a trend of WTFs like this about the UIComponent that can only be explained by, “it’s the base class and we’re trying to keep our API super clean.”

There is a better way: Composited Modularity
Most of the functionality is already segregated by the liberal use of interfaces… now lets actually implement it that way.

Almost all the functionality that the UIComponent (and subclasses of UIComponent for that matter) contains can be grouped into smaller, more discreet classes. Lets call them modules. Once this is done, the UIComponent simply exists to provide a unified API to the developer and glue with which to assemble the modules. More complex controls and components are simply composed of more complex modules.

For example, the functionality for embedded fonts should be isolated into its own module. Then, only the Label, Text, TextArea, and maybe some other controls that require direct access to embedded fonts need to include the “EmbeddedFontsModule.” This way, the VBox doesn’t have to include functionality for accessing embedded fonts.

Similarly, a VBox would include special modules for adding children, measurement, and layout. See, this is easy.

And while we’re at it, let’s rewrite the LayoutManager.

You heard me. The LayoutManager. It’s in my sights.
What’s so special about 3-phased validation that it has to be hard-coded into the Flex framework? Is it phase ordering? Nest-level ordering? That’s not special. That’s algorithms.

First, for those who don’t know, the LayoutManager is what enables Flex components to do the awesome 3-phase component lifecycle that we’ve all come to know and love. When a component is invalidated for a phase (say, invalidateProperties()), he registers with the LayoutManager. The LayoutManager adds the component to the proper invalidation queue. There are 3 invalidation queues, one for each validation phase. The invalidation queues are a special PriorityQueue implementation. This is important, because there is an order to the validation process.

Components have a nestLevel, which is really just their position in the display list. The Application’s nestLevel is 3. The nestLevel increases from there, so the lowest component in the display tree has the highest number.

When a component is added to the invalidatePropertiesQueue, it is added at its nestLevel priority. When the invalidatePropertiesQueue is processed, components with the lowest nestLevel, the ones closest to 0, are processed first. This is called “top-down” processing, because it starts at the top of the display list and processes to the bottom.

The commit phase does top-down processing, because generally parents can commit properties on themselves and change properties on their children, which will then get committed. The measure phase is from the bottom-up (can you guess what that means? If not, put it in the comments.), because a parent will often make a decision on his size based on the sizes of his children. The update phase is another top-down queue, because now that the sizes and positions are calculated, it’s time to lay them out. This is what makes percent widths/heights, scrollbars, etc. possible.

Rethinking validation
Does validation have to be hardcoded? Are the 3 phases all that are needed? How hard would it be to switch to just 2? 4? 100?

The fact is, the developer should be able to hook into the power of phased updates for himself. Why have a manager that only validates 3 hard-coded phases, when you could have a manager that validates an unlimited number of dynamic phases?
Well sure Paul, that sounds great and all, but it’s kind of a tough problem. <– Shut up alternate text, I’ve got a solution.

Keep the idea of nestLevel. It’s clear, clean, and definite. Change the idea of 3 hard-coded phases into an unlimited number of injected phases, based on priorities. Similar to nestLevel for components, priorities are arbitrarily defined by the developer. A priority is an Array of ints. It can be as simple as “1″ or as complex as “1.2.3.4.” It is only used as a basis for comparison between other priorities. For example, priority 1.2 is greater than priority 1.2.1, since it is assumed 1.2.1 is a subset of 1.2. However, 1.200 is much greater than 1.2, because 200 > 2. Do priorities make sense? If the answer is no, put it in the comments.

The idea is that a developer can invalidate a component for a certain phase. The phase has a priority (like 1.3), and a direction (UP or DOWN). The ValidationManager keeps a Heap of Heaps, sorted by priority. If it doesn’t find a Heap at the priority specified, it creates a new Heap, adds the IValidationClient to it, sets the proper sort direction (UP or DOWN) on it, then adds the new Heap to the Heap of Heaps. If it does find a Heap, it adds the IValidationClient to the Heap that it found.

When it comes time to Validate (on the next enter_frame event), the ValidationManager dequeues each Heap from the Heap of Heaps. Then it dequeues each item from each individual Heap, validating it as it goes.

The beauty of this is that the Flex component lifecycle can be perfectly mimicked. Set the three phases to happen one after another, and you can get the same results. For APIs sake, lets add a gap between them, so a third party developer can come by later and inject his own phases between the 3 usual phases. If we set commit at 1.3, measure at 1.5, and update at 1.7, this should give us enough of a gap for developers to use.

Say Developer X wants to add some extra umph to his custom component, but needs this processing needs to happen in-phase and inbetween the measure and update phases. He simply needs to inject his own validation phase anywhere between measure at 1.5 and update at 1.7, lets keep it simple and say 1.6, and BAM. ValidationManager will validate his phase right after measure and right before update.

This allows the developers a whole new avenue of development, something that they would have had to tack onto one of Flex’s 3 hard-coded phases before.

This is all words. Where are the actions. You fail.

This is where I introduce FlashWorks
FlashWorks is a component set for Flash and FlashBuilder, designed around the concepts of a tiny core API and modularity.

It includes the ValidationManager and validation scheme I’ve outlined here, as well as a few other things:

  • MXML development
  • Skinning similar to Flex 4
  • Graphics primitives (extend EventDispatcher)
  • Measurement and Layout controllers with support for percent widths/heights
  • Injectable Validation phases
  • States, including support for FB4’s new States syntax
  • Styles, through a controller that interfaces with Jesse Freeman’s F*CSS
  • Databinding
  • SystemManager that works with FB4’s code generation, so the FlashWorks movie is 2 frames, just like Flex.
  • A modular, pay-as-you-go system, so functionality is only included when it’s used. For instance, the States controller isn’t included unless States are defined on the component.

Alright, here’s the code and demos

Code: http://github.com/guyinthechair/FlashWorks
Demo: http://guyinthechair.com/misc/flashworks/FlashWorks.html
Source code for demo: http://guyinthechair.com/misc/flashworks/srcview/index.html

Leave a Comment :, , , , , , , more...

Understanding the Flex SystemManager

by Paul Taylor on Jan.17, 2010, under Development

Before I start, let me say that there has been a lot of discussion about the SystemManager on various blogs. Deepa posted a fantastic write-up on the SystemManager back in October 07, which really got me interested in learning about it more. Working on Flex-less MXML is what finally pushed me to understand exactly why it’s such a critical class. There’s a lot to cover about the SystemManager, from the behavior of the Flash Player to the behavior of the Flex compiler, so buckle up, cause this is a long one.

Note 1: A recurring theme in this post is the fundamental behavior of the Flash Player. Flex would be nowhere without Flash, so if we desire true understanding of Flex, we must also understand the Flash Player.
Note 2: For some of this, it is helpful to turn on the -keep-generated-actionscript flag in the FlashBuilder compiler options. To do this, go to Project –> Properties –> Flex Compiler. In the “Additional compiler arguments” field, type “-keep” at the end of the arguments list. FlashBuilder generates ActionScript from all your MXML, including a dynamic subclass of SystemManager. This will instruct FlashBuilder to place that code in the bin-debug/generated folder.

To understand the SystemManager, you must first understand that…

Every Flex Application is a 2-Frame Flash Movie

2 Frame Flash Movie Yes, every one of them. The Flash Player is capable of downloading just the data for the first frame and streaming the rest of the movie. Therefore a trend started in the earlier days of Flash-only developing; you typically put a very small loader object on your first frame that displays the loading progress of the rest of the SWF to the user. That way the user has a visual indication that something is happening, and the movie gets preloaded to a point where the user won’t experience any playback hiccups.

That is awesome… why do I care?
Good question. First, lets examine the implications of Flash’s load-and-stream feature:

From a movie perspective if frames aren’t loaded, the movie stops until they are loaded. If the movie is constantly experiencing this, the movie’s framerate essentially becomes a function of the speed of the user’s internet connection.
From a code perspective, if frames aren’t fully loaded, classes can’t be accessed. Calling new MyObject() will throw a runtime error, “1065: Variable MyObject is not defined.” This is because the frame that contains the definition for that class hasn’t been fully loaded.

Surely code is much smaller…
…and could be loaded much quicker. Why show a pre-loader for something that is a few kilobytes? This question has two answers, one from the camp of pragmatism, the other from a technical perspective.

First, the pragmatic answer: You can’t guarantee your code will stay within the size limits of a few kilobytes. You can’t ever ever ever guarantee this. Therefore the best solution is to show a progress bar, so when (not if) the size of your application grows, you won’t run into scalability problems down the road related to 1065 errors.
Second, the technical answer: You can’t guarantee your code will be executed if it’s in the constructor on the first frame of a movie. To know more, we have to understand a bit about the anatomy of a frame:

Disclaimer: This is only based on my experience with Flash. I don’t have any absolute knowledge or real facts to back this up, and I welcome feedback from people with real knowledge.

At startup, the Flash Player only loads in the data required to build a frame object, meaning it loads in the frame information and the Document class’s constructor. If your Document class kicks off a lot of logic from the constructor, the Flash Player won’t run it all. The loaderInfo object of the root dispatches the Event.INIT event when it is safe to start acting. This is the beginning of the Elastic Racetrack, as Ted Patrick explains it (updated for FP9 here). As best as I can tell, everything before the Event.INIT event is Flash Player internal processing, as well as trying to run the code in your constructor. If it can’t manage to run all the code in the constructor in one AS3 time slice (including if the code isn’t fully loaded to run), it doesn’t care. The code is passed over and it is assumed that you (the developer) screwed up in not knowing about this.

So your code might or might not be run. And you’ll never be able to predict it. It will depend entirely on how fast your user’s internet connection and computer are. When you develop locally, it will work perfectly, because you have a super-awesome fast dev computer and hard drive latency is basically non-existant, so it takes less time to load the SWF than the Flash Player takes to initialize the frame. Unless you are deferring your code until the Event.INIT event is dispatched from the root.loaderInfo object, your app will be buggy at best, and plain fail at worst. Since you have to listen for this event anyway, why not have a pre-loader?

Oh I see now, so we need a small preloader on the first frame?
Exactly. All that silly Flash that we thought we left behind when we became “Enterprise Flex Developers” has come back to bite us in the ass. But never fear, the SystemManager is here.

The SystemManager is a fancy MovieClip. The SystemManager has a few duties, including:

  • Create and initialize the pre-loader to show to the user during app load and startup.
  • Manage loading in RSLs.
  • Manage module logic. If the SystemManager is the root of the SWF, he knows he is a Flex Application. If he is not the root of the SWF, he knows he is a module, and must communicate with whichever SystemManager is the root of the SWF (see if you can spot the logical flaw of the assumption made in that sentence, there will be a quiz later). SystemManager must communicate events both ways between modules/app, such as mouse and keyboard events.
  • Manage Event.RESIZE events dispatched from the Stage.
  • Manages the embedded fonts list
  • Initializes the various manager singletons, such as ResourceManager and StylesManager.
  • Manages top-level application windows. The SystemManager maintains a cursorChildren list and a popUpChildren list, for tooltips and pop-up windows respectively.
  • Once all the code for the movie is loaded, SystemManager creates your actual Application instance and calls initialize().
  • Adds the Application to the stage once the Application dispatches its FlexEvent.CREATION_COMPLETE event. This is why the Application doesn’t have a reference to the stage when its FlexEvent.CREATION_COMPLETE is dispatched, when all the other components do.

How it works
How the SystemManager does its thing. Matching colors are event listening/dispatching pairs.

Frame 1

Frame 2

  • stop()
  • listen for init event
  • init dispatched:
    1. get root SystemManager (if we’re not the top level)
    2. listen for enterFrame event
    3. create preloader
    4. listen for preloaderDocFrameReady from preloader
    5. listen for complete from preloader
    6. load RSLs and wait
    7. RSLs loaded. preloaderDocFrameReady dispatched by preloader
      • Timer created to go run nextFrame() after 100 milliseconds
    8. Exactly 10 milliseconds after preloaderDocFrameReady dispatched, complete dispatched by preloader
    9. Timer event dispatched, nextFrame() called/enterFrame handler triggered
  • Managers initialized.
  • Stage Resize listener added.
  • Application instance created.
  • listener for Application creationComplete added
  • nextFrame()
  • Application creationComplete dispatched
    1. Preloader removed
    2. Application added to the stage
    3. applicationComplete event dispatched

Hold on, I’m a Flex developer. I don’t work with frames.
I don’t have access to the timeline of my SWF. Actually, you do.

It’s through an undocumented meta tag, [Frame], which is really just a shortcut for the -frames compiler option. You can read all about the frame meta tag at Roger Gonzalez’s blog, but here’s the gist of it: If you add the [Frame] meta tag to the top of the Application class of your project, the Flex compiler will insert a frame before the frame that your Application is on. If you specify the factoryClass property on the meta tag, the Flex compiler will generate a subclass of whichever class you specify as the factory, and put that on the frame it creates. If you open up the mx.core.Application class, you’ll see the line [Frame(factoryClass="mx.managers.SystemManager")] near the top. This tells the Flex compiler to create a frame before the mx.core.Application, and attach a generated subclass of mx.managers.SystemManager.

The Flex compiler will generate a subclass of your factory class that implements IFlexModuleFactory. As long as your SystemManager implements IFlexModuleFactory, your code will compile. The Flex compiler overrides the info() method and returns information specific to your Application, such as a list of embedded fonts and the name of your Application.

And with this meta tag, you can override the default SystemManager implementation. As Roger says, “if the [Frame] metadata exists on the base class of your application, a subclass of the factory will be generated. If the metadata is directly on your application class, it will be honored, but no subclass will be generated; its assumed that you’ve already written the appropriate factory.”

Why this is cool

Most Flex developers will never even know the SystemManager exists, and they shouldn’t have to. Adobe has done a good job of masking Flash behind a more professional, Java-like framework with Flex. If you want to write an app with zero dependence on the Flex framework, but still use the fantastic FlashBuilder IDE, debugger/profiler, MXML, and binding, this is really good to know. You can write an Application based on Sprite, write your own stripped down version of the SystemManager, and then write MXML and take advantage of Flex’s bindings and generated code. Rock on.

Leave a Comment :, , , more...

360 Flex/RIAdventure Cruise

by Paul Taylor on Dec.14, 2009, under Development, Meetings, Uncategorized

RIAdventure Cruise

I just got back from the RIAdventure cruise and WOW, what an awesome time! This was the only conference I’ve been to where both the speakers and attendees were all top-notch. Being locked on a cruise ship in the Caribbean for 7 days with these guys was an incredible experience. And I never heard the words, “no, I don’t want to discuss work topics, we’re on vacation!”

On the last day, I filled in for Sam Rivello, who was recovering from a drunken leap off the ship’s main staircase. I threw together a demo of the Particle Emitter Publishing Tool I blogged about a few weeks ago, and showed how easy it is to implement a TweensyFX particle emitter in your app (either through MXML or Actionscript, your choice). A few of the Tweensy classes use constructor injection (they require parameters in the constructor), which isn’t compatible with MXML, so I extended and used the subclasses for MXML instead. Hopefully when Tweensy gets to 1.0, all the constructor injection will be stripped out, as setter injection is usually more efficient anyway.

When I presented this, I got some really great feedback about ways to make it better. I know that I’ve got to work on the interface, as it’s not very intuitive and is difficult to navigate. A great idea that Josh Cyr suggested is a publishing community, where people can submit, rate, and comment on different FX. I envision something similar to Adobe Kuler, or the Flex 3 Regexp Explorer.

Here’s the demo, and here’s the source. The SWF Profiler in the demo overrides the right-click “View Source” option, so sorry about that. Here’s the EmitterCanvas I used to render Emitters and IEffects to one BitmapLayer.

2 Comments :, , , , , , more...

Particle Emitter Publishing Tool

by Paul Taylor on Nov.23, 2009, under Development, Uncategorized

I’m tired, so I’m going to keep this quick. The Emitter class by Tweensy is fantastic and fun to use, but it’s not easy to imagine what an effect will look like without coding up an example.

That’s why I’ve put together a publishing tool for Tweensy’s particle Emitter. I’m using 15 sample particles embedded in a SWF, which you can download here. Launch the editor here.

Some features of this editor include:

  • The ability to save configurations to a file to be loaded again later (serializing the data to AMF and reading it in to restore state). This means your designers can fiddle with the animations and then email you the configuration.
  • A code generater for each Emitter and each BitmapFilter applied, which means you can load up the configuration the designers sent you and pretty much copy/paste the code into your project.

I will update to add more effects, like the PerlinDisplacementEffect that helps with the really cool fire effects Tweensy is capable of, but for now this is what I’ve got.

Once you add an emitter, you’ll need to set at least the emission frequency, emission randomness, and particle life to see anything happen. After that I suggest moving the X/Y coords and turning on either the Blur filter or the ColorTransform filter. Changing the start and end colors does some dramatic things, as well as fiddling with the blendMode (I suggest either Normal or Add). If you’ve got any questions or feature requests, leave them in the comments. Good luck!

Update: Here’s two sample emitters to start off with: Effect 1 and Fireworks (right click and “Save as…”, keeping the .amf extension).

Update 2: Added the PerlinDisplacementEffect. Try it out!

3 Comments :, , , , , , , more...

Specify any property, style any object (not just UIComponent!)

by Paul Taylor on Nov.08, 2009, under Development

The styles in Flex are a wonderful thing. They allow a degree of control over the views in your app without the need to modify source code and recompile. However, the styles are (mostly) predefined and quite rigid. There are reasons for this, but the application of styles are not always consistent with the spirit of the idea.

For instance, you cannot set the x, y, width, or height properties on a component through styles, presumably because it would negatively affect layout algorithms. However, you can set the horizontalCenter style, which affects the placement of components inside Container subclasses that use CanvasLayout (Canvas and any containers with layout="absolute"). If horizontalCenter is defined, these containers obey the law of the style instead of the developer who manually sets the x or y. So if you have a production application, with your layouts working well and code running smoothly, all it takes to completely screw over your Canvases and Panels is for Canvas{horizontalCenter: 0;} to appear somewhere in your external stylesheet.

Another problem with styles is that there is no way to retrieve the styles contained in a CSSStyleDeclaration object. This means that you can’t style an object that doesn’t extend UIComponent. One can argue that this is by design: the inheriting nature of certain styles means that it is very costly to maintain the chain throughout all the components, and UIComponent has a very nice caching scheme. But this is a pain when you work with Sprites and Shapes instead of UIComponents and ProgrammaticSkins.

So if you want a-la-carte styling without the UIComponent, you are out of luck.

The solution? Monkey-patch (or underride, as Doug McCune called it) the CSSStyleDeclaration object to expose a getter called styles. Ideally, this function returns all the styles in the order that they are overridden. So a style set through MXML overrides a style set through a stylesheet, and a style set using setStyle() overrides a style set through MXML.

Luckily, I have written the monkey-patch for you. All you need to do is put it inside a package called mx.styles in your project, and your app will be using the new CSSStyleDeclaration class.

Get it here, and view a demo here.

3 Comments more...

Physics and Flex: Box2DFlashAS3 meets Flex

by Paul Taylor on Oct.15, 2009, under Development

Update: I have since abandoned this project in favor of the PushButton Engine, which wraps Box2D and provides a better graphics and component set than I could hope to achieve on my own. So far this has served as a useful academic exercise, and I will keep the code here for future reference.

The Setup

For those not in the know, Box2D is an open source 2D physics engine for C++. There are many ports of it, and luckily there’s one for AS3 (Box2DFlashAS3). The current version (2.0.2) looks very similar to the C++ version, and might be a straight port (I’m not entirely sure). It follows the C++ syntax of class prefixes and allows public access to (what should be) internal member variables. 2.1 promises cleaned up syntax and fixed accessor types, but until then, the library can seem daunting to the uninitiated.

The Problem

The main problem is that Box2D doesn’t define a (reusable) way to graphically represent objects on the screen. It only simulates the interactions between the objects mathematically. This is very efficient, but not very convenient if you need to rapidly prototype a physics based application. There are tools to build Box2D worlds for the Flash environment, but they emphasize working within the Flash IDE. I hate and loathe the Flash IDE (not AS3 projects themselves, mind you). I want something tailored for Flex. I want something that fits into the rapid application development cycle of most Flex apps, which means I want to use MXML. I want to stay up to date with the Box2D project, so when 2.1 does roll around, I won’t have to rewrite application code.

The Solution

Enter FlexWorld. FlexWorld is a framework for graphical representation of Box2D bodies. It is most similar to the World Construction Kit, but is meant exclusively for Flex. You get all the benefits of Flex, including the LayoutManager, styles, events, data binding, and MXML.

The Demo

FlexWorld Demo (launches in a new window)

How it Works

FlexWorld starts with a PhysicalWorld, which is a subclass of Container. PhysicalWorld has boundaries determined by its width and height. Children of the PhysicalWorld are typically subclasses of the abstract class PhysicalBody (which extends UIComponent). Right now, only the PhysicalBox and PhysicalCircle classes are available. World initialization happens only when you say it does, and clean up is as efficient as can be. To get going, initialize the world: PhysicalWorld#createWorld. Then, you can register each PhysicalBody with the world by calling PhysicalWorld#registerBody. This is to ensure proper instantiation and update. When the world is ready to go, just call PhysicalWorld#activate, and it will start rendering.

In-Phase updates

PhysicalWorld renders by calling PhysicalBody#update on each PhysicalBody registered with it. This render cycle falls into the commitProperties phase of the component lifecycle (more on that here and here). This ensures that properties are changed at the beginning of the lifecycle, just before commits will happen. If the render is meant to continue, updateDisplayList (which is at the end of the update cycle) will call UIComponent#invalidateProperties on the PhysicalWorld.

Where is this going

This is a very alpha release. Everything that you see works, and not much else. The shapes aren’t interactive yet, and they don’t do much drawing beyond what you see. Nothing is documented (and I’m horrible at keeping up with it), I don’t even have an SVN repository set up yet. Right now it’s primarily an interesting proof-of-concept rather than a useful tool. I’ll be developing it more for a project I’m currently on, and hopefully I’ll roll those changes in.

The Source

The source for the demo is here.
The source for the library (including Box2DFlashAS3 2.0.2) is here.

2 Comments :, , , , , , , , , , , more...

Flex Equalizer

by Paul Taylor on Jan.19, 2009, under Development

This is not a new concept in Flash, but as far as I could tell, there weren’t many solutions for this in Flex. Here’s my stab at doing an equalizer. Watch out for your ears, the volume is set to 100% by default.

http://guyinthechair.com/wp-content/flex/equalizer/EqualizerApplication.html

Fixed
I do have one small problem with it, and I’m working to figure it out… for reasons unknown to me the SoundMixer.computeSpectrum function will return a null array sometimes. I have absolutely no clue why, and I’m open to any suggestions as to why. It only errors in the first 5 seconds.

Update: Figured it out. The problem was that I was relying on EnterFrame to call the render method on the equalizer. Unfortunately, EnterFrame could potentially be dispatched before the sound file was loaded from the server, therefore computeSpectrum wouldn’t have any sound data to work with. This would cause computeSpectrum to return me a null array.

6 Comments :, , , more...

Flex 3 Debugger anomaly

by Paul Taylor on Jan.02, 2009, under Development

Working today, I discovered the debugger does something silly with for loops. If you have code formatted like so:

var i:int = 0;
var foo:int = 3;
for(; i < foo; i++){
        //Code here
}


If you set a breakpoint on line 3, where the for loop is defined, the Flex debugger will only stop after it has been through one iteration of the loop. This caught me off guard, and for a minute I thought it was immediately incrementing the iterator. Only when I breakpointed on both the line of the for loop and on the first line inside my loop did I realize what was happening. The debugger stopped on the first line of my loop, not when it executed the condition the first time. This does not seem like standard debugger behavior at all. Does this happen to everyone? I know if you define the iterator inline, the debugger stops. Huh.

Leave a Comment :, , more...

Redirects from Jon Campos

by Paul Taylor on Dec.22, 2008, under Development

Hello everyone coming from Jon Campos’ blog post. Please excuse the messy (read: ugly) design of my blog at the moment. I’m redesigning it with a buddy of mine currently, and I’m stuck with whatever I could throw together in 10 minutes.

Here is a link to the example video player I made in PureMVC.

Here is a link to the presentation that I was going to give, if the projector hadn’t borked on me.

Hopefully you can follow my messy presentation style. If you have any questions, comments, or general feedback, feel free to post them in the comments section.

Leave a Comment :, , , more...

sweet rainbow pic…

by Paul Taylor on Oct.29, 2008, under Uncategorized

Dusty did this at 3 this morning because he needed to wake up and continue working on the project we’re doing.

I love it.

 

 

 

 

 

1 Comment more...

Get Adobe Flash playerPlugin by wpburn.com wordpress themes

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...