Tag Archives: actionscript

Stage3D & Flex Demo w/ Source

Back in the summer, I was lucky enough to get my hands on some early builds of Stage3D for mobile. I built some simple examples, including basic geometric shapes and simple 3D bubble charts inside of mobile Flex/AIR applications. I have been asked numerous times for the source code, and I’ve finally given in, and am sharing some source code.

I am not posting the full mobile application source code, since Stage3D for mobile is not yet available. However, I have ported the 3D bubble chart example to run in a Flex application targeting the desktop (Flash Player 11). The bubble chart example extends the concepts explored in the basic geometric shapes example.

Before you say “shoot, he didn’t give us the mobile code”, let me explain… When I ported the code from the mobile project to the desktop Flex project, all I changed was code specific to the mobile Flex framework. I changed <s:ViewNavigatorapplication> to <s:Application> and the corresponding architecture changes that were required, and I changed the list item renderers to Spark item renderers based on <s:Group> instead of mobile item renderers.   In the mobile item renderers, all my drawing logic was done using the ActionScript drawing API.  For simplicity in the port, I just used <s:Rect> to add the colored regions in the desktop variant.

That is all I changed!  

The stage3D code between the desktop and mobile implementations is identical.    You can see the desktop port in action in the video below:

Or, you can test it for yourself here:

The source code was intended to be exploratory at best… I was simply experimenting with hardware accelerated content, and how it can be used within your applications.   There is one big “gotcha” that you will have to watch out for if you want Stage3D content within a Flex application… Stage3D content shows up behind Flex content on the display list.   By default, Flex apps have a background color, and they will hide the Stage3D content.   If you want to display any Stage3D content within a Flex application (regardless of web, desktop AIR, or mobile), you must set the background alpha of the Flex application to zero (0).  Otherwise you will pull out some hair trying to figure out why it doesn’t show up.

The source code for the web/Flex port of this example is available at:

This also requires inclusion of the Away3D library, available at:

You can check out my original posts, showing Stage3D on mobile here:

You can also check out a video of this code running on a mobile device (Samsung Galaxy Tab 10.1) below:

Enjoy!

Object Orientation

Here’s another post that I originally wrote way back in 2006, when object oriented development was a newer concept to client-side web applications. Again, this post is still very relevant with Flex, AIR & ActionScript for mobile/web/desktop, so I decided to resurrect it from the old blog archive as well. Enjoy…

Understanding of OOP (Object Oriented Programming) is fundamental in being successful with the Flex framework and being able to get the most out of it. Developers who do not possess a computer science-related background may not be aware of the fundamental concepts that comprise OOP and how to apply them correctly, so here is a quick piece to help you out.

First, object oriented programming is a programming paradigm where your code is organized into logical objects, and each object has properties and methods. Each object contains similar and/or related functionality, and is organized into classes that logically represent and logically organize it’s functionality.

For Example:
Let’s say that we have a class “Automobile”. This class would contain the information and functions necessary for our application to use the Automobile class. We could have a numeric property for the number of wheels, the speed, and the direction (degrees on a compass). This class would also contain methods that control the actions of the Automobile object: accelerate, decelerate(break), turn, start engine, stop engine, etc… Our class would look something like this…

public class Automobile
{
	public var speed : Number;
	public var direction : Number;
	public var numWheels : Number;
	
	public function Automobile()
	{ /* constructor */ }
	
	public function accelerate() : void
	{ /* speed up the automobile */ }
	
	public function decelerate() : void
	{ /* slow down the automobile */ }
	
	public function turn( direction : Number ) : void
	{ /* turn the automobile */ }
	
	public function startEngine() : void
	{ /* start the automobile engine */ }
	
	public function stopEngine() : void
	{ /* stop the automobile engine */ }
}

Ok, now that we have a brief explanation of what object oriented programming is, we can get into some more aspects of OOP: inheritance and interfaces.

Inheritance is a way to form new objects based on existing objects. When a class inherits from a base class, the new class extends the functionality of the base class, and can utilize public and protected properties and methods from that base class. Inheritance can be used to create different objects that utilize functions within the base class, so that the child classes all utilize the same code base. Inheritance can be used to extend the functionality of existing objects, and inheritance can also be used to override and/ or change functionality from the base class.

In Actionscript 3, you can access the parent class of your class by using the “super” keyword. For instance, calling the constructor of the parent class would use “super()”, where accessing a method of the parent class would use something like: “super.myMethodName()”. If a property of the parent class is created with public or protected access, you can access that property in the child class directly by the property name (you would use this.propertyName, not super.propertyName).

Now, Lets take our Automobile example and apply object-oriented inheritance. We already have a base Automobile class that covers the basic functionality. We can create child classes that extend the functionality of the Automobile.

public class SportsCar extends Automobile
{
	public function SportsCar()
	{
		super();
	}
	
	override public function accelerate():void
	{
		/* we can override the accelerate function
		     so that it accelerates faster than the base
		     Automobile */
	}
}

and…

public class Truck extends Automobile
{
	public function Truck()
	{
		super();
	}
	
	public function tow() : void
	{
		/* we can add a tow function that
		   allows the Automobile class to tow
		   items. */ 
	}	
}

These classes extend the base functionality of the Automobile class, and therefore are instances of the Automobile class. If we have a function outside of the Automobile class, which takes an automobile as the parameter, both a SportsCar and Truck will work since they are both Automobiles. We could have a function such as the following: If we pass in a Truck Instance, and a SportsCar instance, both will work, and each will use the functionality of their specific class instead of the base Automobile class.

public function race( auto1 : Automobile, auto2 : Automobile ) : void
{
	auto1.accelerate();
	auto2.accelerate();
}

I’ll get into some more fine-grain details about inheritance later in this post… now, lets move on to interfaces…

Interfaces are slightly different than inheritance. An interface is a set of “rules” which an object must adhere to. The “rules” are actually method signatures that your class must implement. When we define an interface, we define method signatures that are required for classes that implement that interface. There is no actual code in an interface; it simply defines methods that must exist within your class. Your class that implements the interface must implement the code for the actual function. If you have multiple classes that implement an interface, those classes must have the same functions (only the ones required by the interface), but that is where the similarities of the two classes may stop. They could have completely different logic and properties within them… this is where inheritance and interfaces differ. Two objects that inherit from the same base class have a lot in common (properties and methods): two objects that implement the same interface only have those interface method signatures in common.

Let’s now make an Automobile Interface that defines the functions required to create an IAutomobile object (note the “I” stands for “interface”):

public interface IAutomobile
{
	function accelerate() : void;
	function decelerate() : void;
	function turn( direction : Number ) : void;
}

We can use the IAutomobile interface to create objects (classes) that behave as Automobile objects. These classes do not necessarily inherit from each other and do not necessarily share any common properties.

public class Car implements IAutomobile
{
	private var direction:Number;
	private var speed:Number;
	
	public function turn(direction:Number):void
	{
		this.direction = direction;
	}
	
	public function decelerate():void
	{
		this.speed++;
	}
	
	public function accelerate():void
	{
		this.speed--;
	}
}
<?xml version="1.0" encoding="utf-8"?>
<mx:Canvas implements="IAutomobile"
	xmlns:mx="http://www.adobe.com/2006/mxml">	
	<mx:Script>
		<![CDATA[

			private var direction:Number;
			private var speed:Number;
					
			public function turn(direction:Number):void
			{
				this.direction = direction;
			}
			
			public function decellerate():void
			{
				this.speed++;
			}
			
			public function accellerate():void
			{
				this.speed--;
			}
		]]>
	</mx:Script>
</mx:Canvas>

The previous two components both implement the IAutomobile interface, but have nothing else in common. One is simply a class that implements the interface, the other is a mxml component that implements the interface. The mxml component example extends the mx:Canvas component (the same thing could be done by creating an AS class that extends mx.containers.Canvas). Now, lets look at a function similar to the “race” function from earlier…

public function race( auto1 : IAutomobile, auto2 : IAutomobile ) : void
{
	auto1.accelerate();
	auto2.accelerate();
}

This example will work with either object that I have created because both objects implement the IAutomobile interface. They do not rely upon functions in the class hierarchy, just those that were implemented for this interface. You can also use multiple interfaces on classes that you create. Implementing multiple interfaces basically means that you are adding more required method signatures to your class, and you will have to implement these methods to satisfy each interface.

On the other hand, you cannot inherit from multiple classes. Some programming languages allow for multiple inheritance… ActionScript 3 does not support multiple inheritance (so i’ll stop there).

OK… enough of this rambling… What does this have to do with Flex?
Inheritance and interfaces are used extensively in AS3 to create the flex framework. All flex framework components that are rendered to the screen extend from the UIComponent class. AbstractService, DataSerice or EventDispatcher object implements the IEventDispatcher Interface. You may be using these concepts every day, but weren’t aware of them. Inheritance seems easier to take advanatage of at first… Lets say that you want to create several objects, all of which will have identical functions and variables. It is easy to see that you can create a base class that encapsulates all of the common functionality. You can then create a sub-classes that implement the differing functionality for each class.

When putting these concepts into real-world Flex applications you’ll need to get familiar with the following keywords:

extends
This is used when defining a child class from a parent class.

public class MyImage extends Image

implements
This is used when implementing an interface.

public class MyClass implements MyInterface

final
Classes and methods implented with “final” cannot be overridden.

final function myFunction() : void

static
The static keyword is used when creating variables or functions in a class that are specific to the class, not an instance. Static properties and methods do not require variable instantiation to be executed.

public static function myStaticFunction(): void
//to use it call it directly from ClassMyClass.myStaticFunction()

internal
This is used when creating a method or property that can be accessed by any object within the same package (namespace)

internal var foo : String;

override
This is used when creating a function that overrides another function from a parent class.

override public function myFunction() : void

private
This is used when creating methods or properties that are only available to the class where it is defined. A private variable cannot be accessed by outside classes or from descendant classes.

private var myPrivateValue : String;

protected
This is used when creating methods or properties that are only available to the class where it is defined and descendant classes. A protected variable cannot be accessed by outside classes.

protected var myProtectedValue : String;

public
This is used when creating properties and methods that are available to any class.

public var myPublicValue : String;

Getters & Setters vs. Public Properties

Here’s a post that I originally wrote way back in 2006, when Flex 2 was all the rage.   No, seriously, Flex 2 was awesome – it is the base of today’s Flex framework, helped to revolutionize applications on the web, and heralded the “RIA” frenzy.   The best part is that this post is still very relevant with Flex, AIR & ActionScript for mobile/web/desktop, so I decided to resurrect it from the old blog archive.  Enjoy…

I’ve been asked several times, why would you use get/set functions instead of public variables in your flex components and classes? Well, there are some great things you can do with getters and setters that you can’t do with public variables. On the other hand, there are cases where public variables may be an easy choice. When using these functions and/or public variables, the code for the caller will be the same:

mycomponent.myValue = 1;

First, lets look at public variables…

[Bindable]
public var myValue : Number

Public variables are useful when there are no addional actions that need to take place when the value has been changed. If you change the value of “myValue”, the bindings will update and everything will be handled accordingly. The value will change, and anything bound to that value will change. In this case, there is no need to use getter/setter methods, keeping code simple and easy to implement.

Now, on to getters and setters…

[Bindable(event="myValueUpdated")]
public function set myValue (value:Number):void
{
  _myValue = value;
  dispatchEvent( new FlexEvent( "myValueUpdated" ) );
}

public function get myValue ():Number
{
  return _myValue ;
}

private var _myValue : Number;

First I’ll explain the [Bindable(event=”myValueUpdated”)] statement: This indicates that the data binding to the getter’s value should be updated when the event of type “myValueUpdated” is dispatched.

You’ll notice that when the value is set, this event is dispatched, which would notify and components that are bound to this value. Using a binding event isn’t required for all getters and setters, however this approach can allow you to invoke binding events on the “getter” even if you don’t access the “setter” method.

Now, the rest… The code that I showed above is consumed in exactly the same way as a public property, but requires more code. The benefits of getter and setter functions are that they enable sequential code execution when the value is changed, and also enable inheritance in getter/setter methods.

This means that you can create your components so that specific functions are executed any time that the value is accessed using get and/or set functions.

Here’s an example:

[Bindable(event="myValueUpdated")]
public function set myValue (value:Number):void
{
  _myValue = value;
  numSets ++;
  myFunction();
  dispatchEvent( new FlexEvent( "myValueUpdated" ) );
}

public function get myValue ():Number
{
  numGets ++;
  myOtherFunction();
  return _myValue ;
}

private var _myValue : Number;
private var numGets : Number = 0;
private var numSets : Number = 0;

In this example, every time the value is set, the numSets Number is incremented, and the myFunction() function is executed. Likewise, every time the value is accessed using the “get” method, the numGets Number is incremented, and the myOtherFunction() function is executed. There is no limit to what kind of code you can execute here. You can have it dispatch custom events, change styles, create new components, etc… This turns out to be very handy when creating custom Flex components.

As I mentioned earlier, getter/setter accessors also enable inheritance on “properties” of an object. This means that you can change the behavior of a getter/setter in descendant classes, while usage remains the same. A great example of this are the “get data” and “set data” accessor methods used throughout the Flex framework (and part of the IDataRenderer interface). You can override “get data” or “set data” methods to modify behaviors and/or return values, without changing how those methods are used.